LLVM 23.0.0git
Verifier.cpp
Go to the documentation of this file.
1//===-- Verifier.cpp - Implement the Module Verifier -----------------------==//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the function verifier interface, that can be used for some
10// basic correctness checking of input to the system.
11//
12// Note that this does not provide full `Java style' security and verifications,
13// instead it just tries to ensure that code is well-formed.
14//
15// * Both of a binary operator's parameters are of the same type
16// * Verify that the indices of mem access instructions match other operands
17// * Verify that arithmetic and other things are only performed on first-class
18// types. Verify that shifts & logicals only happen on integrals f.e.
19// * All of the constants in a switch statement are of the correct type
20// * The code is in valid SSA form
21// * It should be illegal to put a label into any other type (like a structure)
22// or to return one. [except constant arrays!]
23// * Only phi nodes can be self referential: 'add i32 %0, %0 ; <int>:0' is bad
24// * PHI nodes must have an entry for each predecessor, with no extras.
25// * PHI nodes must be the first thing in a basic block, all grouped together
26// * All basic blocks should only end with terminator insts, not contain them
27// * The entry node to a function must not have predecessors
28// * All Instructions must be embedded into a basic block
29// * Functions cannot take a void-typed parameter
30// * Verify that a function's argument list agrees with it's declared type.
31// * It is illegal to specify a name for a void value.
32// * It is illegal to have a internal global value with no initializer
33// * It is illegal to have a ret instruction that returns a value that does not
34// agree with the function return value type.
35// * Function call argument types match the function prototype
36// * A landing pad is defined by a landingpad instruction, and can be jumped to
37// only by the unwind edge of an invoke instruction.
38// * A landingpad instruction must be the first non-PHI instruction in the
39// block.
40// * Landingpad instructions must be in a function with a personality function.
41// * Convergence control intrinsics are introduced in ConvergentOperations.rst.
42// The applied restrictions are too numerous to list here.
43// * The convergence entry intrinsic and the loop heart must be the first
44// non-PHI instruction in their respective block. This does not conflict with
45// the landing pads, since these two kinds cannot occur in the same block.
46// * All other things that are tested by asserts spread about the code...
47//
48//===----------------------------------------------------------------------===//
49
50#include "llvm/IR/Verifier.h"
51#include "llvm/ADT/APFloat.h"
52#include "llvm/ADT/APInt.h"
53#include "llvm/ADT/ArrayRef.h"
54#include "llvm/ADT/DenseMap.h"
55#include "llvm/ADT/MapVector.h"
56#include "llvm/ADT/STLExtras.h"
60#include "llvm/ADT/StringRef.h"
61#include "llvm/ADT/Twine.h"
63#include "llvm/IR/Argument.h"
65#include "llvm/IR/Attributes.h"
66#include "llvm/IR/BasicBlock.h"
67#include "llvm/IR/CFG.h"
68#include "llvm/IR/CallingConv.h"
69#include "llvm/IR/Comdat.h"
70#include "llvm/IR/Constant.h"
73#include "llvm/IR/Constants.h"
75#include "llvm/IR/DataLayout.h"
76#include "llvm/IR/DebugInfo.h"
78#include "llvm/IR/DebugLoc.h"
80#include "llvm/IR/Dominators.h"
82#include "llvm/IR/FPEnv.h"
83#include "llvm/IR/Function.h"
84#include "llvm/IR/GCStrategy.h"
86#include "llvm/IR/GlobalAlias.h"
87#include "llvm/IR/GlobalValue.h"
89#include "llvm/IR/InlineAsm.h"
90#include "llvm/IR/InstVisitor.h"
91#include "llvm/IR/InstrTypes.h"
92#include "llvm/IR/Instruction.h"
95#include "llvm/IR/Intrinsics.h"
96#include "llvm/IR/IntrinsicsAArch64.h"
97#include "llvm/IR/IntrinsicsAMDGPU.h"
98#include "llvm/IR/IntrinsicsARM.h"
99#include "llvm/IR/IntrinsicsNVPTX.h"
100#include "llvm/IR/IntrinsicsWebAssembly.h"
101#include "llvm/IR/LLVMContext.h"
103#include "llvm/IR/Metadata.h"
104#include "llvm/IR/Module.h"
106#include "llvm/IR/PassManager.h"
108#include "llvm/IR/Statepoint.h"
109#include "llvm/IR/Type.h"
110#include "llvm/IR/Use.h"
111#include "llvm/IR/User.h"
113#include "llvm/IR/Value.h"
115#include "llvm/Pass.h"
119#include "llvm/Support/Casting.h"
123#include "llvm/Support/ModRef.h"
127#include <algorithm>
128#include <cassert>
129#include <cstdint>
130#include <memory>
131#include <optional>
132#include <queue>
133#include <string>
134#include <utility>
135
136using namespace llvm;
137
139 "verify-noalias-scope-decl-dom", cl::Hidden, cl::init(false),
140 cl::desc("Ensure that llvm.experimental.noalias.scope.decl for identical "
141 "scopes are not dominating"));
142
145 const Module &M;
147 const Triple &TT;
150
151 /// Track the brokenness of the module while recursively visiting.
152 bool Broken = false;
153 /// Broken debug info can be "recovered" from by stripping the debug info.
154 bool BrokenDebugInfo = false;
155 /// Whether to treat broken debug info as an error.
157
159 : OS(OS), M(M), MST(&M), TT(M.getTargetTriple()), DL(M.getDataLayout()),
160 Context(M.getContext()) {}
161
162private:
163 void Write(const Module *M) {
164 *OS << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
165 }
166
167 void Write(const Value *V) {
168 if (V)
169 Write(*V);
170 }
171
172 void Write(const Value &V) {
173 if (isa<Instruction>(V)) {
174 V.print(*OS, MST);
175 *OS << '\n';
176 } else {
177 V.printAsOperand(*OS, true, MST);
178 *OS << '\n';
179 }
180 }
181
182 void Write(const DbgRecord *DR) {
183 if (DR) {
184 DR->print(*OS, MST, false);
185 *OS << '\n';
186 }
187 }
188
190 switch (Type) {
192 *OS << "value";
193 break;
195 *OS << "declare";
196 break;
198 *OS << "declare_value";
199 break;
201 *OS << "assign";
202 break;
204 *OS << "end";
205 break;
207 *OS << "any";
208 break;
209 };
210 }
211
212 void Write(const Metadata *MD) {
213 if (!MD)
214 return;
215 MD->print(*OS, MST, &M);
216 *OS << '\n';
217 }
218
219 template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) {
220 Write(MD.get());
221 }
222
223 void Write(const NamedMDNode *NMD) {
224 if (!NMD)
225 return;
226 NMD->print(*OS, MST);
227 *OS << '\n';
228 }
229
230 void Write(Type *T) {
231 if (!T)
232 return;
233 *OS << ' ' << *T;
234 }
235
236 void Write(const Comdat *C) {
237 if (!C)
238 return;
239 *OS << *C;
240 }
241
242 void Write(const APInt *AI) {
243 if (!AI)
244 return;
245 *OS << *AI << '\n';
246 }
247
248 void Write(const unsigned i) { *OS << i << '\n'; }
249
250 // NOLINTNEXTLINE(readability-identifier-naming)
251 void Write(const Attribute *A) {
252 if (!A)
253 return;
254 *OS << A->getAsString() << '\n';
255 }
256
257 // NOLINTNEXTLINE(readability-identifier-naming)
258 void Write(const AttributeSet *AS) {
259 if (!AS)
260 return;
261 *OS << AS->getAsString() << '\n';
262 }
263
264 // NOLINTNEXTLINE(readability-identifier-naming)
265 void Write(const AttributeList *AL) {
266 if (!AL)
267 return;
268 AL->print(*OS);
269 }
270
271 void Write(Printable P) { *OS << P << '\n'; }
272
273 template <typename T> void Write(ArrayRef<T> Vs) {
274 for (const T &V : Vs)
275 Write(V);
276 }
277
278 template <typename T1, typename... Ts>
279 void WriteTs(const T1 &V1, const Ts &... Vs) {
280 Write(V1);
281 WriteTs(Vs...);
282 }
283
284 template <typename... Ts> void WriteTs() {}
285
286public:
287 /// A check failed, so printout out the condition and the message.
288 ///
289 /// This provides a nice place to put a breakpoint if you want to see why
290 /// something is not correct.
291 void CheckFailed(const Twine &Message) {
292 if (OS)
293 *OS << Message << '\n';
294 Broken = true;
295 }
296
297 /// A check failed (with values to print).
298 ///
299 /// This calls the Message-only version so that the above is easier to set a
300 /// breakpoint on.
301 template <typename T1, typename... Ts>
302 void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
303 CheckFailed(Message);
304 if (OS)
305 WriteTs(V1, Vs...);
306 }
307
308 /// A debug info check failed.
309 void DebugInfoCheckFailed(const Twine &Message) {
310 if (OS)
311 *OS << Message << '\n';
313 BrokenDebugInfo = true;
314 }
315
316 /// A debug info check failed (with values to print).
317 template <typename T1, typename... Ts>
318 void DebugInfoCheckFailed(const Twine &Message, const T1 &V1,
319 const Ts &... Vs) {
320 DebugInfoCheckFailed(Message);
321 if (OS)
322 WriteTs(V1, Vs...);
323 }
324};
325
326namespace {
327
328class Verifier : public InstVisitor<Verifier>, VerifierSupport {
329 friend class InstVisitor<Verifier>;
330 DominatorTree DT;
331
332 /// When verifying a basic block, keep track of all of the
333 /// instructions we have seen so far.
334 ///
335 /// This allows us to do efficient dominance checks for the case when an
336 /// instruction has an operand that is an instruction in the same block.
337 SmallPtrSet<Instruction *, 16> InstsInThisBlock;
338
339 /// Keep track of the metadata nodes that have been checked already.
341
342 /// Keep track which DISubprogram is attached to which function.
344
345 /// Track all DICompileUnits visited.
347
348 /// The result type for a landingpad.
349 Type *LandingPadResultTy;
350
351 /// Whether we've seen a call to @llvm.localescape in this function
352 /// already.
353 bool SawFrameEscape;
354
355 /// Whether the current function has a DISubprogram attached to it.
356 bool HasDebugInfo = false;
357
358 /// Stores the count of how many objects were passed to llvm.localescape for a
359 /// given function and the largest index passed to llvm.localrecover.
361
362 // Maps catchswitches and cleanuppads that unwind to siblings to the
363 // terminators that indicate the unwind, used to detect cycles therein.
365
366 /// Cache which blocks are in which funclet, if an EH funclet personality is
367 /// in use. Otherwise empty.
368 DenseMap<BasicBlock *, ColorVector> BlockEHFuncletColors;
369
370 /// Cache of constants visited in search of ConstantExprs.
371 SmallPtrSet<const Constant *, 32> ConstantExprVisited;
372
373 /// Cache of declarations of the llvm.experimental.deoptimize.<ty> intrinsic.
374 SmallVector<const Function *, 4> DeoptimizeDeclarations;
375
376 /// Cache of attribute lists verified.
377 SmallPtrSet<const void *, 32> AttributeListsVisited;
378
379 // Verify that this GlobalValue is only used in this module.
380 // This map is used to avoid visiting uses twice. We can arrive at a user
381 // twice, if they have multiple operands. In particular for very large
382 // constant expressions, we can arrive at a particular user many times.
383 SmallPtrSet<const Value *, 32> GlobalValueVisited;
384
385 // Keeps track of duplicate function argument debug info.
387
388 TBAAVerifier TBAAVerifyHelper;
389 ConvergenceVerifier ConvergenceVerifyHelper;
390
391 SmallVector<IntrinsicInst *, 4> NoAliasScopeDecls;
392
393 void checkAtomicMemAccessSize(Type *Ty, const Instruction *I);
394
395public:
396 explicit Verifier(raw_ostream *OS, bool ShouldTreatBrokenDebugInfoAsError,
397 const Module &M)
398 : VerifierSupport(OS, M), LandingPadResultTy(nullptr),
399 SawFrameEscape(false), TBAAVerifyHelper(this) {
400 TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
401 }
402
403 bool hasBrokenDebugInfo() const { return BrokenDebugInfo; }
404
405 bool verify(const Function &F) {
406 llvm::TimeTraceScope timeScope("Verifier");
407 assert(F.getParent() == &M &&
408 "An instance of this class only works with a specific module!");
409
410 // First ensure the function is well-enough formed to compute dominance
411 // information, and directly compute a dominance tree. We don't rely on the
412 // pass manager to provide this as it isolates us from a potentially
413 // out-of-date dominator tree and makes it significantly more complex to run
414 // this code outside of a pass manager.
415
416 // First check that every basic block has a terminator, otherwise we can't
417 // even inspect the CFG.
418 for (const BasicBlock &BB : F) {
419 if (!BB.empty() && BB.back().isTerminator())
420 continue;
421
422 if (OS) {
423 *OS << "Basic Block in function '" << F.getName()
424 << "' does not have terminator!\n";
425 BB.printAsOperand(*OS, true, MST);
426 *OS << "\n";
427 }
428 return false;
429 }
430
431 // FIXME: It's really gross that we have to cast away constness here.
432 if (!F.empty())
433 DT.recalculate(const_cast<Function &>(F));
434
435 auto FailureCB = [this](const Twine &Message) {
436 this->CheckFailed(Message);
437 };
438 ConvergenceVerifyHelper.initialize(OS, FailureCB, F);
439
440 Broken = false;
441 // FIXME: We strip const here because the inst visitor strips const.
442 visit(const_cast<Function &>(F));
443 verifySiblingFuncletUnwinds();
444
445 if (ConvergenceVerifyHelper.sawTokens())
446 ConvergenceVerifyHelper.verify(DT);
447
448 InstsInThisBlock.clear();
449 DebugFnArgs.clear();
450 LandingPadResultTy = nullptr;
451 SawFrameEscape = false;
452 SiblingFuncletInfo.clear();
453 verifyNoAliasScopeDecl();
454 NoAliasScopeDecls.clear();
455
456 return !Broken;
457 }
458
459 /// Verify the module that this instance of \c Verifier was initialized with.
460 bool verify() {
461 Broken = false;
462
463 // Collect all declarations of the llvm.experimental.deoptimize intrinsic.
464 for (const Function &F : M)
465 if (F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
466 DeoptimizeDeclarations.push_back(&F);
467
468 // Now that we've visited every function, verify that we never asked to
469 // recover a frame index that wasn't escaped.
470 verifyFrameRecoverIndices();
471 for (const GlobalVariable &GV : M.globals())
472 visitGlobalVariable(GV);
473
474 for (const GlobalAlias &GA : M.aliases())
475 visitGlobalAlias(GA);
476
477 for (const GlobalIFunc &GI : M.ifuncs())
478 visitGlobalIFunc(GI);
479
480 for (const NamedMDNode &NMD : M.named_metadata())
481 visitNamedMDNode(NMD);
482
483 for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
484 visitComdat(SMEC.getValue());
485
486 visitModuleFlags();
487 visitModuleIdents();
488 visitModuleCommandLines();
489 visitModuleErrnoTBAA();
490
491 verifyCompileUnits();
492
493 verifyDeoptimizeCallingConvs();
494 DISubprogramAttachments.clear();
495 return !Broken;
496 }
497
498private:
499 /// Whether a metadata node is allowed to be, or contain, a DILocation.
500 enum class AreDebugLocsAllowed { No, Yes };
501
502 /// Metadata that should be treated as a range, with slightly different
503 /// requirements.
504 enum class RangeLikeMetadataKind {
505 Range, // MD_range
506 AbsoluteSymbol, // MD_absolute_symbol
507 NoaliasAddrspace // MD_noalias_addrspace
508 };
509
510 // Verification methods...
511 void visitGlobalValue(const GlobalValue &GV);
512 void visitGlobalVariable(const GlobalVariable &GV);
513 void visitGlobalAlias(const GlobalAlias &GA);
514 void visitGlobalIFunc(const GlobalIFunc &GI);
515 void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
516 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
517 const GlobalAlias &A, const Constant &C);
518 void visitNamedMDNode(const NamedMDNode &NMD);
519 void visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs);
520 void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
521 void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
522 void visitDIArgList(const DIArgList &AL, Function *F);
523 void visitComdat(const Comdat &C);
524 void visitModuleIdents();
525 void visitModuleCommandLines();
526 void visitModuleErrnoTBAA();
527 void visitModuleFlags();
528 void visitModuleFlag(const MDNode *Op,
529 DenseMap<const MDString *, const MDNode *> &SeenIDs,
530 SmallVectorImpl<const MDNode *> &Requirements);
531 void visitModuleFlagCGProfileEntry(const MDOperand &MDO);
532 void visitFunction(const Function &F);
533 void visitBasicBlock(BasicBlock &BB);
534 void verifyRangeLikeMetadata(const Value &V, const MDNode *Range, Type *Ty,
535 RangeLikeMetadataKind Kind);
536 void visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty);
537 void visitNoFPClassMetadata(Instruction &I, MDNode *Range, Type *Ty);
538 void visitNoaliasAddrspaceMetadata(Instruction &I, MDNode *Range, Type *Ty);
539 void visitDereferenceableMetadata(Instruction &I, MDNode *MD);
540 void visitNofreeMetadata(Instruction &I, MDNode *MD);
541 void visitProfMetadata(Instruction &I, MDNode *MD);
542 void visitCallStackMetadata(MDNode *MD);
543 void visitMemProfMetadata(Instruction &I, MDNode *MD);
544 void visitCallsiteMetadata(Instruction &I, MDNode *MD);
545 void visitCalleeTypeMetadata(Instruction &I, MDNode *MD);
546 void visitDIAssignIDMetadata(Instruction &I, MDNode *MD);
547 void visitMMRAMetadata(Instruction &I, MDNode *MD);
548 void visitAnnotationMetadata(MDNode *Annotation);
549 void visitAliasScopeMetadata(const MDNode *MD);
550 void visitAliasScopeListMetadata(const MDNode *MD);
551 void visitAccessGroupMetadata(const MDNode *MD);
552 void visitCapturesMetadata(Instruction &I, const MDNode *Captures);
553 void visitAllocTokenMetadata(Instruction &I, MDNode *MD);
554 void visitInlineHistoryMetadata(Instruction &I, MDNode *MD);
555 void visitMemCacheHintMetadata(Instruction &I, MDNode *MD);
556
557 template <class Ty> bool isValidMetadataArray(const MDTuple &N);
558#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
559#include "llvm/IR/Metadata.def"
560 void visitDIType(const DIType &N);
561 void visitDIScope(const DIScope &N);
562 void visitDIVariable(const DIVariable &N);
563 void visitDILexicalBlockBase(const DILexicalBlockBase &N);
564 void visitDITemplateParameter(const DITemplateParameter &N);
565
566 void visitTemplateParams(const MDNode &N, const Metadata &RawParams);
567
568 void visit(DbgLabelRecord &DLR);
569 void visit(DbgVariableRecord &DVR);
570 // InstVisitor overrides...
571 using InstVisitor<Verifier>::visit;
572 void visitDbgRecords(Instruction &I);
573 void visit(Instruction &I);
574
575 void visitTruncInst(TruncInst &I);
576 void visitZExtInst(ZExtInst &I);
577 void visitSExtInst(SExtInst &I);
578 void visitFPTruncInst(FPTruncInst &I);
579 void visitFPExtInst(FPExtInst &I);
580 void visitFPToUIInst(FPToUIInst &I);
581 void visitFPToSIInst(FPToSIInst &I);
582 void visitUIToFPInst(UIToFPInst &I);
583 void visitSIToFPInst(SIToFPInst &I);
584 void visitIntToPtrInst(IntToPtrInst &I);
585 void checkPtrToAddr(Type *SrcTy, Type *DestTy, const Value &V);
586 void visitPtrToAddrInst(PtrToAddrInst &I);
587 void visitPtrToIntInst(PtrToIntInst &I);
588 void visitBitCastInst(BitCastInst &I);
589 void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
590 void visitPHINode(PHINode &PN);
591 void visitCallBase(CallBase &Call);
592 void visitUnaryOperator(UnaryOperator &U);
593 void visitBinaryOperator(BinaryOperator &B);
594 void visitICmpInst(ICmpInst &IC);
595 void visitFCmpInst(FCmpInst &FC);
596 void visitExtractElementInst(ExtractElementInst &EI);
597 void visitInsertElementInst(InsertElementInst &EI);
598 void visitShuffleVectorInst(ShuffleVectorInst &EI);
599 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
600 void visitCallInst(CallInst &CI);
601 void visitInvokeInst(InvokeInst &II);
602 void visitGetElementPtrInst(GetElementPtrInst &GEP);
603 void visitLoadInst(LoadInst &LI);
604 void visitStoreInst(StoreInst &SI);
605 void verifyDominatesUse(Instruction &I, unsigned i);
606 void visitInstruction(Instruction &I);
607 void visitTerminator(Instruction &I);
608 void visitCondBrInst(CondBrInst &BI);
609 void visitReturnInst(ReturnInst &RI);
610 void visitSwitchInst(SwitchInst &SI);
611 void visitIndirectBrInst(IndirectBrInst &BI);
612 void visitCallBrInst(CallBrInst &CBI);
613 void visitSelectInst(SelectInst &SI);
614 void visitUserOp1(Instruction &I);
615 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
616 void visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call);
617 void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI);
618 void visitVPIntrinsic(VPIntrinsic &VPI);
619 void visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI);
620 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
621 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
622 void visitFenceInst(FenceInst &FI);
623 void visitAllocaInst(AllocaInst &AI);
624 void visitExtractValueInst(ExtractValueInst &EVI);
625 void visitInsertValueInst(InsertValueInst &IVI);
626 void visitEHPadPredecessors(Instruction &I);
627 void visitLandingPadInst(LandingPadInst &LPI);
628 void visitResumeInst(ResumeInst &RI);
629 void visitCatchPadInst(CatchPadInst &CPI);
630 void visitCatchReturnInst(CatchReturnInst &CatchReturn);
631 void visitCleanupPadInst(CleanupPadInst &CPI);
632 void visitFuncletPadInst(FuncletPadInst &FPI);
633 void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
634 void visitCleanupReturnInst(CleanupReturnInst &CRI);
635
636 void verifySwiftErrorCall(CallBase &Call, const Value *SwiftErrorVal);
637 void verifySwiftErrorValue(const Value *SwiftErrorVal);
638 void verifyTailCCMustTailAttrs(const AttrBuilder &Attrs, StringRef Context);
639 void verifyMustTailCall(CallInst &CI);
640 bool verifyAttributeCount(AttributeList Attrs, unsigned Params);
641 void verifyAttributeTypes(AttributeSet Attrs, const Value *V);
642 void verifyParameterAttrs(AttributeSet Attrs, Type *Ty, const Value *V);
643 void checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
644 const Value *V);
645 void verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
646 const Value *V, bool IsIntrinsic, bool IsInlineAsm);
647 void verifyFunctionMetadata(ArrayRef<std::pair<unsigned, MDNode *>> MDs);
648 void verifyUnknownProfileMetadata(MDNode *MD);
649 void visitConstantExprsRecursively(const Constant *EntryC);
650 void visitConstantExpr(const ConstantExpr *CE);
651 void visitConstantPtrAuth(const ConstantPtrAuth *CPA);
652 void verifyInlineAsmCall(const CallBase &Call);
653 void verifyStatepoint(const CallBase &Call);
654 void verifyFrameRecoverIndices();
655 void verifySiblingFuncletUnwinds();
656
657 void verifyFragmentExpression(const DbgVariableRecord &I);
658 template <typename ValueOrMetadata>
659 void verifyFragmentExpression(const DIVariable &V,
661 ValueOrMetadata *Desc);
662 void verifyFnArgs(const DbgVariableRecord &DVR);
663 void verifyNotEntryValue(const DbgVariableRecord &I);
664
665 /// Module-level debug info verification...
666 void verifyCompileUnits();
667
668 /// Module-level verification that all @llvm.experimental.deoptimize
669 /// declarations share the same calling convention.
670 void verifyDeoptimizeCallingConvs();
671
672 void verifyAttachedCallBundle(const CallBase &Call,
673 const OperandBundleUse &BU);
674
675 /// Verify the llvm.experimental.noalias.scope.decl declarations
676 void verifyNoAliasScopeDecl();
677};
678
679} // end anonymous namespace
680
681/// We know that cond should be true, if not print an error message.
682#define Check(C, ...) \
683 do { \
684 if (!(C)) { \
685 CheckFailed(__VA_ARGS__); \
686 return; \
687 } \
688 } while (false)
689
690/// We know that a debug info condition should be true, if not print
691/// an error message.
692#define CheckDI(C, ...) \
693 do { \
694 if (!(C)) { \
695 DebugInfoCheckFailed(__VA_ARGS__); \
696 return; \
697 } \
698 } while (false)
699
700void Verifier::visitDbgRecords(Instruction &I) {
701 if (!I.DebugMarker)
702 return;
703 CheckDI(I.DebugMarker->MarkedInstr == &I,
704 "Instruction has invalid DebugMarker", &I);
705 CheckDI(!isa<PHINode>(&I) || !I.hasDbgRecords(),
706 "PHI Node must not have any attached DbgRecords", &I);
707 for (DbgRecord &DR : I.getDbgRecordRange()) {
708 CheckDI(DR.getMarker() == I.DebugMarker,
709 "DbgRecord had invalid DebugMarker", &I, &DR);
710 if (auto *Loc =
712 visitMDNode(*Loc, AreDebugLocsAllowed::Yes);
713 if (auto *DVR = dyn_cast<DbgVariableRecord>(&DR)) {
714 visit(*DVR);
715 // These have to appear after `visit` for consistency with existing
716 // intrinsic behaviour.
717 verifyFragmentExpression(*DVR);
718 verifyNotEntryValue(*DVR);
719 } else if (auto *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
720 visit(*DLR);
721 }
722 }
723}
724
725void Verifier::visit(Instruction &I) {
726 visitDbgRecords(I);
727 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
728 Check(I.getOperand(i) != nullptr, "Operand is null", &I);
730}
731
732// Helper to iterate over indirect users. By returning false, the callback can ask to stop traversing further.
733static void forEachUser(const Value *User,
735 llvm::function_ref<bool(const Value *)> Callback) {
736 if (!Visited.insert(User).second)
737 return;
738
740 while (!WorkList.empty()) {
741 const Value *Cur = WorkList.pop_back_val();
742 if (!Visited.insert(Cur).second)
743 continue;
744 if (Callback(Cur))
745 append_range(WorkList, Cur->materialized_users());
746 }
747}
748
749void Verifier::visitGlobalValue(const GlobalValue &GV) {
751 "Global is external, but doesn't have external or weak linkage!", &GV);
752
753 if (const GlobalObject *GO = dyn_cast<GlobalObject>(&GV)) {
754 if (const MDNode *Associated =
755 GO->getMetadata(LLVMContext::MD_associated)) {
756 Check(Associated->getNumOperands() == 1,
757 "associated metadata must have one operand", &GV, Associated);
758 const Metadata *Op = Associated->getOperand(0).get();
759 Check(Op, "associated metadata must have a global value", GO, Associated);
760
761 const auto *VM = dyn_cast_or_null<ValueAsMetadata>(Op);
762 Check(VM, "associated metadata must be ValueAsMetadata", GO, Associated);
763 if (VM) {
764 Check(isa<PointerType>(VM->getValue()->getType()),
765 "associated value must be pointer typed", GV, Associated);
766
767 const Value *Stripped = VM->getValue()->stripPointerCastsAndAliases();
768 Check(isa<GlobalObject>(Stripped) || isa<Constant>(Stripped),
769 "associated metadata must point to a GlobalObject", GO, Stripped);
770 Check(Stripped != GO,
771 "global values should not associate to themselves", GO,
772 Associated);
773 }
774 }
775
776 // FIXME: Why is getMetadata on GlobalValue protected?
777 if (const MDNode *AbsoluteSymbol =
778 GO->getMetadata(LLVMContext::MD_absolute_symbol)) {
779 verifyRangeLikeMetadata(*GO, AbsoluteSymbol,
780 DL.getIntPtrType(GO->getType()),
781 RangeLikeMetadataKind::AbsoluteSymbol);
782 }
783
784 if (GO->hasMetadata(LLVMContext::MD_implicit_ref)) {
785 Check(!GO->isDeclaration(),
786 "ref metadata must not be placed on a declaration", GO);
787
789 GO->getMetadata(LLVMContext::MD_implicit_ref, MDs);
790 for (const MDNode *MD : MDs) {
791 Check(MD->getNumOperands() == 1, "ref metadata must have one operand",
792 &GV, MD);
793 const Metadata *Op = MD->getOperand(0).get();
794 const auto *VM = dyn_cast_or_null<ValueAsMetadata>(Op);
795 Check(VM, "ref metadata must be ValueAsMetadata", GO, MD);
796 if (VM) {
797 Check(isa<PointerType>(VM->getValue()->getType()),
798 "ref value must be pointer typed", GV, MD);
799
800 const Value *Stripped = VM->getValue()->stripPointerCastsAndAliases();
801 Check(isa<GlobalObject>(Stripped) || isa<Constant>(Stripped),
802 "ref metadata must point to a GlobalObject", GO, Stripped);
803 Check(Stripped != GO, "values should not reference themselves", GO,
804 MD);
805 }
806 }
807 }
808
809 if (auto *Props = GO->getMetadata(LLVMContext::MD_elf_section_properties)) {
810 Check(Props->getNumOperands() == 2,
811 "elf_section_properties metadata must have two operands", GO,
812 Props);
813 if (Props->getNumOperands() == 2) {
814 auto *Type = dyn_cast<ConstantAsMetadata>(Props->getOperand(0));
815 Check(Type, "type field must be ConstantAsMetadata", GO, Props);
816 auto *TypeInt = dyn_cast<ConstantInt>(Type->getValue());
817 Check(TypeInt, "type field must be ConstantInt", GO, Props);
818
819 auto *Entsize = dyn_cast<ConstantAsMetadata>(Props->getOperand(1));
820 Check(Entsize, "entsize field must be ConstantAsMetadata", GO, Props);
821 auto *EntsizeInt = dyn_cast<ConstantInt>(Entsize->getValue());
822 Check(EntsizeInt, "entsize field must be ConstantInt", GO, Props);
823 }
824 }
825 }
826
828 "Only global variables can have appending linkage!", &GV);
829
830 if (GV.hasAppendingLinkage()) {
831 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
832 Check(GVar && GVar->getValueType()->isArrayTy(),
833 "Only global arrays can have appending linkage!", GVar);
834 }
835
836 if (GV.isDeclarationForLinker())
837 Check(!GV.hasComdat(), "Declaration may not be in a Comdat!", &GV);
838
839 if (GV.hasDLLExportStorageClass()) {
841 "dllexport GlobalValue must have default or protected visibility",
842 &GV);
843 }
844 if (GV.hasDLLImportStorageClass()) {
846 "dllimport GlobalValue must have default visibility", &GV);
847 Check(!GV.isDSOLocal(), "GlobalValue with DLLImport Storage is dso_local!",
848 &GV);
849
850 Check((GV.isDeclaration() &&
853 "Global is marked as dllimport, but not external", &GV);
854 }
855
856 if (GV.isImplicitDSOLocal())
857 Check(GV.isDSOLocal(),
858 "GlobalValue with local linkage or non-default "
859 "visibility must be dso_local!",
860 &GV);
861
862 forEachUser(&GV, GlobalValueVisited, [&](const Value *V) -> bool {
863 if (const Instruction *I = dyn_cast<Instruction>(V)) {
864 if (!I->getParent() || !I->getParent()->getParent())
865 CheckFailed("Global is referenced by parentless instruction!", &GV, &M,
866 I);
867 else if (I->getParent()->getParent()->getParent() != &M)
868 CheckFailed("Global is referenced in a different module!", &GV, &M, I,
869 I->getParent()->getParent(),
870 I->getParent()->getParent()->getParent());
871 return false;
872 } else if (const Function *F = dyn_cast<Function>(V)) {
873 if (F->getParent() != &M)
874 CheckFailed("Global is used by function in a different module", &GV, &M,
875 F, F->getParent());
876 return false;
877 }
878 return true;
879 });
880}
881
882void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
883 Type *GVType = GV.getValueType();
884
885 if (MaybeAlign A = GV.getAlign()) {
886 Check(A->value() <= Value::MaximumAlignment,
887 "huge alignment values are unsupported", &GV);
888 }
889
890 if (GV.hasInitializer()) {
891 Check(GV.getInitializer()->getType() == GVType,
892 "Global variable initializer type does not match global "
893 "variable type!",
894 &GV);
896 "Global variable initializer must be sized", &GV);
897 visitConstantExprsRecursively(GV.getInitializer());
898 // If the global has common linkage, it must have a zero initializer and
899 // cannot be constant.
900 if (GV.hasCommonLinkage()) {
902 "'common' global must have a zero initializer!", &GV);
903 Check(!GV.isConstant(), "'common' global may not be marked constant!",
904 &GV);
905 Check(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
906 }
907 }
908
909 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
910 GV.getName() == "llvm.global_dtors")) {
912 "invalid linkage for intrinsic global variable", &GV);
914 "invalid uses of intrinsic global variable", &GV);
915
916 // Don't worry about emitting an error for it not being an array,
917 // visitGlobalValue will complain on appending non-array.
918 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
919 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
920 PointerType *FuncPtrTy =
921 PointerType::get(Context, DL.getProgramAddressSpace());
922 Check(STy && (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
923 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
924 STy->getTypeAtIndex(1) == FuncPtrTy,
925 "wrong type for intrinsic global variable", &GV);
926 Check(STy->getNumElements() == 3,
927 "the third field of the element type is mandatory, "
928 "specify ptr null to migrate from the obsoleted 2-field form");
929 Type *ETy = STy->getTypeAtIndex(2);
930 Check(ETy->isPointerTy(), "wrong type for intrinsic global variable",
931 &GV);
932 }
933 }
934
935 if (GV.hasName() && (GV.getName() == "llvm.used" ||
936 GV.getName() == "llvm.compiler.used")) {
938 "invalid linkage for intrinsic global variable", &GV);
940 "invalid uses of intrinsic global variable", &GV);
941
942 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
943 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
944 Check(PTy, "wrong type for intrinsic global variable", &GV);
945 if (GV.hasInitializer()) {
946 const Constant *Init = GV.getInitializer();
947 const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
948 Check(InitArray, "wrong initializer for intrinsic global variable",
949 Init);
950 for (Value *Op : InitArray->operands()) {
951 Value *V = Op->stripPointerCasts();
954 Twine("invalid ") + GV.getName() + " member", V);
955 Check(V->hasName(),
956 Twine("members of ") + GV.getName() + " must be named", V);
957 }
958 }
959 }
960 }
961
962 // Visit any debug info attachments.
964 GV.getMetadata(LLVMContext::MD_dbg, MDs);
965 for (auto *MD : MDs) {
966 if (auto *GVE = dyn_cast<DIGlobalVariableExpression>(MD))
967 visitDIGlobalVariableExpression(*GVE);
968 else
969 CheckDI(false, "!dbg attachment of global variable must be a "
970 "DIGlobalVariableExpression");
971 }
972
973 // Scalable vectors cannot be global variables, since we don't know
974 // the runtime size.
975 Check(!GVType->isScalableTy(), "Globals cannot contain scalable types", &GV);
976
977 // Check if it is or contains a target extension type that disallows being
978 // used as a global.
980 "Global @" + GV.getName() + " has illegal target extension type",
981 GVType);
982
983 // Check that the the address space can hold all bits of the type, recognized
984 // by an access in the address space being able to reach all bytes of the
985 // type.
986 Check(!GVType->isSized() ||
987 isUIntN(DL.getAddressSizeInBits(GV.getAddressSpace()),
988 GV.getGlobalSize(DL)),
989 "Global variable is too large to fit into the address space", &GV,
990 GVType);
991
992 if (!GV.hasInitializer()) {
993 visitGlobalValue(GV);
994 return;
995 }
996
997 // Walk any aggregate initializers looking for bitcasts between address spaces
998 visitConstantExprsRecursively(GV.getInitializer());
999
1000 visitGlobalValue(GV);
1001}
1002
1003void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
1004 SmallPtrSet<const GlobalAlias*, 4> Visited;
1005 Visited.insert(&GA);
1006 visitAliaseeSubExpr(Visited, GA, C);
1007}
1008
1009void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
1010 const GlobalAlias &GA, const Constant &C) {
1013 cast<GlobalValue>(C).hasAvailableExternallyLinkage(),
1014 "available_externally alias must point to available_externally "
1015 "global value",
1016 &GA);
1017 }
1018 if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
1020 Check(!GV->isDeclarationForLinker(), "Alias must point to a definition",
1021 &GA);
1022 }
1023
1024 if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
1025 Check(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
1026
1027 Check(!GA2->isInterposable(),
1028 "Alias cannot point to an interposable alias", &GA);
1029 } else {
1030 // Only continue verifying subexpressions of GlobalAliases.
1031 // Do not recurse into global initializers.
1032 return;
1033 }
1034 }
1035
1036 if (const auto *CE = dyn_cast<ConstantExpr>(&C))
1037 visitConstantExprsRecursively(CE);
1038
1039 for (const Use &U : C.operands()) {
1040 Value *V = &*U;
1041 if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
1042 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
1043 else if (const auto *C2 = dyn_cast<Constant>(V))
1044 visitAliaseeSubExpr(Visited, GA, *C2);
1045 }
1046}
1047
1048void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
1050 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
1051 "weak_odr, external, or available_externally linkage!",
1052 &GA);
1053 const Constant *Aliasee = GA.getAliasee();
1054 Check(Aliasee, "Aliasee cannot be NULL!", &GA);
1055 Check(GA.getType() == Aliasee->getType(),
1056 "Alias and aliasee types should match!", &GA);
1057
1058 Check(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
1059 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
1060
1061 visitAliaseeSubExpr(GA, *Aliasee);
1062
1063 visitGlobalValue(GA);
1064}
1065
1066void Verifier::visitGlobalIFunc(const GlobalIFunc &GI) {
1067 visitGlobalValue(GI);
1068
1070 GI.getAllMetadata(MDs);
1071 for (const auto &I : MDs) {
1072 CheckDI(I.first != LLVMContext::MD_dbg,
1073 "an ifunc may not have a !dbg attachment", &GI);
1074 Check(I.first != LLVMContext::MD_prof,
1075 "an ifunc may not have a !prof attachment", &GI);
1076 visitMDNode(*I.second, AreDebugLocsAllowed::No);
1077 }
1078
1080 "IFunc should have private, internal, linkonce, weak, linkonce_odr, "
1081 "weak_odr, or external linkage!",
1082 &GI);
1083 // Pierce through ConstantExprs and GlobalAliases and check that the resolver
1084 // is a Function definition.
1085 const Function *Resolver = GI.getResolverFunction();
1086 Check(Resolver, "IFunc must have a Function resolver", &GI);
1087 Check(!Resolver->isDeclarationForLinker(),
1088 "IFunc resolver must be a definition", &GI);
1089
1090 // Check that the immediate resolver operand (prior to any bitcasts) has the
1091 // correct type.
1092 const Type *ResolverTy = GI.getResolver()->getType();
1093
1095 "IFunc resolver must return a pointer", &GI);
1096
1097 Check(ResolverTy == PointerType::get(Context, GI.getAddressSpace()),
1098 "IFunc resolver has incorrect type", &GI);
1099}
1100
1101void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
1102 // There used to be various other llvm.dbg.* nodes, but we don't support
1103 // upgrading them and we want to reserve the namespace for future uses.
1104 if (NMD.getName().starts_with("llvm.dbg."))
1105 CheckDI(NMD.getName() == "llvm.dbg.cu",
1106 "unrecognized named metadata node in the llvm.dbg namespace", &NMD);
1107 for (const MDNode *MD : NMD.operands()) {
1108 if (NMD.getName() == "llvm.dbg.cu")
1109 CheckDI(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD);
1110
1111 if (!MD)
1112 continue;
1113
1114 visitMDNode(*MD, AreDebugLocsAllowed::Yes);
1115 }
1116}
1117
1118void Verifier::visitMDNode(const MDNode &BaseMD,
1119 AreDebugLocsAllowed AllowLocs) {
1120 // Only visit each node once. Metadata can be mutually recursive, so this
1121 // avoids infinite recursion here, as well as being an optimization.
1122 if (!MDNodes.insert(&BaseMD).second)
1123 return;
1124
1125 std::queue<const MDNode *> Worklist;
1126 Worklist.push(&BaseMD);
1127
1128 while (!Worklist.empty()) {
1129 const MDNode *CurrentMD = Worklist.front();
1130 Worklist.pop();
1131 Check(&CurrentMD->getContext() == &Context,
1132 "MDNode context does not match Module context!", CurrentMD);
1133
1134 switch (CurrentMD->getMetadataID()) {
1135 default:
1136 llvm_unreachable("Invalid MDNode subclass");
1137 case Metadata::MDTupleKind:
1138 break;
1139#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
1140 case Metadata::CLASS##Kind: \
1141 visit##CLASS(cast<CLASS>(*CurrentMD)); \
1142 break;
1143#include "llvm/IR/Metadata.def"
1144 }
1145
1146 for (const Metadata *Op : CurrentMD->operands()) {
1147 if (!Op)
1148 continue;
1149 Check(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
1150 CurrentMD, Op);
1151 CheckDI(!isa<DILocation>(Op) || AllowLocs == AreDebugLocsAllowed::Yes,
1152 "DILocation not allowed within this metadata node", CurrentMD,
1153 Op);
1154 if (auto *N = dyn_cast<MDNode>(Op)) {
1155 if (MDNodes.insert(N).second)
1156 Worklist.push(N);
1157 continue;
1158 }
1159 if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
1160 visitValueAsMetadata(*V, nullptr);
1161 continue;
1162 }
1163 }
1164
1165 // Check llvm.loop.estimated_trip_count.
1166 if (CurrentMD->getNumOperands() > 0 &&
1168 Check(CurrentMD->getNumOperands() == 2, "Expected two operands",
1169 CurrentMD);
1170 auto *Count =
1172 Check(Count && Count->getType()->isIntegerTy() &&
1173 cast<IntegerType>(Count->getType())->getBitWidth() <= 32,
1174 "Expected second operand to be an integer constant of type i32 or "
1175 "smaller",
1176 CurrentMD);
1177 }
1178
1179 // Check these last, so we diagnose problems in operands first.
1180 Check(!CurrentMD->isTemporary(), "Expected no forward declarations!",
1181 CurrentMD);
1182 Check(CurrentMD->isResolved(), "All nodes should be resolved!", CurrentMD);
1183 }
1184}
1185
1186void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
1187 Check(MD.getValue(), "Expected valid value", &MD);
1188 Check(!MD.getValue()->getType()->isMetadataTy(),
1189 "Unexpected metadata round-trip through values", &MD, MD.getValue());
1190
1191 auto *L = dyn_cast<LocalAsMetadata>(&MD);
1192 if (!L)
1193 return;
1194
1195 Check(F, "function-local metadata used outside a function", L);
1196
1197 // If this was an instruction, bb, or argument, verify that it is in the
1198 // function that we expect.
1199 Function *ActualF = nullptr;
1200 if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
1201 Check(I->getParent(), "function-local metadata not in basic block", L, I);
1202 ActualF = I->getParent()->getParent();
1203 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
1204 ActualF = BB->getParent();
1205 else if (Argument *A = dyn_cast<Argument>(L->getValue()))
1206 ActualF = A->getParent();
1207 assert(ActualF && "Unimplemented function local metadata case!");
1208
1209 Check(ActualF == F, "function-local metadata used in wrong function", L);
1210}
1211
1212void Verifier::visitDIArgList(const DIArgList &AL, Function *F) {
1213 for (const ValueAsMetadata *VAM : AL.getArgs())
1214 visitValueAsMetadata(*VAM, F);
1215}
1216
1217void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
1218 Metadata *MD = MDV.getMetadata();
1219 if (auto *N = dyn_cast<MDNode>(MD)) {
1220 visitMDNode(*N, AreDebugLocsAllowed::No);
1221 return;
1222 }
1223
1224 // Only visit each node once. Metadata can be mutually recursive, so this
1225 // avoids infinite recursion here, as well as being an optimization.
1226 if (!MDNodes.insert(MD).second)
1227 return;
1228
1229 if (auto *V = dyn_cast<ValueAsMetadata>(MD))
1230 visitValueAsMetadata(*V, F);
1231
1232 if (auto *AL = dyn_cast<DIArgList>(MD))
1233 visitDIArgList(*AL, F);
1234}
1235
1236static bool isType(const Metadata *MD) { return !MD || isa<DIType>(MD); }
1237static bool isScope(const Metadata *MD) { return !MD || isa<DIScope>(MD); }
1238static bool isDINode(const Metadata *MD) { return !MD || isa<DINode>(MD); }
1239static bool isMDTuple(const Metadata *MD) { return !MD || isa<MDTuple>(MD); }
1240
1241void Verifier::visitDILocation(const DILocation &N) {
1242 CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1243 "location requires a valid scope", &N, N.getRawScope());
1244 if (auto *IA = N.getRawInlinedAt())
1245 CheckDI(isa<DILocation>(IA), "inlined-at should be a location", &N, IA);
1246 if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
1247 CheckDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
1248}
1249
1250void Verifier::visitGenericDINode(const GenericDINode &N) {
1251 CheckDI(N.getTag(), "invalid tag", &N);
1252}
1253
1254void Verifier::visitDIScope(const DIScope &N) {
1255 if (auto *F = N.getRawFile())
1256 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1257}
1258
1259void Verifier::visitDIType(const DIType &N) {
1260 CheckDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
1261 visitDIScope(N);
1262 CheckDI(N.getRawFile() || N.getLine() == 0, "line specified with no file", &N,
1263 N.getLine());
1264}
1265
1266void Verifier::visitDISubrangeType(const DISubrangeType &N) {
1267 visitDIType(N);
1268
1269 CheckDI(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
1270 auto *BaseType = N.getRawBaseType();
1271 CheckDI(!BaseType || isType(BaseType), "BaseType must be a type");
1272 auto *LBound = N.getRawLowerBound();
1273 CheckDI(!LBound || isa<ConstantAsMetadata>(LBound) ||
1274 isa<DIVariable>(LBound) || isa<DIExpression>(LBound) ||
1275 isa<DIDerivedType>(LBound),
1276 "LowerBound must be signed constant or DIVariable or DIExpression or "
1277 "DIDerivedType",
1278 &N);
1279 auto *UBound = N.getRawUpperBound();
1280 CheckDI(!UBound || isa<ConstantAsMetadata>(UBound) ||
1281 isa<DIVariable>(UBound) || isa<DIExpression>(UBound) ||
1282 isa<DIDerivedType>(UBound),
1283 "UpperBound must be signed constant or DIVariable or DIExpression or "
1284 "DIDerivedType",
1285 &N);
1286 auto *Stride = N.getRawStride();
1287 CheckDI(!Stride || isa<ConstantAsMetadata>(Stride) ||
1288 isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
1289 "Stride must be signed constant or DIVariable or DIExpression", &N);
1290 auto *Bias = N.getRawBias();
1291 CheckDI(!Bias || isa<ConstantAsMetadata>(Bias) || isa<DIVariable>(Bias) ||
1292 isa<DIExpression>(Bias),
1293 "Bias must be signed constant or DIVariable or DIExpression", &N);
1294 // Subrange types currently only support constant size.
1295 auto *Size = N.getRawSizeInBits();
1297 "SizeInBits must be a constant");
1298}
1299
1300void Verifier::visitDISubrange(const DISubrange &N) {
1301 CheckDI(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
1302 CheckDI(!N.getRawCountNode() || !N.getRawUpperBound(),
1303 "Subrange can have any one of count or upperBound", &N);
1304 auto *CBound = N.getRawCountNode();
1305 CheckDI(!CBound || isa<ConstantAsMetadata>(CBound) ||
1306 isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
1307 "Count must be signed constant or DIVariable or DIExpression", &N);
1308 auto Count = N.getCount();
1310 cast<ConstantInt *>(Count)->getSExtValue() >= -1,
1311 "invalid subrange count", &N);
1312 auto *LBound = N.getRawLowerBound();
1313 CheckDI(!LBound || isa<ConstantAsMetadata>(LBound) ||
1314 isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
1315 "LowerBound must be signed constant or DIVariable or DIExpression",
1316 &N);
1317 auto *UBound = N.getRawUpperBound();
1318 CheckDI(!UBound || isa<ConstantAsMetadata>(UBound) ||
1319 isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
1320 "UpperBound must be signed constant or DIVariable or DIExpression",
1321 &N);
1322 auto *Stride = N.getRawStride();
1323 CheckDI(!Stride || isa<ConstantAsMetadata>(Stride) ||
1324 isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
1325 "Stride must be signed constant or DIVariable or DIExpression", &N);
1326}
1327
1328void Verifier::visitDIGenericSubrange(const DIGenericSubrange &N) {
1329 CheckDI(N.getTag() == dwarf::DW_TAG_generic_subrange, "invalid tag", &N);
1330 CheckDI(!N.getRawCountNode() || !N.getRawUpperBound(),
1331 "GenericSubrange can have any one of count or upperBound", &N);
1332 auto *CBound = N.getRawCountNode();
1333 CheckDI(!CBound || isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
1334 "Count must be signed constant or DIVariable or DIExpression", &N);
1335 auto *LBound = N.getRawLowerBound();
1336 CheckDI(LBound, "GenericSubrange must contain lowerBound", &N);
1337 CheckDI(isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
1338 "LowerBound must be signed constant or DIVariable or DIExpression",
1339 &N);
1340 auto *UBound = N.getRawUpperBound();
1341 CheckDI(!UBound || isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
1342 "UpperBound must be signed constant or DIVariable or DIExpression",
1343 &N);
1344 auto *Stride = N.getRawStride();
1345 CheckDI(Stride, "GenericSubrange must contain stride", &N);
1346 CheckDI(isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
1347 "Stride must be signed constant or DIVariable or DIExpression", &N);
1348}
1349
1350void Verifier::visitDIEnumerator(const DIEnumerator &N) {
1351 CheckDI(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
1352}
1353
1354void Verifier::visitDIBasicType(const DIBasicType &N) {
1355 visitDIType(N);
1356
1357 CheckDI(N.getTag() == dwarf::DW_TAG_base_type ||
1358 N.getTag() == dwarf::DW_TAG_unspecified_type ||
1359 N.getTag() == dwarf::DW_TAG_string_type,
1360 "invalid tag", &N);
1361 // Basic types currently only support constant size.
1362 auto *Size = N.getRawSizeInBits();
1364 "SizeInBits must be a constant");
1365}
1366
1367void Verifier::visitDIFixedPointType(const DIFixedPointType &N) {
1368 visitDIBasicType(N);
1369
1370 CheckDI(N.getTag() == dwarf::DW_TAG_base_type, "invalid tag", &N);
1371 CheckDI(N.getEncoding() == dwarf::DW_ATE_signed_fixed ||
1372 N.getEncoding() == dwarf::DW_ATE_unsigned_fixed,
1373 "invalid encoding", &N);
1377 "invalid kind", &N);
1379 N.getFactorRaw() == 0,
1380 "factor should be 0 for rationals", &N);
1382 (N.getNumeratorRaw() == 0 && N.getDenominatorRaw() == 0),
1383 "numerator and denominator should be 0 for non-rationals", &N);
1384}
1385
1386void Verifier::visitDIStringType(const DIStringType &N) {
1387 visitDIType(N);
1388
1389 CheckDI(N.getTag() == dwarf::DW_TAG_string_type, "invalid tag", &N);
1390 CheckDI(!(N.isBigEndian() && N.isLittleEndian()), "has conflicting flags",
1391 &N);
1392}
1393
1394void Verifier::visitDIDerivedType(const DIDerivedType &N) {
1395 // Common type checks.
1396 visitDIType(N);
1397
1398 CheckDI(N.getTag() == dwarf::DW_TAG_typedef ||
1399 N.getTag() == dwarf::DW_TAG_pointer_type ||
1400 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
1401 N.getTag() == dwarf::DW_TAG_reference_type ||
1402 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
1403 N.getTag() == dwarf::DW_TAG_const_type ||
1404 N.getTag() == dwarf::DW_TAG_immutable_type ||
1405 N.getTag() == dwarf::DW_TAG_volatile_type ||
1406 N.getTag() == dwarf::DW_TAG_restrict_type ||
1407 N.getTag() == dwarf::DW_TAG_atomic_type ||
1408 N.getTag() == dwarf::DW_TAG_LLVM_ptrauth_type ||
1409 N.getTag() == dwarf::DW_TAG_member ||
1410 (N.getTag() == dwarf::DW_TAG_variable && N.isStaticMember()) ||
1411 N.getTag() == dwarf::DW_TAG_inheritance ||
1412 N.getTag() == dwarf::DW_TAG_friend ||
1413 N.getTag() == dwarf::DW_TAG_set_type ||
1414 N.getTag() == dwarf::DW_TAG_template_alias,
1415 "invalid tag", &N);
1416 if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
1417 CheckDI(isType(N.getRawExtraData()), "invalid pointer to member type", &N,
1418 N.getRawExtraData());
1419 } else if (N.getTag() == dwarf::DW_TAG_template_alias) {
1420 CheckDI(isMDTuple(N.getRawExtraData()), "invalid template parameters", &N,
1421 N.getRawExtraData());
1422 } else if (N.getTag() == dwarf::DW_TAG_inheritance ||
1423 N.getTag() == dwarf::DW_TAG_member ||
1424 N.getTag() == dwarf::DW_TAG_variable) {
1425 auto *ExtraData = N.getRawExtraData();
1426 auto IsValidExtraData = [&]() {
1427 if (ExtraData == nullptr)
1428 return true;
1429 if (isa<ConstantAsMetadata>(ExtraData) || isa<MDString>(ExtraData) ||
1430 isa<DIObjCProperty>(ExtraData))
1431 return true;
1432 if (auto *Tuple = dyn_cast<MDTuple>(ExtraData)) {
1433 if (Tuple->getNumOperands() != 1)
1434 return false;
1435 return isa_and_nonnull<ConstantAsMetadata>(Tuple->getOperand(0).get());
1436 }
1437 return false;
1438 };
1439 CheckDI(IsValidExtraData(),
1440 "extraData must be ConstantAsMetadata, MDString, DIObjCProperty, "
1441 "or MDTuple with single ConstantAsMetadata operand",
1442 &N, ExtraData);
1443 }
1444
1445 if (N.getTag() == dwarf::DW_TAG_set_type) {
1446 if (auto *T = N.getRawBaseType()) {
1450 CheckDI(
1451 (Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type) ||
1452 (Subrange && Subrange->getTag() == dwarf::DW_TAG_subrange_type) ||
1453 (Basic && (Basic->getEncoding() == dwarf::DW_ATE_unsigned ||
1454 Basic->getEncoding() == dwarf::DW_ATE_signed ||
1455 Basic->getEncoding() == dwarf::DW_ATE_unsigned_char ||
1456 Basic->getEncoding() == dwarf::DW_ATE_signed_char ||
1457 Basic->getEncoding() == dwarf::DW_ATE_boolean)),
1458 "invalid set base type", &N, T);
1459 }
1460 }
1461
1462 CheckDI(isType(N.getRawBaseType()), "invalid base type", &N,
1463 N.getRawBaseType());
1464
1465 if (N.getDWARFAddressSpace()) {
1466 CheckDI(N.getTag() == dwarf::DW_TAG_pointer_type ||
1467 N.getTag() == dwarf::DW_TAG_reference_type ||
1468 N.getTag() == dwarf::DW_TAG_rvalue_reference_type,
1469 "DWARF address space only applies to pointer or reference types",
1470 &N);
1471 }
1472
1473 auto *Size = N.getRawSizeInBits();
1476 "SizeInBits must be a constant or DIVariable or DIExpression");
1477}
1478
1479/// Detect mutually exclusive flags.
1480static bool hasConflictingReferenceFlags(unsigned Flags) {
1481 return ((Flags & DINode::FlagLValueReference) &&
1482 (Flags & DINode::FlagRValueReference)) ||
1483 ((Flags & DINode::FlagTypePassByValue) &&
1484 (Flags & DINode::FlagTypePassByReference));
1485}
1486
1487void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) {
1488 auto *Params = dyn_cast<MDTuple>(&RawParams);
1489 CheckDI(Params, "invalid template params", &N, &RawParams);
1490 for (Metadata *Op : Params->operands()) {
1491 CheckDI(Op && isa<DITemplateParameter>(Op), "invalid template parameter",
1492 &N, Params, Op);
1493 }
1494}
1495
1496void Verifier::visitDICompositeType(const DICompositeType &N) {
1497 // Common type checks.
1498 visitDIType(N);
1499
1500 CheckDI(N.getTag() == dwarf::DW_TAG_array_type ||
1501 N.getTag() == dwarf::DW_TAG_structure_type ||
1502 N.getTag() == dwarf::DW_TAG_union_type ||
1503 N.getTag() == dwarf::DW_TAG_enumeration_type ||
1504 N.getTag() == dwarf::DW_TAG_class_type ||
1505 N.getTag() == dwarf::DW_TAG_variant_part ||
1506 N.getTag() == dwarf::DW_TAG_variant ||
1507 N.getTag() == dwarf::DW_TAG_namelist,
1508 "invalid tag", &N);
1509
1510 CheckDI(isType(N.getRawBaseType()), "invalid base type", &N,
1511 N.getRawBaseType());
1512
1513 CheckDI(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
1514 "invalid composite elements", &N, N.getRawElements());
1515 CheckDI(isType(N.getRawVTableHolder()), "invalid vtable holder", &N,
1516 N.getRawVTableHolder());
1518 "invalid reference flags", &N);
1519 unsigned DIBlockByRefStruct = 1 << 4;
1520 CheckDI((N.getFlags() & DIBlockByRefStruct) == 0,
1521 "DIBlockByRefStruct on DICompositeType is no longer supported", &N);
1522 CheckDI(llvm::all_of(N.getElements(), [](const DINode *N) { return N; }),
1523 "DISubprogram contains null entry in `elements` field", &N);
1524
1525 if (N.isVector()) {
1526 const DINodeArray Elements = N.getElements();
1527 CheckDI(Elements.size() == 1 &&
1528 Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
1529 "invalid vector, expected one element of type subrange", &N);
1530 }
1531
1532 if (auto *Params = N.getRawTemplateParams())
1533 visitTemplateParams(N, *Params);
1534
1535 if (auto *D = N.getRawDiscriminator()) {
1536 CheckDI(isa<DIDerivedType>(D) && N.getTag() == dwarf::DW_TAG_variant_part,
1537 "discriminator can only appear on variant part");
1538 }
1539
1540 if (N.getRawDataLocation()) {
1541 CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1542 "dataLocation can only appear in array type");
1543 }
1544
1545 if (N.getRawAssociated()) {
1546 CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1547 "associated can only appear in array type");
1548 }
1549
1550 if (N.getRawAllocated()) {
1551 CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1552 "allocated can only appear in array type");
1553 }
1554
1555 if (N.getRawRank()) {
1556 CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1557 "rank can only appear in array type");
1558 }
1559
1560 if (N.getTag() == dwarf::DW_TAG_array_type) {
1561 CheckDI(N.getRawBaseType(), "array types must have a base type", &N);
1562 }
1563
1564 auto *Size = N.getRawSizeInBits();
1567 "SizeInBits must be a constant or DIVariable or DIExpression");
1568}
1569
1570void Verifier::visitDISubroutineType(const DISubroutineType &N) {
1571 visitDIType(N);
1572 CheckDI(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
1573 if (auto *Types = N.getRawTypeArray()) {
1574 CheckDI(isa<MDTuple>(Types), "invalid composite elements", &N, Types);
1575 for (Metadata *Ty : N.getTypeArray()->operands()) {
1576 CheckDI(isType(Ty), "invalid subroutine type ref", &N, Types, Ty);
1577 }
1578 }
1580 "invalid reference flags", &N);
1581}
1582
1583void Verifier::visitDIFile(const DIFile &N) {
1584 CheckDI(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
1585 std::optional<DIFile::ChecksumInfo<StringRef>> Checksum = N.getChecksum();
1586 if (Checksum) {
1587 CheckDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last,
1588 "invalid checksum kind", &N);
1589 size_t Size;
1590 switch (Checksum->Kind) {
1591 case DIFile::CSK_MD5:
1592 Size = 32;
1593 break;
1594 case DIFile::CSK_SHA1:
1595 Size = 40;
1596 break;
1597 case DIFile::CSK_SHA256:
1598 Size = 64;
1599 break;
1600 }
1601 CheckDI(Checksum->Value.size() == Size, "invalid checksum length", &N);
1602 CheckDI(Checksum->Value.find_if_not(llvm::isHexDigit) == StringRef::npos,
1603 "invalid checksum", &N);
1604 }
1605}
1606
1607void Verifier::visitDICompileUnit(const DICompileUnit &N) {
1608 CheckDI(N.isDistinct(), "compile units must be distinct", &N);
1609 CheckDI(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
1610
1611 // Don't bother verifying the compilation directory or producer string
1612 // as those could be empty.
1613 CheckDI(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N,
1614 N.getRawFile());
1615 CheckDI(!N.getFile()->getFilename().empty(), "invalid filename", &N,
1616 N.getFile());
1617
1618 CheckDI((N.getEmissionKind() <= DICompileUnit::LastEmissionKind),
1619 "invalid emission kind", &N);
1620
1621 CheckDI(N.getSourceLanguage().getDialect() <= dwarf::DW_LLVM_LANG_DIALECT_max,
1622 "invalid language dialect", &N);
1623
1624 if (auto *Array = N.getRawEnumTypes()) {
1625 CheckDI(isa<MDTuple>(Array), "invalid enum list", &N, Array);
1626 for (Metadata *Op : N.getEnumTypes()->operands()) {
1628 CheckDI(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
1629 "invalid enum type", &N, N.getEnumTypes(), Op);
1630 CheckDI(!Enum->getScope() || !isa<DILocalScope>(Enum->getScope()),
1631 "function-local enum in a DICompileUnit's enum list", &N,
1632 N.getEnumTypes(), Op);
1633 }
1634 }
1635 if (auto *Array = N.getRawRetainedTypes()) {
1636 CheckDI(isa<MDTuple>(Array), "invalid retained type list", &N, Array);
1637 for (Metadata *Op : N.getRetainedTypes()->operands()) {
1638 CheckDI(
1639 Op && (isa<DIType>(Op) || (isa<DISubprogram>(Op) &&
1640 !cast<DISubprogram>(Op)->isDefinition())),
1641 "invalid retained type", &N, Op);
1642 }
1643 }
1644 if (auto *Array = N.getRawGlobalVariables()) {
1645 CheckDI(isa<MDTuple>(Array), "invalid global variable list", &N, Array);
1646 for (Metadata *Op : N.getGlobalVariables()->operands()) {
1648 "invalid global variable ref", &N, Op);
1649 }
1650 }
1651 if (auto *Array = N.getRawImportedEntities()) {
1652 CheckDI(isa<MDTuple>(Array), "invalid imported entity list", &N, Array);
1653 for (Metadata *Op : N.getImportedEntities()->operands()) {
1655 CheckDI(IE, "invalid imported entity ref", &N, Op);
1657 "function-local imports are not allowed in a DICompileUnit's "
1658 "imported entities list",
1659 &N, Op);
1660 }
1661 }
1662 if (auto *Array = N.getRawMacros()) {
1663 CheckDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
1664 for (Metadata *Op : N.getMacros()->operands()) {
1665 CheckDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
1666 }
1667 }
1668 CUVisited.insert(&N);
1669}
1670
1671void Verifier::visitDISubprogram(const DISubprogram &N) {
1672 CheckDI(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
1673 CheckDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
1674 if (auto *F = N.getRawFile())
1675 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1676 else
1677 CheckDI(N.getLine() == 0, "line specified with no file", &N, N.getLine());
1678 auto *T = N.getRawType();
1679 CheckDI(T, "DISubprogram requires a non-null type", &N);
1680 CheckDI(isa<DISubroutineType>(T), "invalid subroutine type", &N, T);
1681 CheckDI(isType(N.getRawContainingType()), "invalid containing type", &N,
1682 N.getRawContainingType());
1683 if (auto *Params = N.getRawTemplateParams())
1684 visitTemplateParams(N, *Params);
1685 if (auto *S = N.getRawDeclaration())
1686 CheckDI(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(),
1687 "invalid subprogram declaration", &N, S);
1688 if (auto *RawNode = N.getRawRetainedNodes()) {
1689 auto *Node = dyn_cast<MDTuple>(RawNode);
1690 CheckDI(Node, "invalid retained nodes list", &N, RawNode);
1691
1692 DenseMap<unsigned, DILocalVariable *> Args;
1693 for (Metadata *Op : Node->operands()) {
1694 CheckDI(Op, "nullptr in retained nodes", &N, Node);
1695
1696 auto True = [](const Metadata *) { return true; };
1697 auto False = [](const Metadata *) { return false; };
1698 bool IsTypeCorrect = DISubprogram::visitRetainedNode<bool>(
1699 Op, True, True, True, True, False);
1700 CheckDI(IsTypeCorrect,
1701 "invalid retained nodes, expected DILocalVariable, DILabel, "
1702 "DIImportedEntity or DIType",
1703 &N, Node, Op);
1704
1705 auto *RetainedNode = cast<DINode>(Op);
1706 auto *RetainedNodeScope = dyn_cast_or_null<DILocalScope>(
1708 CheckDI(RetainedNodeScope,
1709 "invalid retained nodes, retained node is not local", &N, Node,
1710 RetainedNode);
1711
1712 DISubprogram *RetainedNodeSP = RetainedNodeScope->getSubprogram();
1713 DICompileUnit *RetainedNodeUnit =
1714 RetainedNodeSP ? RetainedNodeSP->getUnit() : nullptr;
1715 CheckDI(
1716 RetainedNodeSP == &N,
1717 "invalid retained nodes, retained node does not belong to subprogram",
1718 &N, Node, RetainedNode, RetainedNodeScope, RetainedNodeSP,
1719 RetainedNodeUnit);
1720
1721 auto *DV = dyn_cast<DILocalVariable>(RetainedNode);
1722 if (!DV)
1723 continue;
1724 if (unsigned ArgNum = DV->getArg()) {
1725 auto [ArgI, Inserted] = Args.insert({ArgNum, DV});
1726 CheckDI(Inserted || DV == ArgI->second,
1727 "invalid retained nodes, more than one local variable with the "
1728 "same argument index",
1729 &N, N.getUnit(), Node, RetainedNode, Args[ArgNum]);
1730 }
1731 }
1732 }
1734 "invalid reference flags", &N);
1735
1736 auto *Unit = N.getRawUnit();
1737 if (N.isDefinition()) {
1738 // Subprogram definitions (not part of the type hierarchy).
1739 CheckDI(N.isDistinct(), "subprogram definitions must be distinct", &N);
1740 CheckDI(Unit, "subprogram definitions must have a compile unit", &N);
1741 CheckDI(isa<DICompileUnit>(Unit), "invalid unit type", &N, Unit);
1742 // There's no good way to cross the CU boundary to insert a nested
1743 // DISubprogram definition in one CU into a type defined in another CU.
1744 auto *CT = dyn_cast_or_null<DICompositeType>(N.getRawScope());
1745 if (CT && CT->getRawIdentifier() &&
1746 M.getContext().isODRUniquingDebugTypes())
1747 CheckDI(N.getDeclaration(),
1748 "definition subprograms cannot be nested within DICompositeType "
1749 "when enabling ODR",
1750 &N);
1751 } else {
1752 // Subprogram declarations (part of the type hierarchy).
1753 CheckDI(!Unit, "subprogram declarations must not have a compile unit", &N);
1754 CheckDI(!N.getRawDeclaration(),
1755 "subprogram declaration must not have a declaration field");
1756 }
1757
1758 if (auto *RawThrownTypes = N.getRawThrownTypes()) {
1759 auto *ThrownTypes = dyn_cast<MDTuple>(RawThrownTypes);
1760 CheckDI(ThrownTypes, "invalid thrown types list", &N, RawThrownTypes);
1761 for (Metadata *Op : ThrownTypes->operands())
1762 CheckDI(Op && isa<DIType>(Op), "invalid thrown type", &N, ThrownTypes,
1763 Op);
1764 }
1765
1766 if (N.areAllCallsDescribed())
1767 CheckDI(N.isDefinition(),
1768 "DIFlagAllCallsDescribed must be attached to a definition");
1769}
1770
1771void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) {
1772 CheckDI(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
1773 CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1774 "invalid local scope", &N, N.getRawScope());
1775 if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
1776 CheckDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
1777}
1778
1779void Verifier::visitDILexicalBlock(const DILexicalBlock &N) {
1780 visitDILexicalBlockBase(N);
1781
1782 CheckDI(N.getLine() || !N.getColumn(),
1783 "cannot have column info without line info", &N);
1784}
1785
1786void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) {
1787 visitDILexicalBlockBase(N);
1788}
1789
1790void Verifier::visitDICommonBlock(const DICommonBlock &N) {
1791 CheckDI(N.getTag() == dwarf::DW_TAG_common_block, "invalid tag", &N);
1792 if (auto *S = N.getRawScope())
1793 CheckDI(isa<DIScope>(S), "invalid scope ref", &N, S);
1794 if (auto *S = N.getRawDecl())
1795 CheckDI(isa<DIGlobalVariable>(S), "invalid declaration", &N, S);
1796}
1797
1798void Verifier::visitDINamespace(const DINamespace &N) {
1799 CheckDI(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
1800 if (auto *S = N.getRawScope())
1801 CheckDI(isa<DIScope>(S), "invalid scope ref", &N, S);
1802}
1803
1804void Verifier::visitDIMacro(const DIMacro &N) {
1805 CheckDI(N.getMacinfoType() == dwarf::DW_MACINFO_define ||
1806 N.getMacinfoType() == dwarf::DW_MACINFO_undef,
1807 "invalid macinfo type", &N);
1808 CheckDI(!N.getName().empty(), "anonymous macro", &N);
1809 if (!N.getValue().empty()) {
1810 assert(N.getValue().data()[0] != ' ' && "Macro value has a space prefix");
1811 }
1812}
1813
1814void Verifier::visitDIMacroFile(const DIMacroFile &N) {
1815 CheckDI(N.getMacinfoType() == dwarf::DW_MACINFO_start_file,
1816 "invalid macinfo type", &N);
1817 if (auto *F = N.getRawFile())
1818 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1819
1820 if (auto *Array = N.getRawElements()) {
1821 CheckDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
1822 for (Metadata *Op : N.getElements()->operands()) {
1823 CheckDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
1824 }
1825 }
1826}
1827
1828void Verifier::visitDIModule(const DIModule &N) {
1829 CheckDI(N.getTag() == dwarf::DW_TAG_module, "invalid tag", &N);
1830 CheckDI(!N.getName().empty(), "anonymous module", &N);
1831}
1832
1833void Verifier::visitDITemplateParameter(const DITemplateParameter &N) {
1834 CheckDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
1835}
1836
1837void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) {
1838 visitDITemplateParameter(N);
1839
1840 CheckDI(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
1841 &N);
1842}
1843
1844void Verifier::visitDITemplateValueParameter(
1845 const DITemplateValueParameter &N) {
1846 visitDITemplateParameter(N);
1847
1848 CheckDI(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1849 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1850 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1851 "invalid tag", &N);
1852}
1853
1854void Verifier::visitDIVariable(const DIVariable &N) {
1855 if (auto *S = N.getRawScope())
1856 CheckDI(isa<DIScope>(S), "invalid scope", &N, S);
1857 if (auto *F = N.getRawFile())
1858 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1859}
1860
1861void Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) {
1862 // Checks common to all variables.
1863 visitDIVariable(N);
1864
1865 CheckDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1866 CheckDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
1867 // Check only if the global variable is not an extern
1868 if (N.isDefinition())
1869 CheckDI(N.getType(), "missing global variable type", &N);
1870 if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
1872 "invalid static data member declaration", &N, Member);
1873 }
1874}
1875
1876void Verifier::visitDILocalVariable(const DILocalVariable &N) {
1877 // Checks common to all variables.
1878 visitDIVariable(N);
1879
1880 CheckDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
1881 CheckDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1882 CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1883 "local variable requires a valid scope", &N, N.getRawScope());
1884 if (auto Ty = N.getType())
1885 CheckDI(!isa<DISubroutineType>(Ty), "invalid type", &N, N.getType());
1886}
1887
1888void Verifier::visitDIAssignID(const DIAssignID &N) {
1889 CheckDI(!N.getNumOperands(), "DIAssignID has no arguments", &N);
1890 CheckDI(N.isDistinct(), "DIAssignID must be distinct", &N);
1891}
1892
1893void Verifier::visitDILabel(const DILabel &N) {
1894 if (auto *S = N.getRawScope())
1895 CheckDI(isa<DIScope>(S), "invalid scope", &N, S);
1896 if (auto *F = N.getRawFile())
1897 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1898
1899 CheckDI(N.getTag() == dwarf::DW_TAG_label, "invalid tag", &N);
1900 CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1901 "label requires a valid scope", &N, N.getRawScope());
1902}
1903
1904void Verifier::visitDIExpression(const DIExpression &N) {
1905 CheckDI(N.isValid(), "invalid expression", &N);
1906}
1907
1908void Verifier::visitDIGlobalVariableExpression(
1909 const DIGlobalVariableExpression &GVE) {
1910 CheckDI(GVE.getVariable(), "missing variable");
1911 if (auto *Var = GVE.getVariable())
1912 visitDIGlobalVariable(*Var);
1913 if (auto *Expr = GVE.getExpression()) {
1914 visitDIExpression(*Expr);
1915 if (auto Fragment = Expr->getFragmentInfo())
1916 verifyFragmentExpression(*GVE.getVariable(), *Fragment, &GVE);
1917 }
1918}
1919
1920void Verifier::visitDIObjCProperty(const DIObjCProperty &N) {
1921 CheckDI(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
1922 if (auto *T = N.getRawType())
1923 CheckDI(isType(T), "invalid type ref", &N, T);
1924 if (auto *F = N.getRawFile())
1925 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1926}
1927
1928void Verifier::visitDIImportedEntity(const DIImportedEntity &N) {
1929 CheckDI(N.getTag() == dwarf::DW_TAG_imported_module ||
1930 N.getTag() == dwarf::DW_TAG_imported_declaration,
1931 "invalid tag", &N);
1932 if (auto *S = N.getRawScope())
1933 CheckDI(isa<DIScope>(S), "invalid scope for imported entity", &N, S);
1934 CheckDI(isDINode(N.getRawEntity()), "invalid imported entity", &N,
1935 N.getRawEntity());
1936}
1937
1938void Verifier::visitComdat(const Comdat &C) {
1939 // In COFF the Module is invalid if the GlobalValue has private linkage.
1940 // Entities with private linkage don't have entries in the symbol table.
1941 if (TT.isOSBinFormatCOFF())
1942 if (const GlobalValue *GV = M.getNamedValue(C.getName()))
1943 Check(!GV->hasPrivateLinkage(), "comdat global value has private linkage",
1944 GV);
1945}
1946
1947void Verifier::visitModuleIdents() {
1948 const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
1949 if (!Idents)
1950 return;
1951
1952 // llvm.ident takes a list of metadata entry. Each entry has only one string.
1953 // Scan each llvm.ident entry and make sure that this requirement is met.
1954 for (const MDNode *N : Idents->operands()) {
1955 Check(N->getNumOperands() == 1,
1956 "incorrect number of operands in llvm.ident metadata", N);
1957 Check(dyn_cast_or_null<MDString>(N->getOperand(0)),
1958 ("invalid value for llvm.ident metadata entry operand"
1959 "(the operand should be a string)"),
1960 N->getOperand(0));
1961 }
1962}
1963
1964void Verifier::visitModuleCommandLines() {
1965 const NamedMDNode *CommandLines = M.getNamedMetadata("llvm.commandline");
1966 if (!CommandLines)
1967 return;
1968
1969 // llvm.commandline takes a list of metadata entry. Each entry has only one
1970 // string. Scan each llvm.commandline entry and make sure that this
1971 // requirement is met.
1972 for (const MDNode *N : CommandLines->operands()) {
1973 Check(N->getNumOperands() == 1,
1974 "incorrect number of operands in llvm.commandline metadata", N);
1975 Check(dyn_cast_or_null<MDString>(N->getOperand(0)),
1976 ("invalid value for llvm.commandline metadata entry operand"
1977 "(the operand should be a string)"),
1978 N->getOperand(0));
1979 }
1980}
1981
1982void Verifier::visitModuleErrnoTBAA() {
1983 const NamedMDNode *ErrnoTBAA = M.getNamedMetadata("llvm.errno.tbaa");
1984 if (!ErrnoTBAA)
1985 return;
1986
1987 Check(ErrnoTBAA->getNumOperands() >= 1,
1988 "llvm.errno.tbaa must have at least one operand", ErrnoTBAA);
1989
1990 for (const MDNode *N : ErrnoTBAA->operands())
1991 TBAAVerifyHelper.visitTBAAMetadata(nullptr, N);
1992}
1993
1994void Verifier::visitModuleFlags() {
1995 const NamedMDNode *Flags = M.getModuleFlagsMetadata();
1996 if (!Flags) return;
1997
1998 // Scan each flag, and track the flags and requirements.
1999 DenseMap<const MDString*, const MDNode*> SeenIDs;
2000 SmallVector<const MDNode*, 16> Requirements;
2001 uint64_t PAuthABIPlatform = -1;
2002 uint64_t PAuthABIVersion = -1;
2003 for (const MDNode *MDN : Flags->operands()) {
2004 visitModuleFlag(MDN, SeenIDs, Requirements);
2005 if (MDN->getNumOperands() != 3)
2006 continue;
2007 if (const auto *FlagName = dyn_cast_or_null<MDString>(MDN->getOperand(1))) {
2008 if (FlagName->getString() == "aarch64-elf-pauthabi-platform") {
2009 if (const auto *PAP =
2011 PAuthABIPlatform = PAP->getZExtValue();
2012 } else if (FlagName->getString() == "aarch64-elf-pauthabi-version") {
2013 if (const auto *PAV =
2015 PAuthABIVersion = PAV->getZExtValue();
2016 }
2017 }
2018 }
2019
2020 if ((PAuthABIPlatform == uint64_t(-1)) != (PAuthABIVersion == uint64_t(-1)))
2021 CheckFailed("either both or no 'aarch64-elf-pauthabi-platform' and "
2022 "'aarch64-elf-pauthabi-version' module flags must be present");
2023
2024 // Validate that the requirements in the module are valid.
2025 for (const MDNode *Requirement : Requirements) {
2026 const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
2027 const Metadata *ReqValue = Requirement->getOperand(1);
2028
2029 const MDNode *Op = SeenIDs.lookup(Flag);
2030 if (!Op) {
2031 CheckFailed("invalid requirement on flag, flag is not present in module",
2032 Flag);
2033 continue;
2034 }
2035
2036 if (Op->getOperand(2) != ReqValue) {
2037 CheckFailed(("invalid requirement on flag, "
2038 "flag does not have the required value"),
2039 Flag);
2040 continue;
2041 }
2042 }
2043}
2044
2045void
2046Verifier::visitModuleFlag(const MDNode *Op,
2047 DenseMap<const MDString *, const MDNode *> &SeenIDs,
2048 SmallVectorImpl<const MDNode *> &Requirements) {
2049 // Each module flag should have three arguments, the merge behavior (a
2050 // constant int), the flag ID (an MDString), and the value.
2051 Check(Op->getNumOperands() == 3,
2052 "incorrect number of operands in module flag", Op);
2053 Module::ModFlagBehavior MFB;
2054 if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
2056 "invalid behavior operand in module flag (expected constant integer)",
2057 Op->getOperand(0));
2058 Check(false,
2059 "invalid behavior operand in module flag (unexpected constant)",
2060 Op->getOperand(0));
2061 }
2062 MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
2063 Check(ID, "invalid ID operand in module flag (expected metadata string)",
2064 Op->getOperand(1));
2065
2066 // Check the values for behaviors with additional requirements.
2067 switch (MFB) {
2068 case Module::Error:
2069 case Module::Warning:
2070 case Module::Override:
2071 // These behavior types accept any value.
2072 break;
2073
2074 case Module::Min: {
2075 auto *V = mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
2076 Check(V && V->getValue().isNonNegative(),
2077 "invalid value for 'min' module flag (expected constant non-negative "
2078 "integer)",
2079 Op->getOperand(2));
2080 break;
2081 }
2082
2083 case Module::Max: {
2085 "invalid value for 'max' module flag (expected constant integer)",
2086 Op->getOperand(2));
2087 break;
2088 }
2089
2090 case Module::Require: {
2091 // The value should itself be an MDNode with two operands, a flag ID (an
2092 // MDString), and a value.
2093 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
2094 Check(Value && Value->getNumOperands() == 2,
2095 "invalid value for 'require' module flag (expected metadata pair)",
2096 Op->getOperand(2));
2097 Check(isa<MDString>(Value->getOperand(0)),
2098 ("invalid value for 'require' module flag "
2099 "(first value operand should be a string)"),
2100 Value->getOperand(0));
2101
2102 // Append it to the list of requirements, to check once all module flags are
2103 // scanned.
2104 Requirements.push_back(Value);
2105 break;
2106 }
2107
2108 case Module::Append:
2109 case Module::AppendUnique: {
2110 // These behavior types require the operand be an MDNode.
2111 Check(isa<MDNode>(Op->getOperand(2)),
2112 "invalid value for 'append'-type module flag "
2113 "(expected a metadata node)",
2114 Op->getOperand(2));
2115 break;
2116 }
2117 }
2118
2119 // Unless this is a "requires" flag, check the ID is unique.
2120 if (MFB != Module::Require) {
2121 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
2122 Check(Inserted,
2123 "module flag identifiers must be unique (or of 'require' type)", ID);
2124 }
2125
2126 if (ID->getString() == "wchar_size") {
2127 ConstantInt *Value
2129 Check(Value, "wchar_size metadata requires constant integer argument");
2130 }
2131
2132 if (ID->getString() == "Linker Options") {
2133 // If the llvm.linker.options named metadata exists, we assume that the
2134 // bitcode reader has upgraded the module flag. Otherwise the flag might
2135 // have been created by a client directly.
2136 Check(M.getNamedMetadata("llvm.linker.options"),
2137 "'Linker Options' named metadata no longer supported");
2138 }
2139
2140 if (ID->getString() == "SemanticInterposition") {
2141 ConstantInt *Value =
2143 Check(Value,
2144 "SemanticInterposition metadata requires constant integer argument");
2145 }
2146
2147 if (ID->getString() == "amdgpu.buffer.oob.mode" ||
2148 ID->getString() == "amdgpu.tbuffer.oob.mode") {
2149 Check(MFB == Module::Max,
2150 "'" + ID->getString() +
2151 "' module flag must use 'max' merge behaviour");
2152 ConstantInt *Value =
2154 Check(Value, "'" + ID->getString() +
2155 "' module flag must have a constant integer value");
2156 if (Value) {
2157 Check(Value->getZExtValue() <= 2,
2158 "'" + ID->getString() + "' module flag must be 0, 1, or 2");
2159 }
2160 }
2161
2162 if (ID->getString() == "CG Profile") {
2163 for (const MDOperand &MDO : cast<MDNode>(Op->getOperand(2))->operands())
2164 visitModuleFlagCGProfileEntry(MDO);
2165 }
2166}
2167
2168void Verifier::visitModuleFlagCGProfileEntry(const MDOperand &MDO) {
2169 auto CheckFunction = [&](const MDOperand &FuncMDO) {
2170 if (!FuncMDO)
2171 return;
2172 auto F = dyn_cast<ValueAsMetadata>(FuncMDO);
2173 Check(F && isa<Function>(F->getValue()->stripPointerCasts()),
2174 "expected a Function or null", FuncMDO);
2175 };
2176 auto Node = dyn_cast_or_null<MDNode>(MDO);
2177 Check(Node && Node->getNumOperands() == 3, "expected a MDNode triple", MDO);
2178 CheckFunction(Node->getOperand(0));
2179 CheckFunction(Node->getOperand(1));
2180 auto Count = dyn_cast_or_null<ConstantAsMetadata>(Node->getOperand(2));
2181 Check(Count && Count->getType()->isIntegerTy(),
2182 "expected an integer constant", Node->getOperand(2));
2183}
2184
2185void Verifier::verifyAttributeTypes(AttributeSet Attrs, const Value *V) {
2186 for (Attribute A : Attrs) {
2187
2188 if (A.isStringAttribute()) {
2189#define GET_ATTR_NAMES
2190#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)
2191#define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME) \
2192 if (A.getKindAsString() == #DISPLAY_NAME) { \
2193 auto V = A.getValueAsString(); \
2194 if (!(V.empty() || V == "true" || V == "false")) \
2195 CheckFailed("invalid value for '" #DISPLAY_NAME "' attribute: " + V + \
2196 ""); \
2197 }
2198
2199#include "llvm/IR/Attributes.inc"
2200 continue;
2201 }
2202
2203 if (A.isIntAttribute() != Attribute::isIntAttrKind(A.getKindAsEnum())) {
2204 CheckFailed("Attribute '" + A.getAsString() + "' should have an Argument",
2205 V);
2206 return;
2207 }
2208 }
2209}
2210
2211// VerifyParameterAttrs - Check the given attributes for an argument or return
2212// value of the specified type. The value V is printed in error messages.
2213void Verifier::verifyParameterAttrs(AttributeSet Attrs, Type *Ty,
2214 const Value *V) {
2215 if (!Attrs.hasAttributes())
2216 return;
2217
2218 verifyAttributeTypes(Attrs, V);
2219
2220 for (Attribute Attr : Attrs)
2221 Check(Attr.isStringAttribute() ||
2222 Attribute::canUseAsParamAttr(Attr.getKindAsEnum()),
2223 "Attribute '" + Attr.getAsString() + "' does not apply to parameters",
2224 V);
2225
2226 if (Attrs.hasAttribute(Attribute::ImmArg)) {
2227 unsigned AttrCount =
2228 Attrs.getNumAttributes() - Attrs.hasAttribute(Attribute::Range);
2229 Check(AttrCount == 1,
2230 "Attribute 'immarg' is incompatible with other attributes except the "
2231 "'range' attribute",
2232 V);
2233 }
2234
2235 // Check for mutually incompatible attributes. Only inreg is compatible with
2236 // sret.
2237 unsigned AttrCount = 0;
2238 AttrCount += Attrs.hasAttribute(Attribute::ByVal);
2239 AttrCount += Attrs.hasAttribute(Attribute::InAlloca);
2240 AttrCount += Attrs.hasAttribute(Attribute::Preallocated);
2241 AttrCount += Attrs.hasAttribute(Attribute::StructRet) ||
2242 Attrs.hasAttribute(Attribute::InReg);
2243 AttrCount += Attrs.hasAttribute(Attribute::Nest);
2244 AttrCount += Attrs.hasAttribute(Attribute::ByRef);
2245 Check(AttrCount <= 1,
2246 "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
2247 "'byref', and 'sret' are incompatible!",
2248 V);
2249
2250 Check(!(Attrs.hasAttribute(Attribute::InAlloca) &&
2251 Attrs.hasAttribute(Attribute::ReadOnly)),
2252 "Attributes "
2253 "'inalloca and readonly' are incompatible!",
2254 V);
2255
2256 Check(!(Attrs.hasAttribute(Attribute::StructRet) &&
2257 Attrs.hasAttribute(Attribute::Returned)),
2258 "Attributes "
2259 "'sret and returned' are incompatible!",
2260 V);
2261
2262 Check(!(Attrs.hasAttribute(Attribute::ZExt) &&
2263 Attrs.hasAttribute(Attribute::SExt)),
2264 "Attributes "
2265 "'zeroext and signext' are incompatible!",
2266 V);
2267
2268 Check(!(Attrs.hasAttribute(Attribute::ReadNone) &&
2269 Attrs.hasAttribute(Attribute::ReadOnly)),
2270 "Attributes "
2271 "'readnone and readonly' are incompatible!",
2272 V);
2273
2274 Check(!(Attrs.hasAttribute(Attribute::ReadNone) &&
2275 Attrs.hasAttribute(Attribute::WriteOnly)),
2276 "Attributes "
2277 "'readnone and writeonly' are incompatible!",
2278 V);
2279
2280 Check(!(Attrs.hasAttribute(Attribute::ReadOnly) &&
2281 Attrs.hasAttribute(Attribute::WriteOnly)),
2282 "Attributes "
2283 "'readonly and writeonly' are incompatible!",
2284 V);
2285
2286 Check(!(Attrs.hasAttribute(Attribute::NoInline) &&
2287 Attrs.hasAttribute(Attribute::AlwaysInline)),
2288 "Attributes "
2289 "'noinline and alwaysinline' are incompatible!",
2290 V);
2291
2292 Check(!(Attrs.hasAttribute(Attribute::Writable) &&
2293 Attrs.hasAttribute(Attribute::ReadNone)),
2294 "Attributes writable and readnone are incompatible!", V);
2295
2296 Check(!(Attrs.hasAttribute(Attribute::Writable) &&
2297 Attrs.hasAttribute(Attribute::ReadOnly)),
2298 "Attributes writable and readonly are incompatible!", V);
2299
2300 AttributeMask IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty, Attrs);
2301 for (Attribute Attr : Attrs) {
2302 if (!Attr.isStringAttribute() &&
2303 IncompatibleAttrs.contains(Attr.getKindAsEnum())) {
2304 CheckFailed("Attribute '" + Attr.getAsString() +
2305 "' applied to incompatible type!", V);
2306 return;
2307 }
2308 }
2309
2310 if (isa<PointerType>(Ty)) {
2311 if (Attrs.hasAttribute(Attribute::Alignment)) {
2312 Align AttrAlign = Attrs.getAlignment().valueOrOne();
2313 Check(AttrAlign.value() <= Value::MaximumAlignment,
2314 "huge alignment values are unsupported", V);
2315 }
2316 if (Attrs.hasAttribute(Attribute::ByVal)) {
2317 Type *ByValTy = Attrs.getByValType();
2318 SmallPtrSet<Type *, 4> Visited;
2319 Check(ByValTy->isSized(&Visited),
2320 "Attribute 'byval' does not support unsized types!", V);
2321 // Check if it is or contains a target extension type that disallows being
2322 // used on the stack.
2324 "'byval' argument has illegal target extension type", V);
2325 Check(DL.getTypeAllocSize(ByValTy).getKnownMinValue() < (1ULL << 32),
2326 "huge 'byval' arguments are unsupported", V);
2327 }
2328 if (Attrs.hasAttribute(Attribute::ByRef)) {
2329 SmallPtrSet<Type *, 4> Visited;
2330 Check(Attrs.getByRefType()->isSized(&Visited),
2331 "Attribute 'byref' does not support unsized types!", V);
2332 Check(DL.getTypeAllocSize(Attrs.getByRefType()).getKnownMinValue() <
2333 (1ULL << 32),
2334 "huge 'byref' arguments are unsupported", V);
2335 }
2336 if (Attrs.hasAttribute(Attribute::InAlloca)) {
2337 SmallPtrSet<Type *, 4> Visited;
2338 Check(Attrs.getInAllocaType()->isSized(&Visited),
2339 "Attribute 'inalloca' does not support unsized types!", V);
2340 Check(DL.getTypeAllocSize(Attrs.getInAllocaType()).getKnownMinValue() <
2341 (1ULL << 32),
2342 "huge 'inalloca' arguments are unsupported", V);
2343 }
2344 if (Attrs.hasAttribute(Attribute::Preallocated)) {
2345 SmallPtrSet<Type *, 4> Visited;
2346 Check(Attrs.getPreallocatedType()->isSized(&Visited),
2347 "Attribute 'preallocated' does not support unsized types!", V);
2348 Check(
2349 DL.getTypeAllocSize(Attrs.getPreallocatedType()).getKnownMinValue() <
2350 (1ULL << 32),
2351 "huge 'preallocated' arguments are unsupported", V);
2352 }
2353 }
2354
2355 if (Attrs.hasAttribute(Attribute::Initializes)) {
2356 auto Inits = Attrs.getAttribute(Attribute::Initializes).getInitializes();
2357 Check(!Inits.empty(), "Attribute 'initializes' does not support empty list",
2358 V);
2360 "Attribute 'initializes' does not support unordered ranges", V);
2361 }
2362
2363 if (Attrs.hasAttribute(Attribute::NoFPClass)) {
2364 uint64_t Val = Attrs.getAttribute(Attribute::NoFPClass).getValueAsInt();
2365 Check(Val != 0, "Attribute 'nofpclass' must have at least one test bit set",
2366 V);
2367 Check((Val & ~static_cast<unsigned>(fcAllFlags)) == 0,
2368 "Invalid value for 'nofpclass' test mask", V);
2369 }
2370 if (Attrs.hasAttribute(Attribute::Range)) {
2371 const ConstantRange &CR =
2372 Attrs.getAttribute(Attribute::Range).getValueAsConstantRange();
2374 "Range bit width must match type bit width!", V);
2375 }
2376}
2377
2378void Verifier::checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
2379 const Value *V) {
2380 if (Attrs.hasFnAttr(Attr)) {
2381 StringRef S = Attrs.getFnAttr(Attr).getValueAsString();
2382 unsigned N;
2383 if (S.getAsInteger(10, N))
2384 CheckFailed("\"" + Attr + "\" takes an unsigned integer: " + S, V);
2385 }
2386}
2387
2388// Check parameter attributes against a function type.
2389// The value V is printed in error messages.
2390void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
2391 const Value *V, bool IsIntrinsic,
2392 bool IsInlineAsm) {
2393 if (Attrs.isEmpty())
2394 return;
2395
2396 if (AttributeListsVisited.insert(Attrs.getRawPointer()).second) {
2397 Check(Attrs.hasParentContext(Context),
2398 "Attribute list does not match Module context!", &Attrs, V);
2399 for (const auto &AttrSet : Attrs) {
2400 Check(!AttrSet.hasAttributes() || AttrSet.hasParentContext(Context),
2401 "Attribute set does not match Module context!", &AttrSet, V);
2402 for (const auto &A : AttrSet) {
2403 Check(A.hasParentContext(Context),
2404 "Attribute does not match Module context!", &A, V);
2405 }
2406 }
2407 }
2408
2409 bool SawNest = false;
2410 bool SawReturned = false;
2411 bool SawSRet = false;
2412 bool SawSwiftSelf = false;
2413 bool SawSwiftAsync = false;
2414 bool SawSwiftError = false;
2415
2416 // Verify return value attributes.
2417 AttributeSet RetAttrs = Attrs.getRetAttrs();
2418 for (Attribute RetAttr : RetAttrs)
2419 Check(RetAttr.isStringAttribute() ||
2420 Attribute::canUseAsRetAttr(RetAttr.getKindAsEnum()),
2421 "Attribute '" + RetAttr.getAsString() +
2422 "' does not apply to function return values",
2423 V);
2424
2425 unsigned MaxParameterWidth = 0;
2426 auto GetMaxParameterWidth = [&MaxParameterWidth](Type *Ty) {
2427 if (Ty->isVectorTy()) {
2428 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
2429 unsigned Size = VT->getPrimitiveSizeInBits().getFixedValue();
2430 if (Size > MaxParameterWidth)
2431 MaxParameterWidth = Size;
2432 }
2433 }
2434 };
2435 GetMaxParameterWidth(FT->getReturnType());
2436 verifyParameterAttrs(RetAttrs, FT->getReturnType(), V);
2437
2438 // Verify parameter attributes.
2439 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2440 Type *Ty = FT->getParamType(i);
2441 AttributeSet ArgAttrs = Attrs.getParamAttrs(i);
2442
2443 if (!IsIntrinsic) {
2444 Check(!ArgAttrs.hasAttribute(Attribute::ImmArg),
2445 "immarg attribute only applies to intrinsics", V);
2446 if (!IsInlineAsm)
2447 Check(!ArgAttrs.hasAttribute(Attribute::ElementType),
2448 "Attribute 'elementtype' can only be applied to intrinsics"
2449 " and inline asm.",
2450 V);
2451 }
2452
2453 verifyParameterAttrs(ArgAttrs, Ty, V);
2454 GetMaxParameterWidth(Ty);
2455
2456 if (ArgAttrs.hasAttribute(Attribute::Nest)) {
2457 Check(!SawNest, "More than one parameter has attribute nest!", V);
2458 SawNest = true;
2459 }
2460
2461 if (ArgAttrs.hasAttribute(Attribute::Returned)) {
2462 Check(!SawReturned, "More than one parameter has attribute returned!", V);
2463 Check(Ty->canLosslesslyBitCastTo(FT->getReturnType()),
2464 "Incompatible argument and return types for 'returned' attribute",
2465 V);
2466 SawReturned = true;
2467 }
2468
2469 if (ArgAttrs.hasAttribute(Attribute::StructRet)) {
2470 Check(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
2471 Check(i == 0 || i == 1,
2472 "Attribute 'sret' is not on first or second parameter!", V);
2473 SawSRet = true;
2474 }
2475
2476 if (ArgAttrs.hasAttribute(Attribute::SwiftSelf)) {
2477 Check(!SawSwiftSelf, "Cannot have multiple 'swiftself' parameters!", V);
2478 SawSwiftSelf = true;
2479 }
2480
2481 if (ArgAttrs.hasAttribute(Attribute::SwiftAsync)) {
2482 Check(!SawSwiftAsync, "Cannot have multiple 'swiftasync' parameters!", V);
2483 SawSwiftAsync = true;
2484 }
2485
2486 if (ArgAttrs.hasAttribute(Attribute::SwiftError)) {
2487 Check(!SawSwiftError, "Cannot have multiple 'swifterror' parameters!", V);
2488 SawSwiftError = true;
2489 }
2490
2491 if (ArgAttrs.hasAttribute(Attribute::InAlloca)) {
2492 Check(i == FT->getNumParams() - 1,
2493 "inalloca isn't on the last parameter!", V);
2494 }
2495 }
2496
2497 if (!Attrs.hasFnAttrs())
2498 return;
2499
2500 verifyAttributeTypes(Attrs.getFnAttrs(), V);
2501 for (Attribute FnAttr : Attrs.getFnAttrs())
2502 Check(FnAttr.isStringAttribute() ||
2503 Attribute::canUseAsFnAttr(FnAttr.getKindAsEnum()),
2504 "Attribute '" + FnAttr.getAsString() +
2505 "' does not apply to functions!",
2506 V);
2507
2508 Check(!(Attrs.hasFnAttr(Attribute::NoInline) &&
2509 Attrs.hasFnAttr(Attribute::AlwaysInline)),
2510 "Attributes 'noinline and alwaysinline' are incompatible!", V);
2511
2512 if (Attrs.hasFnAttr(Attribute::OptimizeNone)) {
2513 Check(Attrs.hasFnAttr(Attribute::NoInline),
2514 "Attribute 'optnone' requires 'noinline'!", V);
2515
2516 Check(!Attrs.hasFnAttr(Attribute::OptimizeForSize),
2517 "Attributes 'optsize and optnone' are incompatible!", V);
2518
2519 Check(!Attrs.hasFnAttr(Attribute::MinSize),
2520 "Attributes 'minsize and optnone' are incompatible!", V);
2521
2522 Check(!Attrs.hasFnAttr(Attribute::OptimizeForDebugging),
2523 "Attributes 'optdebug and optnone' are incompatible!", V);
2524 }
2525
2526 Check(!(Attrs.hasFnAttr(Attribute::SanitizeRealtime) &&
2527 Attrs.hasFnAttr(Attribute::SanitizeRealtimeBlocking)),
2528 "Attributes "
2529 "'sanitize_realtime and sanitize_realtime_blocking' are incompatible!",
2530 V);
2531
2532 if (Attrs.hasFnAttr(Attribute::OptimizeForDebugging)) {
2533 Check(!Attrs.hasFnAttr(Attribute::OptimizeForSize),
2534 "Attributes 'optsize and optdebug' are incompatible!", V);
2535
2536 Check(!Attrs.hasFnAttr(Attribute::MinSize),
2537 "Attributes 'minsize and optdebug' are incompatible!", V);
2538 }
2539
2540 Check(!Attrs.hasAttrSomewhere(Attribute::Writable) ||
2541 isModSet(Attrs.getMemoryEffects().getModRef(IRMemLocation::ArgMem)),
2542 "Attribute writable and memory without argmem: write are incompatible!",
2543 V);
2544
2545 if (Attrs.hasFnAttr("aarch64_pstate_sm_enabled")) {
2546 Check(!Attrs.hasFnAttr("aarch64_pstate_sm_compatible"),
2547 "Attributes 'aarch64_pstate_sm_enabled and "
2548 "aarch64_pstate_sm_compatible' are incompatible!",
2549 V);
2550 }
2551
2552 Check((Attrs.hasFnAttr("aarch64_new_za") + Attrs.hasFnAttr("aarch64_in_za") +
2553 Attrs.hasFnAttr("aarch64_inout_za") +
2554 Attrs.hasFnAttr("aarch64_out_za") +
2555 Attrs.hasFnAttr("aarch64_preserves_za") +
2556 Attrs.hasFnAttr("aarch64_za_state_agnostic")) <= 1,
2557 "Attributes 'aarch64_new_za', 'aarch64_in_za', 'aarch64_out_za', "
2558 "'aarch64_inout_za', 'aarch64_preserves_za' and "
2559 "'aarch64_za_state_agnostic' are mutually exclusive",
2560 V);
2561
2562 Check((Attrs.hasFnAttr("aarch64_new_zt0") +
2563 Attrs.hasFnAttr("aarch64_in_zt0") +
2564 Attrs.hasFnAttr("aarch64_inout_zt0") +
2565 Attrs.hasFnAttr("aarch64_out_zt0") +
2566 Attrs.hasFnAttr("aarch64_preserves_zt0") +
2567 Attrs.hasFnAttr("aarch64_za_state_agnostic")) <= 1,
2568 "Attributes 'aarch64_new_zt0', 'aarch64_in_zt0', 'aarch64_out_zt0', "
2569 "'aarch64_inout_zt0', 'aarch64_preserves_zt0' and "
2570 "'aarch64_za_state_agnostic' are mutually exclusive",
2571 V);
2572
2573 if (Attrs.hasFnAttr(Attribute::JumpTable)) {
2574 const GlobalValue *GV = cast<GlobalValue>(V);
2576 "Attribute 'jumptable' requires 'unnamed_addr'", V);
2577 }
2578
2579 if (auto Args = Attrs.getFnAttrs().getAllocSizeArgs()) {
2580 auto CheckParam = [&](StringRef Name, unsigned ParamNo) {
2581 if (ParamNo >= FT->getNumParams()) {
2582 CheckFailed("'allocsize' " + Name + " argument is out of bounds", V);
2583 return false;
2584 }
2585
2586 if (!FT->getParamType(ParamNo)->isIntegerTy()) {
2587 CheckFailed("'allocsize' " + Name +
2588 " argument must refer to an integer parameter",
2589 V);
2590 return false;
2591 }
2592
2593 return true;
2594 };
2595
2596 if (!CheckParam("element size", Args->first))
2597 return;
2598
2599 if (Args->second && !CheckParam("number of elements", *Args->second))
2600 return;
2601 }
2602
2603 if (Attrs.hasFnAttr(Attribute::AllocKind)) {
2604 AllocFnKind K = Attrs.getAllocKind();
2606 K & (AllocFnKind::Alloc | AllocFnKind::Realloc | AllocFnKind::Free);
2607 if (!is_contained(
2608 {AllocFnKind::Alloc, AllocFnKind::Realloc, AllocFnKind::Free},
2609 Type))
2610 CheckFailed(
2611 "'allockind()' requires exactly one of alloc, realloc, and free");
2612 if ((Type == AllocFnKind::Free) &&
2613 ((K & (AllocFnKind::Uninitialized | AllocFnKind::Zeroed |
2614 AllocFnKind::Aligned)) != AllocFnKind::Unknown))
2615 CheckFailed("'allockind(\"free\")' doesn't allow uninitialized, zeroed, "
2616 "or aligned modifiers.");
2617 AllocFnKind ZeroedUninit = AllocFnKind::Uninitialized | AllocFnKind::Zeroed;
2618 if ((K & ZeroedUninit) == ZeroedUninit)
2619 CheckFailed("'allockind()' can't be both zeroed and uninitialized");
2620 }
2621
2622 if (Attribute A = Attrs.getFnAttr("alloc-variant-zeroed"); A.isValid()) {
2623 StringRef S = A.getValueAsString();
2624 Check(!S.empty(), "'alloc-variant-zeroed' must not be empty");
2625 Function *Variant = M.getFunction(S);
2626 if (Variant) {
2627 Attribute Family = Attrs.getFnAttr("alloc-family");
2628 Attribute VariantFamily = Variant->getFnAttribute("alloc-family");
2629 if (Family.isValid())
2630 Check(VariantFamily.isValid() &&
2631 VariantFamily.getValueAsString() == Family.getValueAsString(),
2632 "'alloc-variant-zeroed' must name a function belonging to the "
2633 "same 'alloc-family'");
2634
2635 Check(Variant->hasFnAttribute(Attribute::AllocKind) &&
2636 (Variant->getFnAttribute(Attribute::AllocKind).getAllocKind() &
2637 AllocFnKind::Zeroed) != AllocFnKind::Unknown,
2638 "'alloc-variant-zeroed' must name a function with "
2639 "'allockind(\"zeroed\")'");
2640
2641 Check(FT == Variant->getFunctionType(),
2642 "'alloc-variant-zeroed' must name a function with the same "
2643 "signature");
2644
2645 if (const Function *F = dyn_cast<Function>(V))
2646 Check(F->getCallingConv() == Variant->getCallingConv(),
2647 "'alloc-variant-zeroed' must name a function with the same "
2648 "calling convention");
2649 }
2650 }
2651
2652 if (Attrs.hasFnAttr(Attribute::VScaleRange)) {
2653 unsigned VScaleMin = Attrs.getFnAttrs().getVScaleRangeMin();
2654 if (VScaleMin == 0)
2655 CheckFailed("'vscale_range' minimum must be greater than 0", V);
2656 else if (!isPowerOf2_32(VScaleMin))
2657 CheckFailed("'vscale_range' minimum must be power-of-two value", V);
2658 std::optional<unsigned> VScaleMax = Attrs.getFnAttrs().getVScaleRangeMax();
2659 if (VScaleMax && VScaleMin > VScaleMax)
2660 CheckFailed("'vscale_range' minimum cannot be greater than maximum", V);
2661 else if (VScaleMax && !isPowerOf2_32(*VScaleMax))
2662 CheckFailed("'vscale_range' maximum must be power-of-two value", V);
2663 }
2664
2665 if (Attribute FPAttr = Attrs.getFnAttr("frame-pointer"); FPAttr.isValid()) {
2666 StringRef FP = FPAttr.getValueAsString();
2667 if (FP != "all" && FP != "non-leaf" && FP != "none" && FP != "reserved" &&
2668 FP != "non-leaf-no-reserve")
2669 CheckFailed("invalid value for 'frame-pointer' attribute: " + FP, V);
2670 }
2671
2672 checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-prefix", V);
2673 checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-entry", V);
2674 if (Attrs.hasFnAttr("patchable-function-entry-section"))
2675 Check(!Attrs.getFnAttr("patchable-function-entry-section")
2676 .getValueAsString()
2677 .empty(),
2678 "\"patchable-function-entry-section\" must not be empty");
2679 checkUnsignedBaseTenFuncAttr(Attrs, "warn-stack-size", V);
2680
2681 if (auto A = Attrs.getFnAttr("sign-return-address"); A.isValid()) {
2682 StringRef S = A.getValueAsString();
2683 if (S != "none" && S != "all" && S != "non-leaf")
2684 CheckFailed("invalid value for 'sign-return-address' attribute: " + S, V);
2685 }
2686
2687 if (auto A = Attrs.getFnAttr("sign-return-address-key"); A.isValid()) {
2688 StringRef S = A.getValueAsString();
2689 if (S != "a_key" && S != "b_key")
2690 CheckFailed("invalid value for 'sign-return-address-key' attribute: " + S,
2691 V);
2692 if (auto AA = Attrs.getFnAttr("sign-return-address"); !AA.isValid()) {
2693 CheckFailed(
2694 "'sign-return-address-key' present without `sign-return-address`");
2695 }
2696 }
2697
2698 if (auto A = Attrs.getFnAttr("branch-target-enforcement"); A.isValid()) {
2699 StringRef S = A.getValueAsString();
2700 if (S != "" && S != "true" && S != "false")
2701 CheckFailed(
2702 "invalid value for 'branch-target-enforcement' attribute: " + S, V);
2703 }
2704
2705 if (auto A = Attrs.getFnAttr("branch-protection-pauth-lr"); A.isValid()) {
2706 StringRef S = A.getValueAsString();
2707 if (S != "" && S != "true" && S != "false")
2708 CheckFailed(
2709 "invalid value for 'branch-protection-pauth-lr' attribute: " + S, V);
2710 }
2711
2712 if (auto A = Attrs.getFnAttr("guarded-control-stack"); A.isValid()) {
2713 StringRef S = A.getValueAsString();
2714 if (S != "" && S != "true" && S != "false")
2715 CheckFailed("invalid value for 'guarded-control-stack' attribute: " + S,
2716 V);
2717 }
2718
2719 if (auto A = Attrs.getFnAttr("vector-function-abi-variant"); A.isValid()) {
2720 StringRef S = A.getValueAsString();
2721 const std::optional<VFInfo> Info = VFABI::tryDemangleForVFABI(S, FT);
2722 if (!Info)
2723 CheckFailed("invalid name for a VFABI variant: " + S, V);
2724 }
2725
2726 if (auto A = Attrs.getFnAttr("modular-format"); A.isValid()) {
2727 StringRef S = A.getValueAsString();
2729 S.split(Args, ',');
2730 Check(Args.size() >= 5,
2731 "modular-format attribute requires at least 5 arguments", V);
2732 unsigned FirstArgIdx;
2733 Check(!Args[2].getAsInteger(10, FirstArgIdx),
2734 "modular-format attribute first arg index is not an integer", V);
2735 unsigned UpperBound = FT->getNumParams() + (FT->isVarArg() ? 1 : 0);
2736 Check(FirstArgIdx <= UpperBound,
2737 "modular-format attribute first arg index is out of bounds", V);
2738 }
2739
2740 if (auto A = Attrs.getFnAttr("target-features"); A.isValid()) {
2741 StringRef S = A.getValueAsString();
2742 if (!S.empty()) {
2743 for (auto FeatureFlag : split(S, ',')) {
2744 if (FeatureFlag.empty())
2745 CheckFailed(
2746 "target-features attribute should not contain an empty string");
2747 else
2748 Check(FeatureFlag[0] == '+' || FeatureFlag[0] == '-',
2749 "target feature '" + FeatureFlag +
2750 "' must start with a '+' or '-'",
2751 V);
2752 }
2753 }
2754 }
2755}
2756void Verifier::verifyUnknownProfileMetadata(MDNode *MD) {
2757 Check(MD->getNumOperands() == 2,
2758 "'unknown' !prof should have a single additional operand", MD);
2759 auto *PassName = dyn_cast<MDString>(MD->getOperand(1));
2760 Check(PassName != nullptr,
2761 "'unknown' !prof should have an additional operand of type "
2762 "string");
2763 Check(!PassName->getString().empty(),
2764 "the 'unknown' !prof operand should not be an empty string");
2765}
2766
2767void Verifier::verifyFunctionMetadata(
2768 ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
2769 for (const auto &Pair : MDs) {
2770 if (Pair.first == LLVMContext::MD_prof) {
2771 MDNode *MD = Pair.second;
2772 Check(MD->getNumOperands() >= 2,
2773 "!prof annotations should have no less than 2 operands", MD);
2774 // We may have functions that are synthesized by the compiler, e.g. in
2775 // WPD, that we can't currently determine the entry count.
2776 if (MD->getOperand(0).equalsStr(
2778 verifyUnknownProfileMetadata(MD);
2779 continue;
2780 }
2781
2782 // Check first operand.
2783 Check(MD->getOperand(0) != nullptr, "first operand should not be null",
2784 MD);
2786 "expected string with name of the !prof annotation", MD);
2787 MDString *MDS = cast<MDString>(MD->getOperand(0));
2788 StringRef ProfName = MDS->getString();
2791 "first operand should be 'function_entry_count'"
2792 " or 'synthetic_function_entry_count'",
2793 MD);
2794
2795 // Check second operand.
2796 Check(MD->getOperand(1) != nullptr, "second operand should not be null",
2797 MD);
2799 "expected integer argument to function_entry_count", MD);
2800 } else if (Pair.first == LLVMContext::MD_kcfi_type) {
2801 MDNode *MD = Pair.second;
2802 Check(MD->getNumOperands() == 1,
2803 "!kcfi_type must have exactly one operand", MD);
2804 Check(MD->getOperand(0) != nullptr, "!kcfi_type operand must not be null",
2805 MD);
2807 "expected a constant operand for !kcfi_type", MD);
2808 Constant *C = cast<ConstantAsMetadata>(MD->getOperand(0))->getValue();
2809 Check(isa<ConstantInt>(C) && isa<IntegerType>(C->getType()),
2810 "expected a constant integer operand for !kcfi_type", MD);
2812 "expected a 32-bit integer constant operand for !kcfi_type", MD);
2813 }
2814 }
2815}
2816
2817void Verifier::visitConstantExprsRecursively(const Constant *EntryC) {
2818 if (EntryC->getNumOperands() == 0)
2819 return;
2820
2821 if (!ConstantExprVisited.insert(EntryC).second)
2822 return;
2823
2825 Stack.push_back(EntryC);
2826
2827 while (!Stack.empty()) {
2828 const Constant *C = Stack.pop_back_val();
2829
2830 // Check this constant expression.
2831 if (const auto *CE = dyn_cast<ConstantExpr>(C))
2832 visitConstantExpr(CE);
2833
2834 if (const auto *CPA = dyn_cast<ConstantPtrAuth>(C))
2835 visitConstantPtrAuth(CPA);
2836
2837 if (const auto *GV = dyn_cast<GlobalValue>(C)) {
2838 // Global Values get visited separately, but we do need to make sure
2839 // that the global value is in the correct module
2840 Check(GV->getParent() == &M, "Referencing global in another module!",
2841 EntryC, &M, GV, GV->getParent());
2842 continue;
2843 }
2844
2845 // Visit all sub-expressions.
2846 for (const Use &U : C->operands()) {
2847 const auto *OpC = dyn_cast<Constant>(U);
2848 if (!OpC)
2849 continue;
2850 if (!ConstantExprVisited.insert(OpC).second)
2851 continue;
2852 Stack.push_back(OpC);
2853 }
2854 }
2855}
2856
2857void Verifier::visitConstantExpr(const ConstantExpr *CE) {
2858 if (CE->getOpcode() == Instruction::BitCast)
2859 Check(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
2860 CE->getType()),
2861 "Invalid bitcast", CE);
2862 else if (CE->getOpcode() == Instruction::PtrToAddr)
2863 checkPtrToAddr(CE->getOperand(0)->getType(), CE->getType(), *CE);
2864}
2865
2866void Verifier::visitConstantPtrAuth(const ConstantPtrAuth *CPA) {
2867 Check(CPA->getPointer()->getType()->isPointerTy(),
2868 "signed ptrauth constant base pointer must have pointer type");
2869
2870 Check(CPA->getType() == CPA->getPointer()->getType(),
2871 "signed ptrauth constant must have same type as its base pointer");
2872
2873 Check(CPA->getKey()->getBitWidth() == 32,
2874 "signed ptrauth constant key must be i32 constant integer");
2875
2877 "signed ptrauth constant address discriminator must be a pointer");
2878
2879 Check(CPA->getDiscriminator()->getBitWidth() == 64,
2880 "signed ptrauth constant discriminator must be i64 constant integer");
2881
2883 "signed ptrauth constant deactivation symbol must be a pointer");
2884
2887 "signed ptrauth constant deactivation symbol must be a global value "
2888 "or null");
2889}
2890
2891bool Verifier::verifyAttributeCount(AttributeList Attrs, unsigned Params) {
2892 // There shouldn't be more attribute sets than there are parameters plus the
2893 // function and return value.
2894 return Attrs.getNumAttrSets() <= Params + 2;
2895}
2896
2897void Verifier::verifyInlineAsmCall(const CallBase &Call) {
2898 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
2899 unsigned ArgNo = 0;
2900 unsigned LabelNo = 0;
2901 for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
2902 if (CI.Type == InlineAsm::isLabel) {
2903 ++LabelNo;
2904 continue;
2905 }
2906
2907 // Only deal with constraints that correspond to call arguments.
2908 if (!CI.hasArg())
2909 continue;
2910
2911 if (CI.isIndirect) {
2912 const Value *Arg = Call.getArgOperand(ArgNo);
2913 Check(Arg->getType()->isPointerTy(),
2914 "Operand for indirect constraint must have pointer type", &Call);
2915
2917 "Operand for indirect constraint must have elementtype attribute",
2918 &Call);
2919 } else {
2920 Check(!Call.paramHasAttr(ArgNo, Attribute::ElementType),
2921 "Elementtype attribute can only be applied for indirect "
2922 "constraints",
2923 &Call);
2924 }
2925
2926 ArgNo++;
2927 }
2928
2929 if (auto *CallBr = dyn_cast<CallBrInst>(&Call)) {
2930 Check(LabelNo == CallBr->getNumIndirectDests(),
2931 "Number of label constraints does not match number of callbr dests",
2932 &Call);
2933 } else {
2934 Check(LabelNo == 0, "Label constraints can only be used with callbr",
2935 &Call);
2936 }
2937}
2938
2939/// Verify that statepoint intrinsic is well formed.
2940void Verifier::verifyStatepoint(const CallBase &Call) {
2941 assert(Call.getIntrinsicID() == Intrinsic::experimental_gc_statepoint);
2942
2945 "gc.statepoint must read and write all memory to preserve "
2946 "reordering restrictions required by safepoint semantics",
2947 Call);
2948
2949 const int64_t NumPatchBytes =
2950 cast<ConstantInt>(Call.getArgOperand(1))->getSExtValue();
2951 assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!");
2952 Check(NumPatchBytes >= 0,
2953 "gc.statepoint number of patchable bytes must be "
2954 "positive",
2955 Call);
2956
2957 Type *TargetElemType = Call.getParamElementType(2);
2958 Check(TargetElemType,
2959 "gc.statepoint callee argument must have elementtype attribute", Call);
2960 FunctionType *TargetFuncType = dyn_cast<FunctionType>(TargetElemType);
2961 Check(TargetFuncType,
2962 "gc.statepoint callee elementtype must be function type", Call);
2963
2964 const int NumCallArgs = cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue();
2965 Check(NumCallArgs >= 0,
2966 "gc.statepoint number of arguments to underlying call "
2967 "must be positive",
2968 Call);
2969 const int NumParams = (int)TargetFuncType->getNumParams();
2970 if (TargetFuncType->isVarArg()) {
2971 Check(NumCallArgs >= NumParams,
2972 "gc.statepoint mismatch in number of vararg call args", Call);
2973
2974 // TODO: Remove this limitation
2975 Check(TargetFuncType->getReturnType()->isVoidTy(),
2976 "gc.statepoint doesn't support wrapping non-void "
2977 "vararg functions yet",
2978 Call);
2979 } else
2980 Check(NumCallArgs == NumParams,
2981 "gc.statepoint mismatch in number of call args", Call);
2982
2983 const uint64_t Flags
2984 = cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue();
2985 Check((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
2986 "unknown flag used in gc.statepoint flags argument", Call);
2987
2988 // Verify that the types of the call parameter arguments match
2989 // the type of the wrapped callee.
2990 AttributeList Attrs = Call.getAttributes();
2991 for (int i = 0; i < NumParams; i++) {
2992 Type *ParamType = TargetFuncType->getParamType(i);
2993 Type *ArgType = Call.getArgOperand(5 + i)->getType();
2994 Check(ArgType == ParamType,
2995 "gc.statepoint call argument does not match wrapped "
2996 "function type",
2997 Call);
2998
2999 if (TargetFuncType->isVarArg()) {
3000 AttributeSet ArgAttrs = Attrs.getParamAttrs(5 + i);
3001 Check(!ArgAttrs.hasAttribute(Attribute::StructRet),
3002 "Attribute 'sret' cannot be used for vararg call arguments!", Call);
3003 }
3004 }
3005
3006 const int EndCallArgsInx = 4 + NumCallArgs;
3007
3008 const Value *NumTransitionArgsV = Call.getArgOperand(EndCallArgsInx + 1);
3009 Check(isa<ConstantInt>(NumTransitionArgsV),
3010 "gc.statepoint number of transition arguments "
3011 "must be constant integer",
3012 Call);
3013 const int NumTransitionArgs =
3014 cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
3015 Check(NumTransitionArgs == 0,
3016 "gc.statepoint w/inline transition bundle is deprecated", Call);
3017 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
3018
3019 const Value *NumDeoptArgsV = Call.getArgOperand(EndTransitionArgsInx + 1);
3020 Check(isa<ConstantInt>(NumDeoptArgsV),
3021 "gc.statepoint number of deoptimization arguments "
3022 "must be constant integer",
3023 Call);
3024 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
3025 Check(NumDeoptArgs == 0,
3026 "gc.statepoint w/inline deopt operands is deprecated", Call);
3027
3028 const int ExpectedNumArgs = 7 + NumCallArgs;
3029 Check(ExpectedNumArgs == (int)Call.arg_size(),
3030 "gc.statepoint too many arguments", Call);
3031
3032 // Check that the only uses of this gc.statepoint are gc.result or
3033 // gc.relocate calls which are tied to this statepoint and thus part
3034 // of the same statepoint sequence
3035 for (const User *U : Call.users()) {
3036 const CallInst *UserCall = dyn_cast<const CallInst>(U);
3037 Check(UserCall, "illegal use of statepoint token", Call, U);
3038 if (!UserCall)
3039 continue;
3040 Check(isa<GCRelocateInst>(UserCall) || isa<GCResultInst>(UserCall),
3041 "gc.result or gc.relocate are the only value uses "
3042 "of a gc.statepoint",
3043 Call, U);
3044 if (isa<GCResultInst>(UserCall)) {
3045 Check(UserCall->getArgOperand(0) == &Call,
3046 "gc.result connected to wrong gc.statepoint", Call, UserCall);
3047 } else if (isa<GCRelocateInst>(Call)) {
3048 Check(UserCall->getArgOperand(0) == &Call,
3049 "gc.relocate connected to wrong gc.statepoint", Call, UserCall);
3050 }
3051 }
3052
3053 // Note: It is legal for a single derived pointer to be listed multiple
3054 // times. It's non-optimal, but it is legal. It can also happen after
3055 // insertion if we strip a bitcast away.
3056 // Note: It is really tempting to check that each base is relocated and
3057 // that a derived pointer is never reused as a base pointer. This turns
3058 // out to be problematic since optimizations run after safepoint insertion
3059 // can recognize equality properties that the insertion logic doesn't know
3060 // about. See example statepoint.ll in the verifier subdirectory
3061}
3062
3063void Verifier::verifyFrameRecoverIndices() {
3064 for (auto &Counts : FrameEscapeInfo) {
3065 Function *F = Counts.first;
3066 unsigned EscapedObjectCount = Counts.second.first;
3067 unsigned MaxRecoveredIndex = Counts.second.second;
3068 Check(MaxRecoveredIndex <= EscapedObjectCount,
3069 "all indices passed to llvm.localrecover must be less than the "
3070 "number of arguments passed to llvm.localescape in the parent "
3071 "function",
3072 F);
3073 }
3074}
3075
3076static Instruction *getSuccPad(Instruction *Terminator) {
3077 BasicBlock *UnwindDest;
3078 if (auto *II = dyn_cast<InvokeInst>(Terminator))
3079 UnwindDest = II->getUnwindDest();
3080 else if (auto *CSI = dyn_cast<CatchSwitchInst>(Terminator))
3081 UnwindDest = CSI->getUnwindDest();
3082 else
3083 UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest();
3084 return &*UnwindDest->getFirstNonPHIIt();
3085}
3086
3087void Verifier::verifySiblingFuncletUnwinds() {
3088 llvm::TimeTraceScope timeScope("Verifier verify sibling funclet unwinds");
3089 SmallPtrSet<Instruction *, 8> Visited;
3090 SmallPtrSet<Instruction *, 8> Active;
3091 for (const auto &Pair : SiblingFuncletInfo) {
3092 Instruction *PredPad = Pair.first;
3093 if (Visited.count(PredPad))
3094 continue;
3095 Active.insert(PredPad);
3096 Instruction *Terminator = Pair.second;
3097 do {
3098 Instruction *SuccPad = getSuccPad(Terminator);
3099 if (Active.count(SuccPad)) {
3100 // Found a cycle; report error
3101 Instruction *CyclePad = SuccPad;
3102 SmallVector<Instruction *, 8> CycleNodes;
3103 do {
3104 CycleNodes.push_back(CyclePad);
3105 Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
3106 if (CycleTerminator != CyclePad)
3107 CycleNodes.push_back(CycleTerminator);
3108 CyclePad = getSuccPad(CycleTerminator);
3109 } while (CyclePad != SuccPad);
3110 Check(false, "EH pads can't handle each other's exceptions",
3111 ArrayRef<Instruction *>(CycleNodes));
3112 }
3113 // Don't re-walk a node we've already checked
3114 if (!Visited.insert(SuccPad).second)
3115 break;
3116 // Walk to this successor if it has a map entry.
3117 PredPad = SuccPad;
3118 auto TermI = SiblingFuncletInfo.find(PredPad);
3119 if (TermI == SiblingFuncletInfo.end())
3120 break;
3121 Terminator = TermI->second;
3122 Active.insert(PredPad);
3123 } while (true);
3124 // Each node only has one successor, so we've walked all the active
3125 // nodes' successors.
3126 Active.clear();
3127 }
3128}
3129
3130// visitFunction - Verify that a function is ok.
3131//
3132void Verifier::visitFunction(const Function &F) {
3133 visitGlobalValue(F);
3134
3135 // Check function arguments.
3136 FunctionType *FT = F.getFunctionType();
3137 unsigned NumArgs = F.arg_size();
3138
3139 Check(&Context == &F.getContext(),
3140 "Function context does not match Module context!", &F);
3141
3142 Check(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
3143 Check(FT->getNumParams() == NumArgs,
3144 "# formal arguments must match # of arguments for function type!", &F,
3145 FT);
3146 Check(F.getReturnType()->isFirstClassType() ||
3147 F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
3148 "Functions cannot return aggregate values!", &F);
3149
3150 Check(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
3151 "Invalid struct return type!", &F);
3152
3153 if (MaybeAlign A = F.getAlign()) {
3154 Check(A->value() <= Value::MaximumAlignment,
3155 "huge alignment values are unsupported", &F);
3156 }
3157
3158 AttributeList Attrs = F.getAttributes();
3159
3160 Check(verifyAttributeCount(Attrs, FT->getNumParams()),
3161 "Attribute after last parameter!", &F);
3162
3163 bool IsIntrinsic = F.isIntrinsic();
3164
3165 // Check function attributes.
3166 verifyFunctionAttrs(FT, Attrs, &F, IsIntrinsic, /* IsInlineAsm */ false);
3167
3168 // On function declarations/definitions, we do not support the builtin
3169 // attribute. We do not check this in VerifyFunctionAttrs since that is
3170 // checking for Attributes that can/can not ever be on functions.
3171 Check(!Attrs.hasFnAttr(Attribute::Builtin),
3172 "Attribute 'builtin' can only be applied to a callsite.", &F);
3173
3174 Check(!Attrs.hasAttrSomewhere(Attribute::ElementType),
3175 "Attribute 'elementtype' can only be applied to a callsite.", &F);
3176
3177 if (Attrs.hasFnAttr(Attribute::Naked))
3178 for (const Argument &Arg : F.args())
3179 Check(Arg.use_empty(), "cannot use argument of naked function", &Arg);
3180
3181 // Check that this function meets the restrictions on this calling convention.
3182 // Sometimes varargs is used for perfectly forwarding thunks, so some of these
3183 // restrictions can be lifted.
3184 switch (F.getCallingConv()) {
3185 default:
3186 case CallingConv::C:
3187 break;
3188 case CallingConv::X86_INTR: {
3189 Check(F.arg_empty() || Attrs.hasParamAttr(0, Attribute::ByVal),
3190 "Calling convention parameter requires byval", &F);
3191 break;
3192 }
3193 case CallingConv::AMDGPU_KERNEL:
3194 case CallingConv::SPIR_KERNEL:
3195 case CallingConv::AMDGPU_CS_Chain:
3196 case CallingConv::AMDGPU_CS_ChainPreserve:
3197 Check(F.getReturnType()->isVoidTy(),
3198 "Calling convention requires void return type", &F);
3199 [[fallthrough]];
3200 case CallingConv::AMDGPU_VS:
3201 case CallingConv::AMDGPU_HS:
3202 case CallingConv::AMDGPU_GS:
3203 case CallingConv::AMDGPU_PS:
3204 case CallingConv::AMDGPU_CS:
3205 Check(!F.hasStructRetAttr(), "Calling convention does not allow sret", &F);
3206 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3207 const unsigned StackAS = DL.getAllocaAddrSpace();
3208 unsigned i = 0;
3209 for (const Argument &Arg : F.args()) {
3210 Check(!Attrs.hasParamAttr(i, Attribute::ByVal),
3211 "Calling convention disallows byval", &F);
3212 Check(!Attrs.hasParamAttr(i, Attribute::Preallocated),
3213 "Calling convention disallows preallocated", &F);
3214 Check(!Attrs.hasParamAttr(i, Attribute::InAlloca),
3215 "Calling convention disallows inalloca", &F);
3216
3217 if (Attrs.hasParamAttr(i, Attribute::ByRef)) {
3218 // FIXME: Should also disallow LDS and GDS, but we don't have the enum
3219 // value here.
3220 Check(Arg.getType()->getPointerAddressSpace() != StackAS,
3221 "Calling convention disallows stack byref", &F);
3222 }
3223
3224 ++i;
3225 }
3226 }
3227
3228 [[fallthrough]];
3229 case CallingConv::Fast:
3230 case CallingConv::Cold:
3231 case CallingConv::Intel_OCL_BI:
3232 case CallingConv::PTX_Kernel:
3233 case CallingConv::PTX_Device:
3234 Check(!F.isVarArg(),
3235 "Calling convention does not support varargs or "
3236 "perfect forwarding!",
3237 &F);
3238 break;
3239 case CallingConv::AMDGPU_Gfx_WholeWave:
3240 Check(!F.arg_empty() && F.arg_begin()->getType()->isIntegerTy(1),
3241 "Calling convention requires first argument to be i1", &F);
3242 Check(!F.arg_begin()->hasInRegAttr(),
3243 "Calling convention requires first argument to not be inreg", &F);
3244 Check(!F.isVarArg(),
3245 "Calling convention does not support varargs or "
3246 "perfect forwarding!",
3247 &F);
3248 break;
3249 }
3250
3251 // Check that the argument values match the function type for this function...
3252 unsigned i = 0;
3253 for (const Argument &Arg : F.args()) {
3254 Check(Arg.getType() == FT->getParamType(i),
3255 "Argument value does not match function argument type!", &Arg,
3256 FT->getParamType(i));
3257 Check(Arg.getType()->isFirstClassType(),
3258 "Function arguments must have first-class types!", &Arg);
3259 if (!IsIntrinsic) {
3260 Check(!Arg.getType()->isMetadataTy(),
3261 "Function takes metadata but isn't an intrinsic", &Arg, &F);
3262 Check(!Arg.getType()->isTokenLikeTy(),
3263 "Function takes token but isn't an intrinsic", &Arg, &F);
3264 Check(!Arg.getType()->isX86_AMXTy(),
3265 "Function takes x86_amx but isn't an intrinsic", &Arg, &F);
3266 }
3267
3268 // Check that swifterror argument is only used by loads and stores.
3269 if (Attrs.hasParamAttr(i, Attribute::SwiftError)) {
3270 verifySwiftErrorValue(&Arg);
3271 }
3272 ++i;
3273 }
3274
3275 if (!IsIntrinsic) {
3276 Check(!F.getReturnType()->isTokenLikeTy(),
3277 "Function returns a token but isn't an intrinsic", &F);
3278 Check(!F.getReturnType()->isX86_AMXTy(),
3279 "Function returns a x86_amx but isn't an intrinsic", &F);
3280 }
3281
3282 // Get the function metadata attachments.
3284 F.getAllMetadata(MDs);
3285 assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync");
3286 verifyFunctionMetadata(MDs);
3287
3288 // Check validity of the personality function
3289 if (F.hasPersonalityFn()) {
3290 auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
3291 if (Per)
3292 Check(Per->getParent() == F.getParent(),
3293 "Referencing personality function in another module!", &F,
3294 F.getParent(), Per, Per->getParent());
3295 }
3296
3297 // EH funclet coloring can be expensive, recompute on-demand
3298 BlockEHFuncletColors.clear();
3299
3300 if (F.isMaterializable()) {
3301 // Function has a body somewhere we can't see.
3302 Check(MDs.empty(), "unmaterialized function cannot have metadata", &F,
3303 MDs.empty() ? nullptr : MDs.front().second);
3304 } else if (F.isDeclaration()) {
3305 for (const auto &I : MDs) {
3306 // This is used for call site debug information.
3307 CheckDI(I.first != LLVMContext::MD_dbg ||
3308 !cast<DISubprogram>(I.second)->isDistinct(),
3309 "function declaration may only have a unique !dbg attachment",
3310 &F);
3311 Check(I.first != LLVMContext::MD_prof,
3312 "function declaration may not have a !prof attachment", &F);
3313
3314 // Verify the metadata itself.
3315 visitMDNode(*I.second, AreDebugLocsAllowed::Yes);
3316 }
3317 Check(!F.hasPersonalityFn(),
3318 "Function declaration shouldn't have a personality routine", &F);
3319 } else {
3320 // Verify that this function (which has a body) is not named "llvm.*". It
3321 // is not legal to define intrinsics.
3322 Check(!IsIntrinsic, "llvm intrinsics cannot be defined!", &F);
3323
3324 // Check the entry node
3325 const BasicBlock *Entry = &F.getEntryBlock();
3326 Check(pred_empty(Entry),
3327 "Entry block to function must not have predecessors!", Entry);
3328
3329 // The address of the entry block cannot be taken, unless it is dead.
3330 if (Entry->hasAddressTaken()) {
3331 Check(!BlockAddress::lookup(Entry)->isConstantUsed(),
3332 "blockaddress may not be used with the entry block!", Entry);
3333 }
3334
3335 unsigned NumDebugAttachments = 0, NumProfAttachments = 0,
3336 NumKCFIAttachments = 0;
3337 // Visit metadata attachments.
3338 for (const auto &I : MDs) {
3339 // Verify that the attachment is legal.
3340 auto AllowLocs = AreDebugLocsAllowed::No;
3341 switch (I.first) {
3342 default:
3343 break;
3344 case LLVMContext::MD_dbg: {
3345 ++NumDebugAttachments;
3346 CheckDI(NumDebugAttachments == 1,
3347 "function must have a single !dbg attachment", &F, I.second);
3348 CheckDI(isa<DISubprogram>(I.second),
3349 "function !dbg attachment must be a subprogram", &F, I.second);
3350 CheckDI(cast<DISubprogram>(I.second)->isDistinct(),
3351 "function definition may only have a distinct !dbg attachment",
3352 &F);
3353
3354 auto *SP = cast<DISubprogram>(I.second);
3355 const Function *&AttachedTo = DISubprogramAttachments[SP];
3356 CheckDI(!AttachedTo || AttachedTo == &F,
3357 "DISubprogram attached to more than one function", SP, &F);
3358 AttachedTo = &F;
3359 AllowLocs = AreDebugLocsAllowed::Yes;
3360 break;
3361 }
3362 case LLVMContext::MD_prof:
3363 ++NumProfAttachments;
3364 Check(NumProfAttachments == 1,
3365 "function must have a single !prof attachment", &F, I.second);
3366 break;
3367 case LLVMContext::MD_kcfi_type:
3368 ++NumKCFIAttachments;
3369 Check(NumKCFIAttachments == 1,
3370 "function must have a single !kcfi_type attachment", &F,
3371 I.second);
3372 break;
3373 }
3374
3375 // Verify the metadata itself.
3376 visitMDNode(*I.second, AllowLocs);
3377 }
3378 }
3379
3380 // If this function is actually an intrinsic, verify that it is only used in
3381 // direct call/invokes, never having its "address taken".
3382 // Only do this if the module is materialized, otherwise we don't have all the
3383 // uses.
3384 if (F.isIntrinsic() && F.getParent()->isMaterialized()) {
3385 const User *U;
3386 if (F.hasAddressTaken(&U, false, true, false,
3387 /*IgnoreARCAttachedCall=*/true))
3388 Check(false, "Invalid user of intrinsic instruction!", U);
3389 }
3390
3391 // Check intrinsics' signatures.
3392 switch (F.getIntrinsicID()) {
3393 case Intrinsic::experimental_gc_get_pointer_base: {
3394 FunctionType *FT = F.getFunctionType();
3395 Check(FT->getNumParams() == 1, "wrong number of parameters", F);
3396 Check(isa<PointerType>(F.getReturnType()),
3397 "gc.get.pointer.base must return a pointer", F);
3398 Check(FT->getParamType(0) == F.getReturnType(),
3399 "gc.get.pointer.base operand and result must be of the same type", F);
3400 break;
3401 }
3402 case Intrinsic::experimental_gc_get_pointer_offset: {
3403 FunctionType *FT = F.getFunctionType();
3404 Check(FT->getNumParams() == 1, "wrong number of parameters", F);
3405 Check(isa<PointerType>(FT->getParamType(0)),
3406 "gc.get.pointer.offset operand must be a pointer", F);
3407 Check(F.getReturnType()->isIntegerTy(),
3408 "gc.get.pointer.offset must return integer", F);
3409 break;
3410 }
3411 }
3412
3413 auto *N = F.getSubprogram();
3414 HasDebugInfo = (N != nullptr);
3415 if (!HasDebugInfo)
3416 return;
3417
3418 // Check that all !dbg attachments lead to back to N.
3419 //
3420 // FIXME: Check this incrementally while visiting !dbg attachments.
3421 // FIXME: Only check when N is the canonical subprogram for F.
3422 SmallPtrSet<const MDNode *, 32> Seen;
3423 auto VisitDebugLoc = [&](const Instruction &I, const MDNode *Node) {
3424 // Be careful about using DILocation here since we might be dealing with
3425 // broken code (this is the Verifier after all).
3426 const DILocation *DL = dyn_cast_or_null<DILocation>(Node);
3427 if (!DL)
3428 return;
3429 if (!Seen.insert(DL).second)
3430 return;
3431
3432 Metadata *Parent = DL->getRawScope();
3433 CheckDI(Parent && isa<DILocalScope>(Parent),
3434 "DILocation's scope must be a DILocalScope", N, &F, &I, DL, Parent);
3435
3436 DILocalScope *Scope = DL->getInlinedAtScope();
3437 Check(Scope, "Failed to find DILocalScope", DL);
3438
3439 if (!Seen.insert(Scope).second)
3440 return;
3441
3442 DISubprogram *SP = Scope->getSubprogram();
3443
3444 // Scope and SP could be the same MDNode and we don't want to skip
3445 // validation in that case
3446 if ((Scope != SP) && !Seen.insert(SP).second)
3447 return;
3448
3449 CheckDI(SP->describes(&F),
3450 "!dbg attachment points at wrong subprogram for function", N, &F,
3451 &I, DL, Scope, SP);
3452 };
3453 for (auto &BB : F)
3454 for (auto &I : BB) {
3455 VisitDebugLoc(I, I.getDebugLoc().getAsMDNode());
3456 // The llvm.loop annotations also contain two DILocations.
3457 if (auto MD = I.getMetadata(LLVMContext::MD_loop))
3458 for (unsigned i = 1; i < MD->getNumOperands(); ++i)
3459 VisitDebugLoc(I, dyn_cast_or_null<MDNode>(MD->getOperand(i)));
3460 if (BrokenDebugInfo)
3461 return;
3462 }
3463}
3464
3465// verifyBasicBlock - Verify that a basic block is well formed...
3466//
3467void Verifier::visitBasicBlock(BasicBlock &BB) {
3468 InstsInThisBlock.clear();
3469 ConvergenceVerifyHelper.visit(BB);
3470
3471 // Ensure that basic blocks have terminators!
3472 Check(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
3473
3474 // Check constraints that this basic block imposes on all of the PHI nodes in
3475 // it.
3476 if (isa<PHINode>(BB.front())) {
3477 SmallVector<BasicBlock *, 8> Preds(predecessors(&BB));
3479 llvm::sort(Preds);
3480 for (const PHINode &PN : BB.phis()) {
3481 Check(PN.getNumIncomingValues() == Preds.size(),
3482 "PHINode should have one entry for each predecessor of its "
3483 "parent basic block!",
3484 &PN);
3485
3486 // Get and sort all incoming values in the PHI node...
3487 Values.clear();
3488 Values.reserve(PN.getNumIncomingValues());
3489 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3490 Values.push_back(
3491 std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
3492 llvm::sort(Values);
3493
3494 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
3495 // Check to make sure that if there is more than one entry for a
3496 // particular basic block in this PHI node, that the incoming values are
3497 // all identical.
3498 //
3499 Check(i == 0 || Values[i].first != Values[i - 1].first ||
3500 Values[i].second == Values[i - 1].second,
3501 "PHI node has multiple entries for the same basic block with "
3502 "different incoming values!",
3503 &PN, Values[i].first, Values[i].second, Values[i - 1].second);
3504
3505 // Check to make sure that the predecessors and PHI node entries are
3506 // matched up.
3507 Check(Values[i].first == Preds[i],
3508 "PHI node entries do not match predecessors!", &PN,
3509 Values[i].first, Preds[i]);
3510 }
3511 }
3512 }
3513
3514 // Check that all instructions have their parent pointers set up correctly.
3515 for (auto &I : BB)
3516 {
3517 Check(I.getParent() == &BB, "Instruction has bogus parent pointer!");
3518 }
3519
3520 // Confirm that no issues arise from the debug program.
3521 CheckDI(!BB.getTrailingDbgRecords(), "Basic Block has trailing DbgRecords!",
3522 &BB);
3523}
3524
3525void Verifier::visitTerminator(Instruction &I) {
3526 // Ensure that terminators only exist at the end of the basic block.
3527 Check(&I == I.getParent()->getTerminator(),
3528 "Terminator found in the middle of a basic block!", I.getParent());
3529 visitInstruction(I);
3530}
3531
3532void Verifier::visitCondBrInst(CondBrInst &BI) {
3534 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
3535 visitTerminator(BI);
3536}
3537
3538void Verifier::visitReturnInst(ReturnInst &RI) {
3539 Function *F = RI.getParent()->getParent();
3540 unsigned N = RI.getNumOperands();
3541 if (F->getReturnType()->isVoidTy())
3542 Check(N == 0,
3543 "Found return instr that returns non-void in Function of void "
3544 "return type!",
3545 &RI, F->getReturnType());
3546 else
3547 Check(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
3548 "Function return type does not match operand "
3549 "type of return inst!",
3550 &RI, F->getReturnType());
3551
3552 // Check to make sure that the return value has necessary properties for
3553 // terminators...
3554 visitTerminator(RI);
3555}
3556
3557void Verifier::visitSwitchInst(SwitchInst &SI) {
3558 Check(SI.getType()->isVoidTy(), "Switch must have void result type!", &SI);
3559 // Check to make sure that all of the constants in the switch instruction
3560 // have the same type as the switched-on value.
3561 Type *SwitchTy = SI.getCondition()->getType();
3562 SmallPtrSet<ConstantInt*, 32> Constants;
3563 for (auto &Case : SI.cases()) {
3564 Check(isa<ConstantInt>(Case.getCaseValue()),
3565 "Case value is not a constant integer.", &SI);
3566 Check(Case.getCaseValue()->getType() == SwitchTy,
3567 "Switch constants must all be same type as switch value!", &SI);
3568 Check(Constants.insert(Case.getCaseValue()).second,
3569 "Duplicate integer as switch case", &SI, Case.getCaseValue());
3570 }
3571
3572 visitTerminator(SI);
3573}
3574
3575void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
3577 "Indirectbr operand must have pointer type!", &BI);
3578 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
3580 "Indirectbr destinations must all have pointer type!", &BI);
3581
3582 visitTerminator(BI);
3583}
3584
3585void Verifier::visitCallBrInst(CallBrInst &CBI) {
3586 if (!CBI.isInlineAsm()) {
3588 "Callbr: indirect function / invalid signature");
3589 Check(!CBI.hasOperandBundles(),
3590 "Callbr for intrinsics currently doesn't support operand bundles");
3591
3592 switch (CBI.getIntrinsicID()) {
3593 case Intrinsic::amdgcn_kill: {
3594 Check(CBI.getNumIndirectDests() == 1,
3595 "Callbr amdgcn_kill only supports one indirect dest");
3596 bool Unreachable = isa<UnreachableInst>(CBI.getIndirectDest(0)->begin());
3597 CallInst *Call = dyn_cast<CallInst>(CBI.getIndirectDest(0)->begin());
3598 Check(Unreachable || (Call && Call->getIntrinsicID() ==
3599 Intrinsic::amdgcn_unreachable),
3600 "Callbr amdgcn_kill indirect dest needs to be unreachable");
3601 break;
3602 }
3603 default:
3604 CheckFailed(
3605 "Callbr currently only supports asm-goto and selected intrinsics");
3606 }
3607 visitIntrinsicCall(CBI.getIntrinsicID(), CBI);
3608 } else {
3609 const InlineAsm *IA = cast<InlineAsm>(CBI.getCalledOperand());
3610 Check(!IA->canThrow(), "Unwinding from Callbr is not allowed");
3611
3612 verifyInlineAsmCall(CBI);
3613 }
3614 visitTerminator(CBI);
3615}
3616
3617void Verifier::visitSelectInst(SelectInst &SI) {
3618 Check(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
3619 SI.getOperand(2)),
3620 "Invalid operands for select instruction!", &SI);
3621
3622 Check(SI.getTrueValue()->getType() == SI.getType(),
3623 "Select values must have same type as select instruction!", &SI);
3624 visitInstruction(SI);
3625}
3626
3627/// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
3628/// a pass, if any exist, it's an error.
3629///
3630void Verifier::visitUserOp1(Instruction &I) {
3631 Check(false, "User-defined operators should not live outside of a pass!", &I);
3632}
3633
3634void Verifier::visitTruncInst(TruncInst &I) {
3635 // Get the source and destination types
3636 Type *SrcTy = I.getOperand(0)->getType();
3637 Type *DestTy = I.getType();
3638
3639 // Get the size of the types in bits, we'll need this later
3640 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3641 unsigned DestBitSize = DestTy->getScalarSizeInBits();
3642
3643 Check(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
3644 Check(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
3645 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
3646 "trunc source and destination must both be a vector or neither", &I);
3647 Check(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
3648
3649 visitInstruction(I);
3650}
3651
3652void Verifier::visitZExtInst(ZExtInst &I) {
3653 // Get the source and destination types
3654 Type *SrcTy = I.getOperand(0)->getType();
3655 Type *DestTy = I.getType();
3656
3657 // Get the size of the types in bits, we'll need this later
3658 Check(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
3659 Check(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
3660 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
3661 "zext source and destination must both be a vector or neither", &I);
3662 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3663 unsigned DestBitSize = DestTy->getScalarSizeInBits();
3664
3665 Check(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
3666
3667 visitInstruction(I);
3668}
3669
3670void Verifier::visitSExtInst(SExtInst &I) {
3671 // Get the source and destination types
3672 Type *SrcTy = I.getOperand(0)->getType();
3673 Type *DestTy = I.getType();
3674
3675 // Get the size of the types in bits, we'll need this later
3676 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3677 unsigned DestBitSize = DestTy->getScalarSizeInBits();
3678
3679 Check(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
3680 Check(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
3681 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
3682 "sext source and destination must both be a vector or neither", &I);
3683 Check(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
3684
3685 visitInstruction(I);
3686}
3687
3688void Verifier::visitFPTruncInst(FPTruncInst &I) {
3689 // Get the source and destination types
3690 Type *SrcTy = I.getOperand(0)->getType();
3691 Type *DestTy = I.getType();
3692 // Get the size of the types in bits, we'll need this later
3693 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3694 unsigned DestBitSize = DestTy->getScalarSizeInBits();
3695
3696 Check(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
3697 Check(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
3698 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
3699 "fptrunc source and destination must both be a vector or neither", &I);
3700 Check(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
3701
3702 visitInstruction(I);
3703}
3704
3705void Verifier::visitFPExtInst(FPExtInst &I) {
3706 // Get the source and destination types
3707 Type *SrcTy = I.getOperand(0)->getType();
3708 Type *DestTy = I.getType();
3709
3710 // Get the size of the types in bits, we'll need this later
3711 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3712 unsigned DestBitSize = DestTy->getScalarSizeInBits();
3713
3714 Check(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
3715 Check(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
3716 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
3717 "fpext source and destination must both be a vector or neither", &I);
3718 Check(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
3719
3720 visitInstruction(I);
3721}
3722
3723void Verifier::visitUIToFPInst(UIToFPInst &I) {
3724 // Get the source and destination types
3725 Type *SrcTy = I.getOperand(0)->getType();
3726 Type *DestTy = I.getType();
3727
3728 bool SrcVec = SrcTy->isVectorTy();
3729 bool DstVec = DestTy->isVectorTy();
3730
3731 Check(SrcVec == DstVec,
3732 "UIToFP source and dest must both be vector or scalar", &I);
3733 Check(SrcTy->isIntOrIntVectorTy(),
3734 "UIToFP source must be integer or integer vector", &I);
3735 Check(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
3736 &I);
3737
3738 if (SrcVec && DstVec)
3739 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3740 cast<VectorType>(DestTy)->getElementCount(),
3741 "UIToFP source and dest vector length mismatch", &I);
3742
3743 visitInstruction(I);
3744}
3745
3746void Verifier::visitSIToFPInst(SIToFPInst &I) {
3747 // Get the source and destination types
3748 Type *SrcTy = I.getOperand(0)->getType();
3749 Type *DestTy = I.getType();
3750
3751 bool SrcVec = SrcTy->isVectorTy();
3752 bool DstVec = DestTy->isVectorTy();
3753
3754 Check(SrcVec == DstVec,
3755 "SIToFP source and dest must both be vector or scalar", &I);
3756 Check(SrcTy->isIntOrIntVectorTy(),
3757 "SIToFP source must be integer or integer vector", &I);
3758 Check(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
3759 &I);
3760
3761 if (SrcVec && DstVec)
3762 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3763 cast<VectorType>(DestTy)->getElementCount(),
3764 "SIToFP source and dest vector length mismatch", &I);
3765
3766 visitInstruction(I);
3767}
3768
3769void Verifier::visitFPToUIInst(FPToUIInst &I) {
3770 // Get the source and destination types
3771 Type *SrcTy = I.getOperand(0)->getType();
3772 Type *DestTy = I.getType();
3773
3774 bool SrcVec = SrcTy->isVectorTy();
3775 bool DstVec = DestTy->isVectorTy();
3776
3777 Check(SrcVec == DstVec,
3778 "FPToUI source and dest must both be vector or scalar", &I);
3779 Check(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector", &I);
3780 Check(DestTy->isIntOrIntVectorTy(),
3781 "FPToUI result must be integer or integer vector", &I);
3782
3783 if (SrcVec && DstVec)
3784 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3785 cast<VectorType>(DestTy)->getElementCount(),
3786 "FPToUI source and dest vector length mismatch", &I);
3787
3788 visitInstruction(I);
3789}
3790
3791void Verifier::visitFPToSIInst(FPToSIInst &I) {
3792 // Get the source and destination types
3793 Type *SrcTy = I.getOperand(0)->getType();
3794 Type *DestTy = I.getType();
3795
3796 bool SrcVec = SrcTy->isVectorTy();
3797 bool DstVec = DestTy->isVectorTy();
3798
3799 Check(SrcVec == DstVec,
3800 "FPToSI source and dest must both be vector or scalar", &I);
3801 Check(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector", &I);
3802 Check(DestTy->isIntOrIntVectorTy(),
3803 "FPToSI result must be integer or integer vector", &I);
3804
3805 if (SrcVec && DstVec)
3806 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3807 cast<VectorType>(DestTy)->getElementCount(),
3808 "FPToSI source and dest vector length mismatch", &I);
3809
3810 visitInstruction(I);
3811}
3812
3813void Verifier::checkPtrToAddr(Type *SrcTy, Type *DestTy, const Value &V) {
3814 Check(SrcTy->isPtrOrPtrVectorTy(), "PtrToAddr source must be pointer", V);
3815 Check(DestTy->isIntOrIntVectorTy(), "PtrToAddr result must be integral", V);
3816 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToAddr type mismatch",
3817 V);
3818
3819 if (SrcTy->isVectorTy()) {
3820 auto *VSrc = cast<VectorType>(SrcTy);
3821 auto *VDest = cast<VectorType>(DestTy);
3822 Check(VSrc->getElementCount() == VDest->getElementCount(),
3823 "PtrToAddr vector length mismatch", V);
3824 }
3825
3826 Type *AddrTy = DL.getAddressType(SrcTy);
3827 Check(AddrTy == DestTy, "PtrToAddr result must be address width", V);
3828}
3829
3830void Verifier::visitPtrToAddrInst(PtrToAddrInst &I) {
3831 checkPtrToAddr(I.getOperand(0)->getType(), I.getType(), I);
3832 visitInstruction(I);
3833}
3834
3835void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
3836 // Get the source and destination types
3837 Type *SrcTy = I.getOperand(0)->getType();
3838 Type *DestTy = I.getType();
3839
3840 Check(SrcTy->isPtrOrPtrVectorTy(), "PtrToInt source must be pointer", &I);
3841
3842 Check(DestTy->isIntOrIntVectorTy(), "PtrToInt result must be integral", &I);
3843 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
3844 &I);
3845
3846 if (SrcTy->isVectorTy()) {
3847 auto *VSrc = cast<VectorType>(SrcTy);
3848 auto *VDest = cast<VectorType>(DestTy);
3849 Check(VSrc->getElementCount() == VDest->getElementCount(),
3850 "PtrToInt Vector length mismatch", &I);
3851 }
3852
3853 visitInstruction(I);
3854}
3855
3856void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
3857 // Get the source and destination types
3858 Type *SrcTy = I.getOperand(0)->getType();
3859 Type *DestTy = I.getType();
3860
3861 Check(SrcTy->isIntOrIntVectorTy(), "IntToPtr source must be an integral", &I);
3862 Check(DestTy->isPtrOrPtrVectorTy(), "IntToPtr result must be a pointer", &I);
3863
3864 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
3865 &I);
3866 if (SrcTy->isVectorTy()) {
3867 auto *VSrc = cast<VectorType>(SrcTy);
3868 auto *VDest = cast<VectorType>(DestTy);
3869 Check(VSrc->getElementCount() == VDest->getElementCount(),
3870 "IntToPtr Vector length mismatch", &I);
3871 }
3872 visitInstruction(I);
3873}
3874
3875void Verifier::visitBitCastInst(BitCastInst &I) {
3876 Check(
3877 CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
3878 "Invalid bitcast", &I);
3879 visitInstruction(I);
3880}
3881
3882void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
3883 Type *SrcTy = I.getOperand(0)->getType();
3884 Type *DestTy = I.getType();
3885
3886 Check(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
3887 &I);
3888 Check(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
3889 &I);
3891 "AddrSpaceCast must be between different address spaces", &I);
3892 if (auto *SrcVTy = dyn_cast<VectorType>(SrcTy))
3893 Check(SrcVTy->getElementCount() ==
3894 cast<VectorType>(DestTy)->getElementCount(),
3895 "AddrSpaceCast vector pointer number of elements mismatch", &I);
3896 visitInstruction(I);
3897}
3898
3899/// visitPHINode - Ensure that a PHI node is well formed.
3900///
3901void Verifier::visitPHINode(PHINode &PN) {
3902 // Ensure that the PHI nodes are all grouped together at the top of the block.
3903 // This can be tested by checking whether the instruction before this is
3904 // either nonexistent (because this is begin()) or is a PHI node. If not,
3905 // then there is some other instruction before a PHI.
3906 Check(&PN == &PN.getParent()->front() ||
3908 "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
3909
3910 // Check that a PHI doesn't yield a Token.
3911 Check(!PN.getType()->isTokenLikeTy(), "PHI nodes cannot have token type!");
3912
3913 // Check that all of the values of the PHI node have the same type as the
3914 // result.
3915 for (Value *IncValue : PN.incoming_values()) {
3916 Check(PN.getType() == IncValue->getType(),
3917 "PHI node operands are not the same type as the result!", &PN);
3918 }
3919
3920 // All other PHI node constraints are checked in the visitBasicBlock method.
3921
3922 visitInstruction(PN);
3923}
3924
3925void Verifier::visitCallBase(CallBase &Call) {
3927 "Called function must be a pointer!", Call);
3928 FunctionType *FTy = Call.getFunctionType();
3929
3930 // Verify that the correct number of arguments are being passed
3931 if (FTy->isVarArg())
3932 Check(Call.arg_size() >= FTy->getNumParams(),
3933 "Called function requires more parameters than were provided!", Call);
3934 else
3935 Check(Call.arg_size() == FTy->getNumParams(),
3936 "Incorrect number of arguments passed to called function!", Call);
3937
3938 // Verify that all arguments to the call match the function type.
3939 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3940 Check(Call.getArgOperand(i)->getType() == FTy->getParamType(i),
3941 "Call parameter type does not match function signature!",
3942 Call.getArgOperand(i), FTy->getParamType(i), Call);
3943
3944 AttributeList Attrs = Call.getAttributes();
3945
3946 Check(verifyAttributeCount(Attrs, Call.arg_size()),
3947 "Attribute after last parameter!", Call);
3948
3949 Function *Callee =
3951 bool IsIntrinsic = Callee && Callee->isIntrinsic();
3952 if (IsIntrinsic)
3953 Check(Callee->getFunctionType() == FTy,
3954 "Intrinsic called with incompatible signature", Call);
3955
3956 // Verify if the calling convention of the callee is callable.
3958 "calling convention does not permit calls", Call);
3959
3960 // Disallow passing/returning values with alignment higher than we can
3961 // represent.
3962 // FIXME: Consider making DataLayout cap the alignment, so this isn't
3963 // necessary.
3964 auto VerifyTypeAlign = [&](Type *Ty, const Twine &Message) {
3965 if (!Ty->isSized())
3966 return;
3967 Align ABIAlign = DL.getABITypeAlign(Ty);
3968 Check(ABIAlign.value() <= Value::MaximumAlignment,
3969 "Incorrect alignment of " + Message + " to called function!", Call);
3970 };
3971
3972 if (!IsIntrinsic) {
3973 VerifyTypeAlign(FTy->getReturnType(), "return type");
3974 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3975 Type *Ty = FTy->getParamType(i);
3976 VerifyTypeAlign(Ty, "argument passed");
3977 }
3978 }
3979
3980 if (Attrs.hasFnAttr(Attribute::Speculatable)) {
3981 // Don't allow speculatable on call sites, unless the underlying function
3982 // declaration is also speculatable.
3983 Check(Callee && Callee->isSpeculatable(),
3984 "speculatable attribute may not apply to call sites", Call);
3985 }
3986
3987 if (Attrs.hasFnAttr(Attribute::Preallocated)) {
3988 Check(Call.getIntrinsicID() == Intrinsic::call_preallocated_arg,
3989 "preallocated as a call site attribute can only be on "
3990 "llvm.call.preallocated.arg");
3991 }
3992
3993 Check(!Attrs.hasFnAttr(Attribute::DenormalFPEnv),
3994 "denormal_fpenv attribute may not apply to call sites", Call);
3995
3996 // Verify call attributes.
3997 verifyFunctionAttrs(FTy, Attrs, &Call, IsIntrinsic, Call.isInlineAsm());
3998
3999 // Conservatively check the inalloca argument.
4000 // We have a bug if we can find that there is an underlying alloca without
4001 // inalloca.
4002 if (Call.hasInAllocaArgument()) {
4003 Value *InAllocaArg = Call.getArgOperand(FTy->getNumParams() - 1);
4004 if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
4005 Check(AI->isUsedWithInAlloca(),
4006 "inalloca argument for call has mismatched alloca", AI, Call);
4007 }
4008
4009 // For each argument of the callsite, if it has the swifterror argument,
4010 // make sure the underlying alloca/parameter it comes from has a swifterror as
4011 // well.
4012 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
4013 if (Call.paramHasAttr(i, Attribute::SwiftError)) {
4014 Value *SwiftErrorArg = Call.getArgOperand(i);
4015 if (auto AI = dyn_cast<AllocaInst>(SwiftErrorArg->stripInBoundsOffsets())) {
4016 Check(AI->isSwiftError(),
4017 "swifterror argument for call has mismatched alloca", AI, Call);
4018 continue;
4019 }
4020 auto ArgI = dyn_cast<Argument>(SwiftErrorArg);
4021 Check(ArgI, "swifterror argument should come from an alloca or parameter",
4022 SwiftErrorArg, Call);
4023 Check(ArgI->hasSwiftErrorAttr(),
4024 "swifterror argument for call has mismatched parameter", ArgI,
4025 Call);
4026 }
4027
4028 if (Attrs.hasParamAttr(i, Attribute::ImmArg)) {
4029 // Don't allow immarg on call sites, unless the underlying declaration
4030 // also has the matching immarg.
4031 Check(Callee && Callee->hasParamAttribute(i, Attribute::ImmArg),
4032 "immarg may not apply only to call sites", Call.getArgOperand(i),
4033 Call);
4034 }
4035
4036 if (Call.paramHasAttr(i, Attribute::ImmArg)) {
4037 Value *ArgVal = Call.getArgOperand(i);
4038 Check((isa<ConstantInt>(ArgVal) || isa<ConstantFP>(ArgVal)) &&
4039 !isa<VectorType>(ArgVal->getType()),
4040 "immarg operand has non-immediate parameter", ArgVal, Call);
4041
4042 // If the imm-arg is an integer and also has a range attached,
4043 // check if the given value is within the range.
4044 if (Call.paramHasAttr(i, Attribute::Range)) {
4045 if (auto *CI = dyn_cast<ConstantInt>(ArgVal)) {
4046 const ConstantRange &CR =
4047 Call.getParamAttr(i, Attribute::Range).getValueAsConstantRange();
4048 Check(CR.contains(CI->getValue()),
4049 "immarg value " + Twine(CI->getValue().getSExtValue()) +
4050 " out of range [" + Twine(CR.getLower().getSExtValue()) +
4051 ", " + Twine(CR.getUpper().getSExtValue()) + ")",
4052 Call);
4053 }
4054 }
4055 }
4056
4057 if (Call.paramHasAttr(i, Attribute::Preallocated)) {
4058 Value *ArgVal = Call.getArgOperand(i);
4059 bool hasOB =
4061 bool isMustTail = Call.isMustTailCall();
4062 Check(hasOB != isMustTail,
4063 "preallocated operand either requires a preallocated bundle or "
4064 "the call to be musttail (but not both)",
4065 ArgVal, Call);
4066 }
4067 }
4068
4069 if (FTy->isVarArg()) {
4070 // FIXME? is 'nest' even legal here?
4071 bool SawNest = false;
4072 bool SawReturned = false;
4073
4074 for (unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) {
4075 if (Attrs.hasParamAttr(Idx, Attribute::Nest))
4076 SawNest = true;
4077 if (Attrs.hasParamAttr(Idx, Attribute::Returned))
4078 SawReturned = true;
4079 }
4080
4081 // Check attributes on the varargs part.
4082 for (unsigned Idx = FTy->getNumParams(); Idx < Call.arg_size(); ++Idx) {
4083 Type *Ty = Call.getArgOperand(Idx)->getType();
4084 AttributeSet ArgAttrs = Attrs.getParamAttrs(Idx);
4085 verifyParameterAttrs(ArgAttrs, Ty, &Call);
4086
4087 if (ArgAttrs.hasAttribute(Attribute::Nest)) {
4088 Check(!SawNest, "More than one parameter has attribute nest!", Call);
4089 SawNest = true;
4090 }
4091
4092 if (ArgAttrs.hasAttribute(Attribute::Returned)) {
4093 Check(!SawReturned, "More than one parameter has attribute returned!",
4094 Call);
4095 Check(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
4096 "Incompatible argument and return types for 'returned' "
4097 "attribute",
4098 Call);
4099 SawReturned = true;
4100 }
4101
4102 // Statepoint intrinsic is vararg but the wrapped function may be not.
4103 // Allow sret here and check the wrapped function in verifyStatepoint.
4104 if (Call.getIntrinsicID() != Intrinsic::experimental_gc_statepoint)
4105 Check(!ArgAttrs.hasAttribute(Attribute::StructRet),
4106 "Attribute 'sret' cannot be used for vararg call arguments!",
4107 Call);
4108
4109 if (ArgAttrs.hasAttribute(Attribute::InAlloca))
4110 Check(Idx == Call.arg_size() - 1,
4111 "inalloca isn't on the last argument!", Call);
4112 }
4113 }
4114
4115 // Verify that there's no metadata unless it's a direct call to an intrinsic.
4116 if (!IsIntrinsic) {
4117 for (Type *ParamTy : FTy->params()) {
4118 Check(!ParamTy->isMetadataTy(),
4119 "Function has metadata parameter but isn't an intrinsic", Call);
4120 Check(!ParamTy->isTokenLikeTy(),
4121 "Function has token parameter but isn't an intrinsic", Call);
4122 }
4123 }
4124
4125 // Verify that indirect calls don't return tokens.
4126 if (!Call.getCalledFunction()) {
4127 Check(!FTy->getReturnType()->isTokenLikeTy(),
4128 "Return type cannot be token for indirect call!");
4129 Check(!FTy->getReturnType()->isX86_AMXTy(),
4130 "Return type cannot be x86_amx for indirect call!");
4131 }
4132
4134 visitIntrinsicCall(ID, Call);
4135
4136 // Verify that a callsite has at most one "deopt", at most one "funclet", at
4137 // most one "gc-transition", at most one "cfguardtarget", at most one
4138 // "preallocated" operand bundle, and at most one "ptrauth" operand bundle.
4139 bool FoundDeoptBundle = false, FoundFuncletBundle = false,
4140 FoundGCTransitionBundle = false, FoundCFGuardTargetBundle = false,
4141 FoundPreallocatedBundle = false, FoundGCLiveBundle = false,
4142 FoundPtrauthBundle = false, FoundKCFIBundle = false,
4143 FoundAttachedCallBundle = false;
4144 for (unsigned i = 0, e = Call.getNumOperandBundles(); i < e; ++i) {
4145 OperandBundleUse BU = Call.getOperandBundleAt(i);
4146 uint32_t Tag = BU.getTagID();
4147 if (Tag == LLVMContext::OB_deopt) {
4148 Check(!FoundDeoptBundle, "Multiple deopt operand bundles", Call);
4149 FoundDeoptBundle = true;
4150 } else if (Tag == LLVMContext::OB_gc_transition) {
4151 Check(!FoundGCTransitionBundle, "Multiple gc-transition operand bundles",
4152 Call);
4153 FoundGCTransitionBundle = true;
4154 } else if (Tag == LLVMContext::OB_funclet) {
4155 Check(!FoundFuncletBundle, "Multiple funclet operand bundles", Call);
4156 FoundFuncletBundle = true;
4157 Check(BU.Inputs.size() == 1,
4158 "Expected exactly one funclet bundle operand", Call);
4159 Check(isa<FuncletPadInst>(BU.Inputs.front()),
4160 "Funclet bundle operands should correspond to a FuncletPadInst",
4161 Call);
4162 } else if (Tag == LLVMContext::OB_cfguardtarget) {
4163 Check(!FoundCFGuardTargetBundle, "Multiple CFGuardTarget operand bundles",
4164 Call);
4165 FoundCFGuardTargetBundle = true;
4166 Check(BU.Inputs.size() == 1,
4167 "Expected exactly one cfguardtarget bundle operand", Call);
4168 } else if (Tag == LLVMContext::OB_ptrauth) {
4169 Check(!FoundPtrauthBundle, "Multiple ptrauth operand bundles", Call);
4170 FoundPtrauthBundle = true;
4171 Check(BU.Inputs.size() == 2,
4172 "Expected exactly two ptrauth bundle operands", Call);
4173 Check(isa<ConstantInt>(BU.Inputs[0]) &&
4174 BU.Inputs[0]->getType()->isIntegerTy(32),
4175 "Ptrauth bundle key operand must be an i32 constant", Call);
4176 Check(BU.Inputs[1]->getType()->isIntegerTy(64),
4177 "Ptrauth bundle discriminator operand must be an i64", Call);
4178 } else if (Tag == LLVMContext::OB_kcfi) {
4179 Check(!FoundKCFIBundle, "Multiple kcfi operand bundles", Call);
4180 FoundKCFIBundle = true;
4181 Check(BU.Inputs.size() == 1, "Expected exactly one kcfi bundle operand",
4182 Call);
4183 Check(isa<ConstantInt>(BU.Inputs[0]) &&
4184 BU.Inputs[0]->getType()->isIntegerTy(32),
4185 "Kcfi bundle operand must be an i32 constant", Call);
4186 } else if (Tag == LLVMContext::OB_preallocated) {
4187 Check(!FoundPreallocatedBundle, "Multiple preallocated operand bundles",
4188 Call);
4189 FoundPreallocatedBundle = true;
4190 Check(BU.Inputs.size() == 1,
4191 "Expected exactly one preallocated bundle operand", Call);
4192 auto Input = dyn_cast<IntrinsicInst>(BU.Inputs.front());
4193 Check(Input &&
4194 Input->getIntrinsicID() == Intrinsic::call_preallocated_setup,
4195 "\"preallocated\" argument must be a token from "
4196 "llvm.call.preallocated.setup",
4197 Call);
4198 } else if (Tag == LLVMContext::OB_gc_live) {
4199 Check(!FoundGCLiveBundle, "Multiple gc-live operand bundles", Call);
4200 FoundGCLiveBundle = true;
4202 Check(!FoundAttachedCallBundle,
4203 "Multiple \"clang.arc.attachedcall\" operand bundles", Call);
4204 FoundAttachedCallBundle = true;
4205 verifyAttachedCallBundle(Call, BU);
4206 }
4207 }
4208
4209 // Verify that callee and callsite agree on whether to use pointer auth.
4210 Check(!(Call.getCalledFunction() && FoundPtrauthBundle),
4211 "Direct call cannot have a ptrauth bundle", Call);
4212
4213 // Verify that each inlinable callsite of a debug-info-bearing function in a
4214 // debug-info-bearing function has a debug location attached to it. Failure to
4215 // do so causes assertion failures when the inliner sets up inline scope info
4216 // (Interposable functions are not inlinable, neither are functions without
4217 // definitions.)
4223 "inlinable function call in a function with "
4224 "debug info must have a !dbg location",
4225 Call);
4226
4227 if (Call.isInlineAsm())
4228 verifyInlineAsmCall(Call);
4229
4230 ConvergenceVerifyHelper.visit(Call);
4231
4232 visitInstruction(Call);
4233}
4234
4235void Verifier::verifyTailCCMustTailAttrs(const AttrBuilder &Attrs,
4236 StringRef Context) {
4237 Check(!Attrs.contains(Attribute::InAlloca),
4238 Twine("inalloca attribute not allowed in ") + Context);
4239 Check(!Attrs.contains(Attribute::InReg),
4240 Twine("inreg attribute not allowed in ") + Context);
4241 Check(!Attrs.contains(Attribute::SwiftError),
4242 Twine("swifterror attribute not allowed in ") + Context);
4243 Check(!Attrs.contains(Attribute::Preallocated),
4244 Twine("preallocated attribute not allowed in ") + Context);
4245 Check(!Attrs.contains(Attribute::ByRef),
4246 Twine("byref attribute not allowed in ") + Context);
4247}
4248
4249/// Two types are "congruent" if they are identical, or if they are both pointer
4250/// types with different pointee types and the same address space.
4251static bool isTypeCongruent(Type *L, Type *R) {
4252 if (L == R)
4253 return true;
4256 if (!PL || !PR)
4257 return false;
4258 return PL->getAddressSpace() == PR->getAddressSpace();
4259}
4260
4261static AttrBuilder getParameterABIAttributes(LLVMContext& C, unsigned I, AttributeList Attrs) {
4262 static const Attribute::AttrKind ABIAttrs[] = {
4263 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
4264 Attribute::InReg, Attribute::StackAlignment, Attribute::SwiftSelf,
4265 Attribute::SwiftAsync, Attribute::SwiftError, Attribute::Preallocated,
4266 Attribute::ByRef};
4267 AttrBuilder Copy(C);
4268 for (auto AK : ABIAttrs) {
4269 Attribute Attr = Attrs.getParamAttrs(I).getAttribute(AK);
4270 if (Attr.isValid())
4271 Copy.addAttribute(Attr);
4272 }
4273
4274 // `align` is ABI-affecting only in combination with `byval` or `byref`.
4275 if (Attrs.hasParamAttr(I, Attribute::Alignment) &&
4276 (Attrs.hasParamAttr(I, Attribute::ByVal) ||
4277 Attrs.hasParamAttr(I, Attribute::ByRef)))
4278 Copy.addAlignmentAttr(Attrs.getParamAlignment(I));
4279 return Copy;
4280}
4281
4282void Verifier::verifyMustTailCall(CallInst &CI) {
4283 Check(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
4284
4285 Function *F = CI.getParent()->getParent();
4286 FunctionType *CallerTy = F->getFunctionType();
4287 FunctionType *CalleeTy = CI.getFunctionType();
4288 Check(CallerTy->isVarArg() == CalleeTy->isVarArg(),
4289 "cannot guarantee tail call due to mismatched varargs", &CI);
4290 Check(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
4291 "cannot guarantee tail call due to mismatched return types", &CI);
4292
4293 // - The calling conventions of the caller and callee must match.
4294 Check(F->getCallingConv() == CI.getCallingConv(),
4295 "cannot guarantee tail call due to mismatched calling conv", &CI);
4296
4297 // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
4298 // or a pointer bitcast followed by a ret instruction.
4299 // - The ret instruction must return the (possibly bitcasted) value
4300 // produced by the call or void.
4301 Value *RetVal = &CI;
4303
4304 // Handle the optional bitcast.
4305 if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
4306 Check(BI->getOperand(0) == RetVal,
4307 "bitcast following musttail call must use the call", BI);
4308 RetVal = BI;
4309 Next = BI->getNextNode();
4310 }
4311
4312 // Check the return.
4313 ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
4314 Check(Ret, "musttail call must precede a ret with an optional bitcast", &CI);
4315 Check(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal ||
4317 "musttail call result must be returned", Ret);
4318
4319 AttributeList CallerAttrs = F->getAttributes();
4320 AttributeList CalleeAttrs = CI.getAttributes();
4321 if (CI.getCallingConv() == CallingConv::SwiftTail ||
4322 CI.getCallingConv() == CallingConv::Tail) {
4323 StringRef CCName =
4324 CI.getCallingConv() == CallingConv::Tail ? "tailcc" : "swifttailcc";
4325
4326 // - Only sret, byval, swiftself, and swiftasync ABI-impacting attributes
4327 // are allowed in swifttailcc call
4328 for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
4329 AttrBuilder ABIAttrs = getParameterABIAttributes(F->getContext(), I, CallerAttrs);
4330 SmallString<32> Context{CCName, StringRef(" musttail caller")};
4331 verifyTailCCMustTailAttrs(ABIAttrs, Context);
4332 }
4333 for (unsigned I = 0, E = CalleeTy->getNumParams(); I != E; ++I) {
4334 AttrBuilder ABIAttrs = getParameterABIAttributes(F->getContext(), I, CalleeAttrs);
4335 SmallString<32> Context{CCName, StringRef(" musttail callee")};
4336 verifyTailCCMustTailAttrs(ABIAttrs, Context);
4337 }
4338 // - Varargs functions are not allowed
4339 Check(!CallerTy->isVarArg(), Twine("cannot guarantee ") + CCName +
4340 " tail call for varargs function");
4341 return;
4342 }
4343
4344 // - The caller and callee prototypes must match. Pointer types of
4345 // parameters or return types may differ in pointee type, but not
4346 // address space.
4347 if (!CI.getIntrinsicID()) {
4348 Check(CallerTy->getNumParams() == CalleeTy->getNumParams(),
4349 "cannot guarantee tail call due to mismatched parameter counts", &CI);
4350 for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
4351 Check(
4352 isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
4353 "cannot guarantee tail call due to mismatched parameter types", &CI);
4354 }
4355 }
4356
4357 // - All ABI-impacting function attributes, such as sret, byval, inreg,
4358 // returned, preallocated, and inalloca, must match.
4359 for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
4360 AttrBuilder CallerABIAttrs = getParameterABIAttributes(F->getContext(), I, CallerAttrs);
4361 AttrBuilder CalleeABIAttrs = getParameterABIAttributes(F->getContext(), I, CalleeAttrs);
4362 Check(CallerABIAttrs == CalleeABIAttrs,
4363 "cannot guarantee tail call due to mismatched ABI impacting "
4364 "function attributes",
4365 &CI, CI.getOperand(I));
4366 }
4367}
4368
4369void Verifier::visitCallInst(CallInst &CI) {
4370 visitCallBase(CI);
4371
4372 if (CI.isMustTailCall())
4373 verifyMustTailCall(CI);
4374}
4375
4376void Verifier::visitInvokeInst(InvokeInst &II) {
4377 visitCallBase(II);
4378
4379 // Verify that the first non-PHI instruction of the unwind destination is an
4380 // exception handling instruction.
4381 Check(
4382 II.getUnwindDest()->isEHPad(),
4383 "The unwind destination does not have an exception handling instruction!",
4384 &II);
4385
4386 visitTerminator(II);
4387}
4388
4389/// visitUnaryOperator - Check the argument to the unary operator.
4390///
4391void Verifier::visitUnaryOperator(UnaryOperator &U) {
4392 Check(U.getType() == U.getOperand(0)->getType(),
4393 "Unary operators must have same type for"
4394 "operands and result!",
4395 &U);
4396
4397 switch (U.getOpcode()) {
4398 // Check that floating-point arithmetic operators are only used with
4399 // floating-point operands.
4400 case Instruction::FNeg:
4401 Check(U.getType()->isFPOrFPVectorTy(),
4402 "FNeg operator only works with float types!", &U);
4403 break;
4404 default:
4405 llvm_unreachable("Unknown UnaryOperator opcode!");
4406 }
4407
4408 visitInstruction(U);
4409}
4410
4411/// visitBinaryOperator - Check that both arguments to the binary operator are
4412/// of the same type!
4413///
4414void Verifier::visitBinaryOperator(BinaryOperator &B) {
4415 Check(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
4416 "Both operands to a binary operator are not of the same type!", &B);
4417
4418 switch (B.getOpcode()) {
4419 // Check that integer arithmetic operators are only used with
4420 // integral operands.
4421 case Instruction::Add:
4422 case Instruction::Sub:
4423 case Instruction::Mul:
4424 case Instruction::SDiv:
4425 case Instruction::UDiv:
4426 case Instruction::SRem:
4427 case Instruction::URem:
4428 Check(B.getType()->isIntOrIntVectorTy(),
4429 "Integer arithmetic operators only work with integral types!", &B);
4430 Check(B.getType() == B.getOperand(0)->getType(),
4431 "Integer arithmetic operators must have same type "
4432 "for operands and result!",
4433 &B);
4434 break;
4435 // Check that floating-point arithmetic operators are only used with
4436 // floating-point operands.
4437 case Instruction::FAdd:
4438 case Instruction::FSub:
4439 case Instruction::FMul:
4440 case Instruction::FDiv:
4441 case Instruction::FRem:
4442 Check(B.getType()->isFPOrFPVectorTy(),
4443 "Floating-point arithmetic operators only work with "
4444 "floating-point types!",
4445 &B);
4446 Check(B.getType() == B.getOperand(0)->getType(),
4447 "Floating-point arithmetic operators must have same type "
4448 "for operands and result!",
4449 &B);
4450 break;
4451 // Check that logical operators are only used with integral operands.
4452 case Instruction::And:
4453 case Instruction::Or:
4454 case Instruction::Xor:
4455 Check(B.getType()->isIntOrIntVectorTy(),
4456 "Logical operators only work with integral types!", &B);
4457 Check(B.getType() == B.getOperand(0)->getType(),
4458 "Logical operators must have same type for operands and result!", &B);
4459 break;
4460 case Instruction::Shl:
4461 case Instruction::LShr:
4462 case Instruction::AShr:
4463 Check(B.getType()->isIntOrIntVectorTy(),
4464 "Shifts only work with integral types!", &B);
4465 Check(B.getType() == B.getOperand(0)->getType(),
4466 "Shift return type must be same as operands!", &B);
4467 break;
4468 default:
4469 llvm_unreachable("Unknown BinaryOperator opcode!");
4470 }
4471
4472 visitInstruction(B);
4473}
4474
4475void Verifier::visitICmpInst(ICmpInst &IC) {
4476 // Check that the operands are the same type
4477 Type *Op0Ty = IC.getOperand(0)->getType();
4478 Type *Op1Ty = IC.getOperand(1)->getType();
4479 Check(Op0Ty == Op1Ty,
4480 "Both operands to ICmp instruction are not of the same type!", &IC);
4481 // Check that the operands are the right type
4482 Check(Op0Ty->isIntOrIntVectorTy() || Op0Ty->isPtrOrPtrVectorTy(),
4483 "Invalid operand types for ICmp instruction", &IC);
4484 // Check that the predicate is valid.
4485 Check(IC.isIntPredicate(), "Invalid predicate in ICmp instruction!", &IC);
4486
4487 visitInstruction(IC);
4488}
4489
4490void Verifier::visitFCmpInst(FCmpInst &FC) {
4491 // Check that the operands are the same type
4492 Type *Op0Ty = FC.getOperand(0)->getType();
4493 Type *Op1Ty = FC.getOperand(1)->getType();
4494 Check(Op0Ty == Op1Ty,
4495 "Both operands to FCmp instruction are not of the same type!", &FC);
4496 // Check that the operands are the right type
4497 Check(Op0Ty->isFPOrFPVectorTy(), "Invalid operand types for FCmp instruction",
4498 &FC);
4499 // Check that the predicate is valid.
4500 Check(FC.isFPPredicate(), "Invalid predicate in FCmp instruction!", &FC);
4501
4502 visitInstruction(FC);
4503}
4504
4505void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
4507 "Invalid extractelement operands!", &EI);
4508 visitInstruction(EI);
4509}
4510
4511void Verifier::visitInsertElementInst(InsertElementInst &IE) {
4512 Check(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
4513 IE.getOperand(2)),
4514 "Invalid insertelement operands!", &IE);
4515 visitInstruction(IE);
4516}
4517
4518void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
4520 SV.getShuffleMask()),
4521 "Invalid shufflevector operands!", &SV);
4522 visitInstruction(SV);
4523}
4524
4525void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
4527 GEP.getModule()->getModuleFlag("require-logical-pointer")))
4528 Check(!MD->getZExtValue(),
4529 "Non-logical getelementptr disallowed for this module.");
4530
4531 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
4532
4533 Check(isa<PointerType>(TargetTy),
4534 "GEP base pointer is not a vector or a vector of pointers", &GEP);
4535 Check(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP);
4536
4537 if (auto *STy = dyn_cast<StructType>(GEP.getSourceElementType())) {
4538 Check(!STy->isScalableTy(),
4539 "getelementptr cannot target structure that contains scalable vector"
4540 "type",
4541 &GEP);
4542 }
4543
4544 SmallVector<Value *, 16> Idxs(GEP.indices());
4545 Check(
4546 all_of(Idxs, [](Value *V) { return V->getType()->isIntOrIntVectorTy(); }),
4547 "GEP indexes must be integers", &GEP);
4548 Type *ElTy =
4549 GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs);
4550 Check(ElTy, "Invalid indices for GEP pointer type!", &GEP);
4551
4552 PointerType *PtrTy = dyn_cast<PointerType>(GEP.getType()->getScalarType());
4553
4554 Check(PtrTy && GEP.getResultElementType() == ElTy,
4555 "GEP is not of right type for indices!", &GEP, ElTy);
4556
4557 if (auto *GEPVTy = dyn_cast<VectorType>(GEP.getType())) {
4558 // Additional checks for vector GEPs.
4559 ElementCount GEPWidth = GEPVTy->getElementCount();
4560 if (GEP.getPointerOperandType()->isVectorTy())
4561 Check(
4562 GEPWidth ==
4563 cast<VectorType>(GEP.getPointerOperandType())->getElementCount(),
4564 "Vector GEP result width doesn't match operand's", &GEP);
4565 for (Value *Idx : Idxs) {
4566 Type *IndexTy = Idx->getType();
4567 if (auto *IndexVTy = dyn_cast<VectorType>(IndexTy)) {
4568 ElementCount IndexWidth = IndexVTy->getElementCount();
4569 Check(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP);
4570 }
4571 Check(IndexTy->isIntOrIntVectorTy(),
4572 "All GEP indices should be of integer type");
4573 }
4574 }
4575
4576 // Check that GEP does not index into a vector with non-byte-addressable
4577 // elements.
4579 GTI != GTE; ++GTI) {
4580 if (GTI.isVector()) {
4581 Type *ElemTy = GTI.getIndexedType();
4582 Check(DL.typeSizeEqualsStoreSize(ElemTy),
4583 "GEP into vector with non-byte-addressable element type", &GEP);
4584 }
4585 }
4586
4587 Check(GEP.getAddressSpace() == PtrTy->getAddressSpace(),
4588 "GEP address space doesn't match type", &GEP);
4589
4590 visitInstruction(GEP);
4591}
4592
4593static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
4594 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
4595}
4596
4597/// Verify !range and !absolute_symbol metadata. These have the same
4598/// restrictions, except !absolute_symbol allows the full set.
4599void Verifier::verifyRangeLikeMetadata(const Value &I, const MDNode *Range,
4600 Type *Ty, RangeLikeMetadataKind Kind) {
4601 unsigned NumOperands = Range->getNumOperands();
4602 Check(NumOperands % 2 == 0, "Unfinished range!", Range);
4603 unsigned NumRanges = NumOperands / 2;
4604 Check(NumRanges >= 1, "It should have at least one range!", Range);
4605
4606 ConstantRange LastRange(1, true); // Dummy initial value
4607 for (unsigned i = 0; i < NumRanges; ++i) {
4608 ConstantInt *Low =
4609 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
4610 Check(Low, "The lower limit must be an integer!", Low);
4611 ConstantInt *High =
4612 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
4613 Check(High, "The upper limit must be an integer!", High);
4614
4615 Check(High->getType() == Low->getType(), "Range pair types must match!",
4616 &I);
4617
4618 if (Kind == RangeLikeMetadataKind::NoaliasAddrspace) {
4619 Check(High->getType()->isIntegerTy(32),
4620 "noalias.addrspace type must be i32!", &I);
4621 } else {
4622 Check(High->getType() == Ty->getScalarType(),
4623 "Range types must match instruction type!", &I);
4624 }
4625
4626 APInt HighV = High->getValue();
4627 APInt LowV = Low->getValue();
4628
4629 // ConstantRange asserts if the ranges are the same except for the min/max
4630 // value. Leave the cases it tolerates for the empty range error below.
4631 Check(LowV != HighV || LowV.isMaxValue() || LowV.isMinValue(),
4632 "The upper and lower limits cannot be the same value", &I);
4633
4634 ConstantRange CurRange(LowV, HighV);
4635 Check(!CurRange.isEmptySet() &&
4636 (Kind == RangeLikeMetadataKind::AbsoluteSymbol ||
4637 !CurRange.isFullSet()),
4638 "Range must not be empty!", Range);
4639 if (i != 0) {
4640 Check(CurRange.intersectWith(LastRange).isEmptySet(),
4641 "Intervals are overlapping", Range);
4642 Check(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
4643 Range);
4644 Check(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
4645 Range);
4646 }
4647 LastRange = ConstantRange(LowV, HighV);
4648 }
4649 if (NumRanges > 2) {
4650 APInt FirstLow =
4651 mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
4652 APInt FirstHigh =
4653 mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
4654 ConstantRange FirstRange(FirstLow, FirstHigh);
4655 Check(FirstRange.intersectWith(LastRange).isEmptySet(),
4656 "Intervals are overlapping", Range);
4657 Check(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
4658 Range);
4659 }
4660}
4661
4662void Verifier::visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty) {
4663 assert(Range && Range == I.getMetadata(LLVMContext::MD_range) &&
4664 "precondition violation");
4665 verifyRangeLikeMetadata(I, Range, Ty, RangeLikeMetadataKind::Range);
4666}
4667
4668void Verifier::visitNoFPClassMetadata(Instruction &I, MDNode *NoFPClass,
4669 Type *Ty) {
4670 Check(AttributeFuncs::isNoFPClassCompatibleType(Ty),
4671 "nofpclass only applies to floating-point typed loads", I);
4672
4673 Check(NoFPClass->getNumOperands() == 1,
4674 "nofpclass must have exactly one entry", NoFPClass);
4675 ConstantInt *MaskVal =
4677 Check(MaskVal && MaskVal->getType()->isIntegerTy(32),
4678 "nofpclass entry must be a constant i32", NoFPClass);
4679 uint32_t Val = MaskVal->getZExtValue();
4680 Check(Val != 0, "'nofpclass' must have at least one test bit set", NoFPClass,
4681 I);
4682
4683 Check((Val & ~static_cast<unsigned>(fcAllFlags)) == 0,
4684 "Invalid value for 'nofpclass' test mask", NoFPClass, I);
4685}
4686
4687void Verifier::visitNoaliasAddrspaceMetadata(Instruction &I, MDNode *Range,
4688 Type *Ty) {
4689 assert(Range && Range == I.getMetadata(LLVMContext::MD_noalias_addrspace) &&
4690 "precondition violation");
4691 verifyRangeLikeMetadata(I, Range, Ty,
4692 RangeLikeMetadataKind::NoaliasAddrspace);
4693}
4694
4695void Verifier::checkAtomicMemAccessSize(Type *Ty, const Instruction *I) {
4696 unsigned Size = DL.getTypeSizeInBits(Ty).getFixedValue();
4697 Check(Size >= 8, "atomic memory access' size must be byte-sized", Ty, I);
4698 Check(!(Size & (Size - 1)),
4699 "atomic memory access' operand must have a power-of-two size", Ty, I);
4700}
4701
4702void Verifier::visitLoadInst(LoadInst &LI) {
4704 Check(PTy, "Load operand must be a pointer.", &LI);
4705 Type *ElTy = LI.getType();
4706 if (MaybeAlign A = LI.getAlign()) {
4707 Check(A->value() <= Value::MaximumAlignment,
4708 "huge alignment values are unsupported", &LI);
4709 }
4710 Check(ElTy->isSized(), "loading unsized types is not allowed", &LI);
4711 if (LI.isAtomic()) {
4712 Check(LI.getOrdering() != AtomicOrdering::Release &&
4713 LI.getOrdering() != AtomicOrdering::AcquireRelease,
4714 "Load cannot have Release ordering", &LI);
4715 Check(ElTy->getScalarType()->isIntOrPtrTy() ||
4716 ElTy->getScalarType()->isByteTy() ||
4718 "atomic load operand must have integer, byte, pointer, floating "
4719 "point, or vector type!",
4720 ElTy, &LI);
4721
4722 checkAtomicMemAccessSize(ElTy, &LI);
4723 } else {
4725 "Non-atomic load cannot have SynchronizationScope specified", &LI);
4726 }
4727
4728 visitInstruction(LI);
4729}
4730
4731void Verifier::visitStoreInst(StoreInst &SI) {
4732 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
4733 Check(PTy, "Store operand must be a pointer.", &SI);
4734 Type *ElTy = SI.getOperand(0)->getType();
4735 if (MaybeAlign A = SI.getAlign()) {
4736 Check(A->value() <= Value::MaximumAlignment,
4737 "huge alignment values are unsupported", &SI);
4738 }
4739 Check(ElTy->isSized(), "storing unsized types is not allowed", &SI);
4740 if (SI.isAtomic()) {
4741 Check(SI.getOrdering() != AtomicOrdering::Acquire &&
4742 SI.getOrdering() != AtomicOrdering::AcquireRelease,
4743 "Store cannot have Acquire ordering", &SI);
4744 Check(ElTy->getScalarType()->isIntOrPtrTy() ||
4745 ElTy->getScalarType()->isByteTy() ||
4747 "atomic store operand must have integer, byte, pointer, floating "
4748 "point, or vector type!",
4749 ElTy, &SI);
4750 checkAtomicMemAccessSize(ElTy, &SI);
4751 } else {
4752 Check(SI.getSyncScopeID() == SyncScope::System,
4753 "Non-atomic store cannot have SynchronizationScope specified", &SI);
4754 }
4755 visitInstruction(SI);
4756}
4757
4758/// Check that SwiftErrorVal is used as a swifterror argument in CS.
4759void Verifier::verifySwiftErrorCall(CallBase &Call,
4760 const Value *SwiftErrorVal) {
4761 for (const auto &I : llvm::enumerate(Call.args())) {
4762 if (I.value() == SwiftErrorVal) {
4763 Check(Call.paramHasAttr(I.index(), Attribute::SwiftError),
4764 "swifterror value when used in a callsite should be marked "
4765 "with swifterror attribute",
4766 SwiftErrorVal, Call);
4767 }
4768 }
4769}
4770
4771void Verifier::verifySwiftErrorValue(const Value *SwiftErrorVal) {
4772 // Check that swifterror value is only used by loads, stores, or as
4773 // a swifterror argument.
4774 for (const User *U : SwiftErrorVal->users()) {
4776 isa<InvokeInst>(U),
4777 "swifterror value can only be loaded and stored from, or "
4778 "as a swifterror argument!",
4779 SwiftErrorVal, U);
4780 // If it is used by a store, check it is the second operand.
4781 if (auto StoreI = dyn_cast<StoreInst>(U))
4782 Check(StoreI->getOperand(1) == SwiftErrorVal,
4783 "swifterror value should be the second operand when used "
4784 "by stores",
4785 SwiftErrorVal, U);
4786 if (auto *Call = dyn_cast<CallBase>(U))
4787 verifySwiftErrorCall(*const_cast<CallBase *>(Call), SwiftErrorVal);
4788 }
4789}
4790
4791void Verifier::visitAllocaInst(AllocaInst &AI) {
4793 AI.getModule()->getModuleFlag("require-logical-pointer")))
4794 Check(!MD->getZExtValue(),
4795 "Non-logical alloca disallowed for this module.");
4796
4797 Type *Ty = AI.getAllocatedType();
4798 SmallPtrSet<Type*, 4> Visited;
4799 Check(Ty->isSized(&Visited), "Cannot allocate unsized type", &AI);
4800 // Check if it's a target extension type that disallows being used on the
4801 // stack.
4803 "Alloca has illegal target extension type", &AI);
4805 "Alloca array size must have integer type", &AI);
4806 if (MaybeAlign A = AI.getAlign()) {
4807 Check(A->value() <= Value::MaximumAlignment,
4808 "huge alignment values are unsupported", &AI);
4809 }
4810
4811 if (AI.isSwiftError()) {
4812 Check(Ty->isPointerTy(), "swifterror alloca must have pointer type", &AI);
4814 "swifterror alloca must not be array allocation", &AI);
4815 verifySwiftErrorValue(&AI);
4816 }
4817
4818 if (TT.isAMDGPU()) {
4820 "alloca on amdgpu must be in addrspace(5)", &AI);
4821 }
4822
4823 visitInstruction(AI);
4824}
4825
4826void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
4827 Type *ElTy = CXI.getOperand(1)->getType();
4828 Check(ElTy->isIntOrPtrTy(),
4829 "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
4830 checkAtomicMemAccessSize(ElTy, &CXI);
4831 visitInstruction(CXI);
4832}
4833
4834void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
4835 Check(RMWI.getOrdering() != AtomicOrdering::Unordered,
4836 "atomicrmw instructions cannot be unordered.", &RMWI);
4837 auto Op = RMWI.getOperation();
4838 Type *ElTy = RMWI.getOperand(1)->getType();
4839 Type *ScalarTy = ElTy;
4840 if (RMWI.isElementwise()) {
4841 auto *VecTy = dyn_cast<FixedVectorType>(ElTy);
4842 Check(VecTy, "atomicrmw elementwise operand must have fixed vector type!",
4843 &RMWI, ElTy);
4844 if (VecTy)
4845 ScalarTy = VecTy->getElementType();
4846 }
4847
4848 if (Op == AtomicRMWInst::Xchg) {
4849 Check(ScalarTy->isIntegerTy() || ScalarTy->isFloatingPointTy() ||
4850 ScalarTy->isPointerTy(),
4851 "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
4852 " operand must have integer or floating point type!",
4853 &RMWI, ElTy);
4854 } else if (AtomicRMWInst::isFPOperation(Op)) {
4856 "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
4857 " operand must have floating-point or fixed vector of "
4858 "floating-point "
4859 "type!",
4860 &RMWI, ElTy);
4861 } else {
4862 Check(ScalarTy->isIntegerTy(),
4863 "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
4864 " operand must have integer type!",
4865 &RMWI, ElTy);
4866 }
4867 checkAtomicMemAccessSize(ElTy, &RMWI);
4869 "Invalid binary operation!", &RMWI);
4870 visitInstruction(RMWI);
4871}
4872
4873void Verifier::visitFenceInst(FenceInst &FI) {
4874 const AtomicOrdering Ordering = FI.getOrdering();
4875 Check(Ordering == AtomicOrdering::Acquire ||
4876 Ordering == AtomicOrdering::Release ||
4877 Ordering == AtomicOrdering::AcquireRelease ||
4878 Ordering == AtomicOrdering::SequentiallyConsistent,
4879 "fence instructions may only have acquire, release, acq_rel, or "
4880 "seq_cst ordering.",
4881 &FI);
4882 visitInstruction(FI);
4883}
4884
4885void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
4887 EVI.getIndices()) == EVI.getType(),
4888 "Invalid ExtractValueInst operands!", &EVI);
4889
4890 visitInstruction(EVI);
4891}
4892
4893void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
4895 IVI.getIndices()) ==
4896 IVI.getOperand(1)->getType(),
4897 "Invalid InsertValueInst operands!", &IVI);
4898
4899 visitInstruction(IVI);
4900}
4901
4902static Value *getParentPad(Value *EHPad) {
4903 if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
4904 return FPI->getParentPad();
4905
4906 return cast<CatchSwitchInst>(EHPad)->getParentPad();
4907}
4908
4909void Verifier::visitEHPadPredecessors(Instruction &I) {
4910 assert(I.isEHPad());
4911
4912 BasicBlock *BB = I.getParent();
4913 Function *F = BB->getParent();
4914
4915 Check(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I);
4916
4917 if (auto *LPI = dyn_cast<LandingPadInst>(&I)) {
4918 // The landingpad instruction defines its parent as a landing pad block. The
4919 // landing pad block may be branched to only by the unwind edge of an
4920 // invoke.
4921 for (BasicBlock *PredBB : predecessors(BB)) {
4922 const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator());
4923 Check(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
4924 "Block containing LandingPadInst must be jumped to "
4925 "only by the unwind edge of an invoke.",
4926 LPI);
4927 }
4928 return;
4929 }
4930 if (auto *CPI = dyn_cast<CatchPadInst>(&I)) {
4931 if (!pred_empty(BB))
4932 Check(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(),
4933 "Block containg CatchPadInst must be jumped to "
4934 "only by its catchswitch.",
4935 CPI);
4936 Check(BB != CPI->getCatchSwitch()->getUnwindDest(),
4937 "Catchswitch cannot unwind to one of its catchpads",
4938 CPI->getCatchSwitch(), CPI);
4939 return;
4940 }
4941
4942 // Verify that each pred has a legal terminator with a legal to/from EH
4943 // pad relationship.
4944 Instruction *ToPad = &I;
4945 Value *ToPadParent = getParentPad(ToPad);
4946 for (BasicBlock *PredBB : predecessors(BB)) {
4947 Instruction *TI = PredBB->getTerminator();
4948 Value *FromPad;
4949 if (auto *II = dyn_cast<InvokeInst>(TI)) {
4950 Check(II->getUnwindDest() == BB && II->getNormalDest() != BB,
4951 "EH pad must be jumped to via an unwind edge", ToPad, II);
4952 auto *CalledFn =
4953 dyn_cast<Function>(II->getCalledOperand()->stripPointerCasts());
4954 if (CalledFn && CalledFn->isIntrinsic() && II->doesNotThrow() &&
4955 !IntrinsicInst::mayLowerToFunctionCall(CalledFn->getIntrinsicID()))
4956 continue;
4957 if (auto Bundle = II->getOperandBundle(LLVMContext::OB_funclet))
4958 FromPad = Bundle->Inputs[0];
4959 else
4960 FromPad = ConstantTokenNone::get(II->getContext());
4961 } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
4962 FromPad = CRI->getOperand(0);
4963 Check(FromPad != ToPadParent, "A cleanupret must exit its cleanup", CRI);
4964 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
4965 FromPad = CSI;
4966 } else {
4967 Check(false, "EH pad must be jumped to via an unwind edge", ToPad, TI);
4968 }
4969
4970 // The edge may exit from zero or more nested pads.
4971 SmallPtrSet<Value *, 8> Seen;
4972 for (;; FromPad = getParentPad(FromPad)) {
4973 Check(FromPad != ToPad,
4974 "EH pad cannot handle exceptions raised within it", FromPad, TI);
4975 if (FromPad == ToPadParent) {
4976 // This is a legal unwind edge.
4977 break;
4978 }
4979 Check(!isa<ConstantTokenNone>(FromPad),
4980 "A single unwind edge may only enter one EH pad", TI);
4981 Check(Seen.insert(FromPad).second, "EH pad jumps through a cycle of pads",
4982 FromPad);
4983
4984 // This will be diagnosed on the corresponding instruction already. We
4985 // need the extra check here to make sure getParentPad() works.
4986 Check(isa<FuncletPadInst>(FromPad) || isa<CatchSwitchInst>(FromPad),
4987 "Parent pad must be catchpad/cleanuppad/catchswitch", TI);
4988 }
4989 }
4990}
4991
4992void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
4993 // The landingpad instruction is ill-formed if it doesn't have any clauses and
4994 // isn't a cleanup.
4995 Check(LPI.getNumClauses() > 0 || LPI.isCleanup(),
4996 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
4997
4998 visitEHPadPredecessors(LPI);
4999
5000 if (!LandingPadResultTy)
5001 LandingPadResultTy = LPI.getType();
5002 else
5003 Check(LandingPadResultTy == LPI.getType(),
5004 "The landingpad instruction should have a consistent result type "
5005 "inside a function.",
5006 &LPI);
5007
5008 Function *F = LPI.getParent()->getParent();
5009 Check(F->hasPersonalityFn(),
5010 "LandingPadInst needs to be in a function with a personality.", &LPI);
5011
5012 // The landingpad instruction must be the first non-PHI instruction in the
5013 // block.
5014 Check(LPI.getParent()->getLandingPadInst() == &LPI,
5015 "LandingPadInst not the first non-PHI instruction in the block.", &LPI);
5016
5017 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
5018 Constant *Clause = LPI.getClause(i);
5019 if (LPI.isCatch(i)) {
5020 Check(isa<PointerType>(Clause->getType()),
5021 "Catch operand does not have pointer type!", &LPI);
5022 } else {
5023 Check(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
5025 "Filter operand is not an array of constants!", &LPI);
5026 }
5027 }
5028
5029 visitInstruction(LPI);
5030}
5031
5032void Verifier::visitResumeInst(ResumeInst &RI) {
5034 "ResumeInst needs to be in a function with a personality.", &RI);
5035
5036 if (!LandingPadResultTy)
5037 LandingPadResultTy = RI.getValue()->getType();
5038 else
5039 Check(LandingPadResultTy == RI.getValue()->getType(),
5040 "The resume instruction should have a consistent result type "
5041 "inside a function.",
5042 &RI);
5043
5044 visitTerminator(RI);
5045}
5046
5047void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
5048 BasicBlock *BB = CPI.getParent();
5049
5050 Function *F = BB->getParent();
5051 Check(F->hasPersonalityFn(),
5052 "CatchPadInst needs to be in a function with a personality.", &CPI);
5053
5055 "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
5056 CPI.getParentPad());
5057
5058 // The catchpad instruction must be the first non-PHI instruction in the
5059 // block.
5060 Check(&*BB->getFirstNonPHIIt() == &CPI,
5061 "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
5062
5064 [](Use &U) {
5065 auto *V = U.get();
5066 return isa<Constant>(V) || isa<AllocaInst>(V);
5067 }),
5068 "Argument operand must be alloca or constant.", &CPI);
5069
5070 visitEHPadPredecessors(CPI);
5071 visitFuncletPadInst(CPI);
5072}
5073
5074void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
5075 Check(isa<CatchPadInst>(CatchReturn.getOperand(0)),
5076 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
5077 CatchReturn.getOperand(0));
5078
5079 visitTerminator(CatchReturn);
5080}
5081
5082void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
5083 BasicBlock *BB = CPI.getParent();
5084
5085 Function *F = BB->getParent();
5086 Check(F->hasPersonalityFn(),
5087 "CleanupPadInst needs to be in a function with a personality.", &CPI);
5088
5089 // The cleanuppad instruction must be the first non-PHI instruction in the
5090 // block.
5091 Check(&*BB->getFirstNonPHIIt() == &CPI,
5092 "CleanupPadInst not the first non-PHI instruction in the block.", &CPI);
5093
5094 auto *ParentPad = CPI.getParentPad();
5095 Check(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
5096 "CleanupPadInst has an invalid parent.", &CPI);
5097
5098 visitEHPadPredecessors(CPI);
5099 visitFuncletPadInst(CPI);
5100}
5101
5102void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
5103 User *FirstUser = nullptr;
5104 Value *FirstUnwindPad = nullptr;
5105 SmallVector<FuncletPadInst *, 8> Worklist({&FPI});
5106 SmallPtrSet<FuncletPadInst *, 8> Seen;
5107
5108 while (!Worklist.empty()) {
5109 FuncletPadInst *CurrentPad = Worklist.pop_back_val();
5110 Check(Seen.insert(CurrentPad).second,
5111 "FuncletPadInst must not be nested within itself", CurrentPad);
5112 Value *UnresolvedAncestorPad = nullptr;
5113 for (User *U : CurrentPad->users()) {
5114 BasicBlock *UnwindDest;
5115 if (auto *CRI = dyn_cast<CleanupReturnInst>(U)) {
5116 UnwindDest = CRI->getUnwindDest();
5117 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(U)) {
5118 // We allow catchswitch unwind to caller to nest
5119 // within an outer pad that unwinds somewhere else,
5120 // because catchswitch doesn't have a nounwind variant.
5121 // See e.g. SimplifyCFGOpt::SimplifyUnreachable.
5122 if (CSI->unwindsToCaller())
5123 continue;
5124 UnwindDest = CSI->getUnwindDest();
5125 } else if (auto *II = dyn_cast<InvokeInst>(U)) {
5126 UnwindDest = II->getUnwindDest();
5127 } else if (isa<CallInst>(U)) {
5128 // Calls which don't unwind may be found inside funclet
5129 // pads that unwind somewhere else. We don't *require*
5130 // such calls to be annotated nounwind.
5131 continue;
5132 } else if (auto *CPI = dyn_cast<CleanupPadInst>(U)) {
5133 // The unwind dest for a cleanup can only be found by
5134 // recursive search. Add it to the worklist, and we'll
5135 // search for its first use that determines where it unwinds.
5136 Worklist.push_back(CPI);
5137 continue;
5138 } else {
5139 Check(isa<CatchReturnInst>(U), "Bogus funclet pad use", U);
5140 continue;
5141 }
5142
5143 Value *UnwindPad;
5144 bool ExitsFPI;
5145 if (UnwindDest) {
5146 UnwindPad = &*UnwindDest->getFirstNonPHIIt();
5147 if (!cast<Instruction>(UnwindPad)->isEHPad())
5148 continue;
5149 Value *UnwindParent = getParentPad(UnwindPad);
5150 // Ignore unwind edges that don't exit CurrentPad.
5151 if (UnwindParent == CurrentPad)
5152 continue;
5153 // Determine whether the original funclet pad is exited,
5154 // and if we are scanning nested pads determine how many
5155 // of them are exited so we can stop searching their
5156 // children.
5157 Value *ExitedPad = CurrentPad;
5158 ExitsFPI = false;
5159 do {
5160 if (ExitedPad == &FPI) {
5161 ExitsFPI = true;
5162 // Now we can resolve any ancestors of CurrentPad up to
5163 // FPI, but not including FPI since we need to make sure
5164 // to check all direct users of FPI for consistency.
5165 UnresolvedAncestorPad = &FPI;
5166 break;
5167 }
5168 Value *ExitedParent = getParentPad(ExitedPad);
5169 if (ExitedParent == UnwindParent) {
5170 // ExitedPad is the ancestor-most pad which this unwind
5171 // edge exits, so we can resolve up to it, meaning that
5172 // ExitedParent is the first ancestor still unresolved.
5173 UnresolvedAncestorPad = ExitedParent;
5174 break;
5175 }
5176 ExitedPad = ExitedParent;
5177 } while (!isa<ConstantTokenNone>(ExitedPad));
5178 } else {
5179 // Unwinding to caller exits all pads.
5180 UnwindPad = ConstantTokenNone::get(FPI.getContext());
5181 ExitsFPI = true;
5182 UnresolvedAncestorPad = &FPI;
5183 }
5184
5185 if (ExitsFPI) {
5186 // This unwind edge exits FPI. Make sure it agrees with other
5187 // such edges.
5188 if (FirstUser) {
5189 Check(UnwindPad == FirstUnwindPad,
5190 "Unwind edges out of a funclet "
5191 "pad must have the same unwind "
5192 "dest",
5193 &FPI, U, FirstUser);
5194 } else {
5195 FirstUser = U;
5196 FirstUnwindPad = UnwindPad;
5197 // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds
5198 if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) &&
5199 getParentPad(UnwindPad) == getParentPad(&FPI))
5200 SiblingFuncletInfo[&FPI] = cast<Instruction>(U);
5201 }
5202 }
5203 // Make sure we visit all uses of FPI, but for nested pads stop as
5204 // soon as we know where they unwind to.
5205 if (CurrentPad != &FPI)
5206 break;
5207 }
5208 if (UnresolvedAncestorPad) {
5209 if (CurrentPad == UnresolvedAncestorPad) {
5210 // When CurrentPad is FPI itself, we don't mark it as resolved even if
5211 // we've found an unwind edge that exits it, because we need to verify
5212 // all direct uses of FPI.
5213 assert(CurrentPad == &FPI);
5214 continue;
5215 }
5216 // Pop off the worklist any nested pads that we've found an unwind
5217 // destination for. The pads on the worklist are the uncles,
5218 // great-uncles, etc. of CurrentPad. We've found an unwind destination
5219 // for all ancestors of CurrentPad up to but not including
5220 // UnresolvedAncestorPad.
5221 Value *ResolvedPad = CurrentPad;
5222 while (!Worklist.empty()) {
5223 Value *UnclePad = Worklist.back();
5224 Value *AncestorPad = getParentPad(UnclePad);
5225 // Walk ResolvedPad up the ancestor list until we either find the
5226 // uncle's parent or the last resolved ancestor.
5227 while (ResolvedPad != AncestorPad) {
5228 Value *ResolvedParent = getParentPad(ResolvedPad);
5229 if (ResolvedParent == UnresolvedAncestorPad) {
5230 break;
5231 }
5232 ResolvedPad = ResolvedParent;
5233 }
5234 // If the resolved ancestor search didn't find the uncle's parent,
5235 // then the uncle is not yet resolved.
5236 if (ResolvedPad != AncestorPad)
5237 break;
5238 // This uncle is resolved, so pop it from the worklist.
5239 Worklist.pop_back();
5240 }
5241 }
5242 }
5243
5244 if (FirstUnwindPad) {
5245 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.getParentPad())) {
5246 BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
5247 Value *SwitchUnwindPad;
5248 if (SwitchUnwindDest)
5249 SwitchUnwindPad = &*SwitchUnwindDest->getFirstNonPHIIt();
5250 else
5251 SwitchUnwindPad = ConstantTokenNone::get(FPI.getContext());
5252 Check(SwitchUnwindPad == FirstUnwindPad,
5253 "Unwind edges out of a catch must have the same unwind dest as "
5254 "the parent catchswitch",
5255 &FPI, FirstUser, CatchSwitch);
5256 }
5257 }
5258
5259 visitInstruction(FPI);
5260}
5261
5262void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
5263 BasicBlock *BB = CatchSwitch.getParent();
5264
5265 Function *F = BB->getParent();
5266 Check(F->hasPersonalityFn(),
5267 "CatchSwitchInst needs to be in a function with a personality.",
5268 &CatchSwitch);
5269
5270 // The catchswitch instruction must be the first non-PHI instruction in the
5271 // block.
5272 Check(&*BB->getFirstNonPHIIt() == &CatchSwitch,
5273 "CatchSwitchInst not the first non-PHI instruction in the block.",
5274 &CatchSwitch);
5275
5276 auto *ParentPad = CatchSwitch.getParentPad();
5277 Check(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
5278 "CatchSwitchInst has an invalid parent.", ParentPad);
5279
5280 if (BasicBlock *UnwindDest = CatchSwitch.getUnwindDest()) {
5281 BasicBlock::iterator I = UnwindDest->getFirstNonPHIIt();
5282 Check(I->isEHPad() && !isa<LandingPadInst>(I),
5283 "CatchSwitchInst must unwind to an EH block which is not a "
5284 "landingpad.",
5285 &CatchSwitch);
5286
5287 // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds
5288 if (getParentPad(&*I) == ParentPad)
5289 SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
5290 }
5291
5292 Check(CatchSwitch.getNumHandlers() != 0,
5293 "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
5294
5295 for (BasicBlock *Handler : CatchSwitch.handlers()) {
5296 Check(isa<CatchPadInst>(Handler->getFirstNonPHIIt()),
5297 "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
5298 }
5299
5300 visitEHPadPredecessors(CatchSwitch);
5301 visitTerminator(CatchSwitch);
5302}
5303
5304void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
5306 "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
5307 CRI.getOperand(0));
5308
5309 if (BasicBlock *UnwindDest = CRI.getUnwindDest()) {
5310 BasicBlock::iterator I = UnwindDest->getFirstNonPHIIt();
5311 Check(I->isEHPad() && !isa<LandingPadInst>(I),
5312 "CleanupReturnInst must unwind to an EH block which is not a "
5313 "landingpad.",
5314 &CRI);
5315 }
5316
5317 visitTerminator(CRI);
5318}
5319
5320void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
5321 Instruction *Op = cast<Instruction>(I.getOperand(i));
5322 // If the we have an invalid invoke, don't try to compute the dominance.
5323 // We already reject it in the invoke specific checks and the dominance
5324 // computation doesn't handle multiple edges.
5325 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
5326 if (II->getNormalDest() == II->getUnwindDest())
5327 return;
5328 }
5329
5330 // Quick check whether the def has already been encountered in the same block.
5331 // PHI nodes are not checked to prevent accepting preceding PHIs, because PHI
5332 // uses are defined to happen on the incoming edge, not at the instruction.
5333 //
5334 // FIXME: If this operand is a MetadataAsValue (wrapping a LocalAsMetadata)
5335 // wrapping an SSA value, assert that we've already encountered it. See
5336 // related FIXME in Mapper::mapLocalAsMetadata in ValueMapper.cpp.
5337 if (!isa<PHINode>(I) && InstsInThisBlock.count(Op))
5338 return;
5339
5340 const Use &U = I.getOperandUse(i);
5341 Check(DT.dominates(Op, U), "Instruction does not dominate all uses!", Op, &I);
5342}
5343
5344void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) {
5345 Check(I.getType()->isPointerTy(),
5346 "dereferenceable, dereferenceable_or_null "
5347 "apply only to pointer types",
5348 &I);
5350 "dereferenceable, dereferenceable_or_null apply only to load"
5351 " and inttoptr instructions, use attributes for calls or invokes",
5352 &I);
5353 Check(MD->getNumOperands() == 1,
5354 "dereferenceable, dereferenceable_or_null "
5355 "take one operand!",
5356 &I);
5357 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
5358 Check(CI && CI->getType()->isIntegerTy(64),
5359 "dereferenceable, "
5360 "dereferenceable_or_null metadata value must be an i64!",
5361 &I);
5362}
5363
5364void Verifier::visitNofreeMetadata(Instruction &I, MDNode *MD) {
5365 Check(I.getType()->isPointerTy(), "nofree applies only to pointer types", &I);
5366 Check((isa<IntToPtrInst>(I)), "nofree applies only to inttoptr instruction",
5367 &I);
5368 Check(MD->getNumOperands() == 0, "nofree metadata must be empty", &I);
5369}
5370
5371void Verifier::visitProfMetadata(Instruction &I, MDNode *MD) {
5372 auto GetBranchingTerminatorNumOperands = [&]() {
5373 unsigned ExpectedNumOperands = 0;
5374 if (CondBrInst *BI = dyn_cast<CondBrInst>(&I))
5375 ExpectedNumOperands = BI->getNumSuccessors();
5376 else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
5377 ExpectedNumOperands = SI->getNumSuccessors();
5378 else if (isa<CallInst>(&I))
5379 ExpectedNumOperands = 1;
5380 else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
5381 ExpectedNumOperands = IBI->getNumDestinations();
5382 else if (isa<SelectInst>(&I))
5383 ExpectedNumOperands = 2;
5384 else if (CallBrInst *CI = dyn_cast<CallBrInst>(&I))
5385 ExpectedNumOperands = CI->getNumSuccessors();
5386 return ExpectedNumOperands;
5387 };
5388 Check(MD->getNumOperands() >= 1,
5389 "!prof annotations should have at least 1 operand", MD);
5390 // Check first operand.
5391 Check(MD->getOperand(0) != nullptr, "first operand should not be null", MD);
5393 "expected string with name of the !prof annotation", MD);
5394 MDString *MDS = cast<MDString>(MD->getOperand(0));
5395 StringRef ProfName = MDS->getString();
5396
5398 Check(GetBranchingTerminatorNumOperands() != 0 || isa<InvokeInst>(I),
5399 "'unknown' !prof should only appear on instructions on which "
5400 "'branch_weights' would",
5401 MD);
5402 verifyUnknownProfileMetadata(MD);
5403 return;
5404 }
5405
5406 Check(MD->getNumOperands() >= 2,
5407 "!prof annotations should have no less than 2 operands", MD);
5408
5409 // Check consistency of !prof branch_weights metadata.
5410 if (ProfName == MDProfLabels::BranchWeights) {
5411 unsigned NumBranchWeights = getNumBranchWeights(*MD);
5412 if (isa<InvokeInst>(&I)) {
5413 Check(NumBranchWeights == 1 || NumBranchWeights == 2,
5414 "Wrong number of InvokeInst branch_weights operands", MD);
5415 } else {
5416 const unsigned ExpectedNumOperands = GetBranchingTerminatorNumOperands();
5417 if (ExpectedNumOperands == 0)
5418 CheckFailed("!prof branch_weights are not allowed for this instruction",
5419 MD);
5420
5421 Check(NumBranchWeights == ExpectedNumOperands, "Wrong number of operands",
5422 MD);
5423 }
5424 for (unsigned i = getBranchWeightOffset(MD); i < MD->getNumOperands();
5425 ++i) {
5426 auto &MDO = MD->getOperand(i);
5427 Check(MDO, "second operand should not be null", MD);
5429 "!prof brunch_weights operand is not a const int");
5430 }
5431 } else if (ProfName == MDProfLabels::ValueProfile) {
5432 Check(isValueProfileMD(MD), "invalid value profiling metadata", MD);
5433 ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
5434 Check(KindInt, "VP !prof missing kind argument", MD);
5435
5436 auto Kind = KindInt->getZExtValue();
5437 Check(Kind >= InstrProfValueKind::IPVK_First &&
5438 Kind <= InstrProfValueKind::IPVK_Last,
5439 "Invalid VP !prof kind", MD);
5440 Check(MD->getNumOperands() % 2 == 1,
5441 "VP !prof should have an even number "
5442 "of arguments after 'VP'",
5443 MD);
5444 if (Kind == InstrProfValueKind::IPVK_IndirectCallTarget ||
5445 Kind == InstrProfValueKind::IPVK_MemOPSize)
5447 "VP !prof indirect call or memop size expected to be applied to "
5448 "CallBase instructions only",
5449 MD);
5450
5451 DenseSet<uint64_t> ProfileValues;
5452 for (unsigned I = 3; I < MD->getNumOperands(); I += 2) {
5453 ConstantInt *ProfileValue =
5455 Check(ProfileValue, "VP !prof value operand is not a const int", MD);
5456 uint64_t ProfileValueInt = ProfileValue->getZExtValue();
5457 auto [ValueIt, Inserted] = ProfileValues.insert(ProfileValueInt);
5458 Check(Inserted, "VP !prof should not have duplicate profile values", MD);
5459 }
5460 } else {
5461 CheckFailed("expected either branch_weights or VP profile name", MD);
5462 }
5463}
5464
5465void Verifier::visitDIAssignIDMetadata(Instruction &I, MDNode *MD) {
5466 assert(I.hasMetadata(LLVMContext::MD_DIAssignID));
5467 // DIAssignID metadata must be attached to either an alloca or some form of
5468 // store/memory-writing instruction.
5469 // FIXME: We allow all intrinsic insts here to avoid trying to enumerate all
5470 // possible store intrinsics.
5471 bool ExpectedInstTy =
5473 CheckDI(ExpectedInstTy, "!DIAssignID attached to unexpected instruction kind",
5474 I, MD);
5475 // Iterate over the MetadataAsValue uses of the DIAssignID - these should
5476 // only be found as DbgAssignIntrinsic operands.
5477 if (auto *AsValue = MetadataAsValue::getIfExists(Context, MD)) {
5478 for (auto *User : AsValue->users()) {
5480 "!DIAssignID should only be used by llvm.dbg.assign intrinsics",
5481 MD, User);
5482 // All of the dbg.assign intrinsics should be in the same function as I.
5483 if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(User))
5484 CheckDI(DAI->getFunction() == I.getFunction(),
5485 "dbg.assign not in same function as inst", DAI, &I);
5486 }
5487 }
5488 for (DbgVariableRecord *DVR :
5489 cast<DIAssignID>(MD)->getAllDbgVariableRecordUsers()) {
5490 CheckDI(DVR->isDbgAssign(),
5491 "!DIAssignID should only be used by Assign DVRs.", MD, DVR);
5492 CheckDI(DVR->getFunction() == I.getFunction(),
5493 "DVRAssign not in same function as inst", DVR, &I);
5494 }
5495}
5496
5497void Verifier::visitMMRAMetadata(Instruction &I, MDNode *MD) {
5499 "!mmra metadata attached to unexpected instruction kind", I, MD);
5500
5501 // MMRA Metadata should either be a tag, e.g. !{!"foo", !"bar"}, or a
5502 // list of tags such as !2 in the following example:
5503 // !0 = !{!"a", !"b"}
5504 // !1 = !{!"c", !"d"}
5505 // !2 = !{!0, !1}
5506 if (MMRAMetadata::isTagMD(MD))
5507 return;
5508
5509 Check(isa<MDTuple>(MD), "!mmra expected to be a metadata tuple", I, MD);
5510 for (const MDOperand &MDOp : MD->operands())
5511 Check(MMRAMetadata::isTagMD(MDOp.get()),
5512 "!mmra metadata tuple operand is not an MMRA tag", I, MDOp.get());
5513}
5514
5515void Verifier::visitCallStackMetadata(MDNode *MD) {
5516 // Call stack metadata should consist of a list of at least 1 constant int
5517 // (representing a hash of the location).
5518 Check(MD->getNumOperands() >= 1,
5519 "call stack metadata should have at least 1 operand", MD);
5520
5521 for (const auto &Op : MD->operands())
5523 "call stack metadata operand should be constant integer", Op);
5524}
5525
5526void Verifier::visitMemProfMetadata(Instruction &I, MDNode *MD) {
5527 Check(isa<CallBase>(I), "!memprof metadata should only exist on calls", &I);
5528 Check(MD->getNumOperands() >= 1,
5529 "!memprof annotations should have at least 1 metadata operand "
5530 "(MemInfoBlock)",
5531 MD);
5532
5533 // Check each MIB
5534 for (auto &MIBOp : MD->operands()) {
5535 MDNode *MIB = dyn_cast<MDNode>(MIBOp);
5536 // The first operand of an MIB should be the call stack metadata.
5537 // There rest of the operands should be MDString tags, and there should be
5538 // at least one.
5539 Check(MIB->getNumOperands() >= 2,
5540 "Each !memprof MemInfoBlock should have at least 2 operands", MIB);
5541
5542 // Check call stack metadata (first operand).
5543 Check(MIB->getOperand(0) != nullptr,
5544 "!memprof MemInfoBlock first operand should not be null", MIB);
5545 Check(isa<MDNode>(MIB->getOperand(0)),
5546 "!memprof MemInfoBlock first operand should be an MDNode", MIB);
5547 MDNode *StackMD = dyn_cast<MDNode>(MIB->getOperand(0));
5548 visitCallStackMetadata(StackMD);
5549
5550 // The second MIB operand should be MDString.
5552 "!memprof MemInfoBlock second operand should be an MDString", MIB);
5553
5554 // Any remaining should be MDNode that are pairs of integers
5555 for (unsigned I = 2; I < MIB->getNumOperands(); ++I) {
5556 MDNode *OpNode = dyn_cast<MDNode>(MIB->getOperand(I));
5557 Check(OpNode, "Not all !memprof MemInfoBlock operands 2 to N are MDNode",
5558 MIB);
5559 Check(OpNode->getNumOperands() == 2,
5560 "Not all !memprof MemInfoBlock operands 2 to N are MDNode with 2 "
5561 "operands",
5562 MIB);
5563 // Check that all of Op's operands are ConstantInt.
5564 Check(llvm::all_of(OpNode->operands(),
5565 [](const MDOperand &Op) {
5566 return mdconst::hasa<ConstantInt>(Op);
5567 }),
5568 "Not all !memprof MemInfoBlock operands 2 to N are MDNode with "
5569 "ConstantInt operands",
5570 MIB);
5571 }
5572 }
5573}
5574
5575void Verifier::visitCallsiteMetadata(Instruction &I, MDNode *MD) {
5576 Check(isa<CallBase>(I), "!callsite metadata should only exist on calls", &I);
5577 // Verify the partial callstack annotated from memprof profiles. This callsite
5578 // is a part of a profiled allocation callstack.
5579 visitCallStackMetadata(MD);
5580}
5581
5582static inline bool isConstantIntMetadataOperand(const Metadata *MD) {
5583 if (auto *VAL = dyn_cast<ValueAsMetadata>(MD))
5584 return isa<ConstantInt>(VAL->getValue());
5585 return false;
5586}
5587
5588void Verifier::visitCalleeTypeMetadata(Instruction &I, MDNode *MD) {
5589 Check(isa<CallBase>(I), "!callee_type metadata should only exist on calls",
5590 &I);
5591 for (Metadata *Op : MD->operands()) {
5593 "The callee_type metadata must be a list of type metadata nodes", Op);
5594 auto *TypeMD = cast<MDNode>(Op);
5595 Check(TypeMD->getNumOperands() == 2,
5596 "Well-formed generalized type metadata must contain exactly two "
5597 "operands",
5598 Op);
5599 Check(isConstantIntMetadataOperand(TypeMD->getOperand(0)) &&
5600 mdconst::extract<ConstantInt>(TypeMD->getOperand(0))->isZero(),
5601 "The first operand of type metadata for functions must be zero", Op);
5602 Check(TypeMD->hasGeneralizedMDString(),
5603 "Only generalized type metadata can be part of the callee_type "
5604 "metadata list",
5605 Op);
5606 }
5607}
5608
5609void Verifier::visitAnnotationMetadata(MDNode *Annotation) {
5610 Check(isa<MDTuple>(Annotation), "annotation must be a tuple");
5611 Check(Annotation->getNumOperands() >= 1,
5612 "annotation must have at least one operand");
5613 for (const MDOperand &Op : Annotation->operands()) {
5614 bool TupleOfStrings =
5615 isa<MDTuple>(Op.get()) &&
5616 all_of(cast<MDTuple>(Op)->operands(), [](auto &Annotation) {
5617 return isa<MDString>(Annotation.get());
5618 });
5619 Check(isa<MDString>(Op.get()) || TupleOfStrings,
5620 "operands must be a string or a tuple of strings");
5621 }
5622}
5623
5624void Verifier::visitAliasScopeMetadata(const MDNode *MD) {
5625 unsigned NumOps = MD->getNumOperands();
5626 Check(NumOps >= 2 && NumOps <= 3, "scope must have two or three operands",
5627 MD);
5628 Check(MD->getOperand(0).get() == MD || isa<MDString>(MD->getOperand(0)),
5629 "first scope operand must be self-referential or string", MD);
5630 if (NumOps == 3)
5632 "third scope operand must be string (if used)", MD);
5633
5634 MDNode *Domain = dyn_cast<MDNode>(MD->getOperand(1));
5635 Check(Domain != nullptr, "second scope operand must be MDNode", MD);
5636
5637 unsigned NumDomainOps = Domain->getNumOperands();
5638 Check(NumDomainOps >= 1 && NumDomainOps <= 2,
5639 "domain must have one or two operands", Domain);
5640 Check(Domain->getOperand(0).get() == Domain ||
5641 isa<MDString>(Domain->getOperand(0)),
5642 "first domain operand must be self-referential or string", Domain);
5643 if (NumDomainOps == 2)
5644 Check(isa<MDString>(Domain->getOperand(1)),
5645 "second domain operand must be string (if used)", Domain);
5646}
5647
5648void Verifier::visitAliasScopeListMetadata(const MDNode *MD) {
5649 for (const MDOperand &Op : MD->operands()) {
5650 const MDNode *OpMD = dyn_cast<MDNode>(Op);
5651 Check(OpMD != nullptr, "scope list must consist of MDNodes", MD);
5652 visitAliasScopeMetadata(OpMD);
5653 }
5654}
5655
5656void Verifier::visitAccessGroupMetadata(const MDNode *MD) {
5657 auto IsValidAccessScope = [](const MDNode *MD) {
5658 return MD->getNumOperands() == 0 && MD->isDistinct();
5659 };
5660
5661 // It must be either an access scope itself...
5662 if (IsValidAccessScope(MD))
5663 return;
5664
5665 // ...or a list of access scopes.
5666 for (const MDOperand &Op : MD->operands()) {
5667 const MDNode *OpMD = dyn_cast<MDNode>(Op);
5668 Check(OpMD != nullptr, "Access scope list must consist of MDNodes", MD);
5669 Check(IsValidAccessScope(OpMD),
5670 "Access scope list contains invalid access scope", MD);
5671 }
5672}
5673
5674void Verifier::visitCapturesMetadata(Instruction &I, const MDNode *Captures) {
5675 static const char *ValidArgs[] = {"address_is_null", "address",
5676 "read_provenance", "provenance"};
5677
5678 auto *SI = dyn_cast<StoreInst>(&I);
5679 Check(SI, "!captures metadata can only be applied to store instructions", &I);
5680 Check(SI->getValueOperand()->getType()->isPointerTy(),
5681 "!captures metadata can only be applied to store with value operand of "
5682 "pointer type",
5683 &I);
5684 Check(Captures->getNumOperands() != 0, "!captures metadata cannot be empty",
5685 &I);
5686
5687 for (Metadata *Op : Captures->operands()) {
5688 auto *Str = dyn_cast<MDString>(Op);
5689 Check(Str, "!captures metadata must be a list of strings", &I);
5690 Check(is_contained(ValidArgs, Str->getString()),
5691 "invalid entry in !captures metadata", &I, Str);
5692 }
5693}
5694
5695void Verifier::visitAllocTokenMetadata(Instruction &I, MDNode *MD) {
5696 Check(isa<CallBase>(I), "!alloc_token should only exist on calls", &I);
5697 Check(MD->getNumOperands() == 2, "!alloc_token must have 2 operands", MD);
5698 Check(isa<MDString>(MD->getOperand(0)), "expected string", MD);
5700 "expected integer constant", MD);
5701}
5702
5703void Verifier::visitInlineHistoryMetadata(Instruction &I, MDNode *MD) {
5704 Check(isa<CallBase>(I), "!inline_history should only exist on calls", &I);
5705 for (Metadata *Op : MD->operands()) {
5706 // Can be null when a function is erased.
5707 if (!Op)
5708 continue;
5711 ->getValue()
5712 ->stripPointerCastsAndAliases()),
5713 "!inline_history operands must be functions or null", MD);
5714 }
5715}
5716
5717void Verifier::visitMemCacheHintMetadata(Instruction &I, MDNode *MD) {
5718 Check(I.mayReadOrWriteMemory(),
5719 "!mem.cache_hint is only valid on memory operations", &I);
5720
5721 Check(MD->getNumOperands() % 2 == 0,
5722 "!mem.cache_hint must have even number of operands "
5723 "(operand_no, hint_node pairs)",
5724 MD);
5725
5726 const auto *CB = dyn_cast<CallBase>(&I);
5727 if (CB)
5728 Check(CB->getIntrinsicID() != Intrinsic::not_intrinsic,
5729 "!mem.cache_hint is not supported on non-intrinsic calls", &I);
5730
5731 unsigned NumOperands = CB ? CB->arg_size() : I.getNumOperands();
5732
5733 SmallDenseSet<unsigned, 4> SeenOperandNos;
5734 std::optional<uint64_t> LastOperandNo;
5735
5736 // Top-level metadata alternates: i32 operand_no, MDNode hint_node.
5737 for (unsigned J = 0; J + 1 < MD->getNumOperands(); J += 2) {
5738 auto *OpNoCI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(J));
5739 Check(OpNoCI,
5740 "!mem.cache_hint must alternate between i32 operand numbers and "
5741 "metadata hint nodes",
5742 MD);
5743
5744 Check(OpNoCI->getValue().isNonNegative(),
5745 "!mem.cache_hint operand number must be non-negative", MD);
5746
5747 uint64_t OperandNo = OpNoCI->getZExtValue();
5748 Check(OperandNo < NumOperands,
5749 "!mem.cache_hint operand number is out of range", &I);
5750
5751 Value *Operand =
5752 CB ? CB->getArgOperand(OperandNo) : I.getOperand(OperandNo);
5753 Check(Operand->getType()->isPtrOrPtrVectorTy(),
5754 "!mem.cache_hint operand number must refer to a pointer operand", &I);
5755
5756 bool Inserted = SeenOperandNos.insert(OperandNo).second;
5757 Check(Inserted, "!mem.cache_hint contains duplicate operand number", MD);
5758
5759 Check(!Inserted || !LastOperandNo || OperandNo > *LastOperandNo,
5760 "!mem.cache_hint operand numbers must be in increasing order", MD);
5761 LastOperandNo = OperandNo;
5762
5763 const auto *Node = dyn_cast<MDNode>(MD->getOperand(J + 1));
5764 Check(Node,
5765 "!mem.cache_hint must alternate between i32 operand numbers and "
5766 "metadata hint nodes",
5767 MD);
5768
5769 Check(Node->getNumOperands() % 2 == 0,
5770 "!mem.cache_hint hint node must have even number of operands "
5771 "(key-value pairs)",
5772 Node);
5773
5774 StringSet<> SeenKeys;
5775 for (unsigned K = 0; K + 1 < Node->getNumOperands(); K += 2) {
5776 const auto *Key = dyn_cast<MDString>(Node->getOperand(K));
5777 Check(Key, "!mem.cache_hint key must be a string", Node);
5778
5779 StringRef KeyStr = Key->getString();
5780 Check(SeenKeys.insert(KeyStr).second,
5781 "!mem.cache_hint hint node contains duplicate key", Node);
5782
5783 const Metadata *Value = Node->getOperand(K + 1).get();
5786 "!mem.cache_hint value must be a string or integer", Node);
5787 }
5788 }
5789}
5790
5791/// verifyInstruction - Verify that an instruction is well formed.
5792///
5793void Verifier::visitInstruction(Instruction &I) {
5794 BasicBlock *BB = I.getParent();
5795 Check(BB, "Instruction not embedded in basic block!", &I);
5796
5797 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
5798 for (User *U : I.users()) {
5799 Check(U != (User *)&I || !DT.isReachableFromEntry(BB),
5800 "Only PHI nodes may reference their own value!", &I);
5801 }
5802 }
5803
5804 // Check that void typed values don't have names
5805 Check(!I.getType()->isVoidTy() || !I.hasName(),
5806 "Instruction has a name, but provides a void value!", &I);
5807
5808 // Check that the return value of the instruction is either void or a legal
5809 // value type.
5810 Check(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
5811 "Instruction returns a non-scalar type!", &I);
5812
5813 // Check that the instruction doesn't produce metadata. Calls are already
5814 // checked against the callee type.
5815 Check(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
5816 "Invalid use of metadata!", &I);
5817
5818 // Check that all uses of the instruction, if they are instructions
5819 // themselves, actually have parent basic blocks. If the use is not an
5820 // instruction, it is an error!
5821 for (Use &U : I.uses()) {
5822 if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
5823 Check(Used->getParent() != nullptr,
5824 "Instruction referencing"
5825 " instruction not embedded in a basic block!",
5826 &I, Used);
5827 else {
5828 CheckFailed("Use of instruction is not an instruction!", U);
5829 return;
5830 }
5831 }
5832
5833 // Get a pointer to the call base of the instruction if it is some form of
5834 // call.
5835 const CallBase *CBI = dyn_cast<CallBase>(&I);
5836
5837 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
5838 Check(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
5839
5840 // Check to make sure that only first-class-values are operands to
5841 // instructions.
5842 if (!I.getOperand(i)->getType()->isFirstClassType()) {
5843 Check(false, "Instruction operands must be first-class values!", &I);
5844 }
5845
5846 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
5847 // This code checks whether the function is used as the operand of a
5848 // clang_arc_attachedcall operand bundle.
5849 auto IsAttachedCallOperand = [](Function *F, const CallBase *CBI,
5850 int Idx) {
5851 return CBI && CBI->isOperandBundleOfType(
5853 };
5854
5855 // Check to make sure that the "address of" an intrinsic function is never
5856 // taken. Ignore cases where the address of the intrinsic function is used
5857 // as the argument of operand bundle "clang.arc.attachedcall" as those
5858 // cases are handled in verifyAttachedCallBundle.
5859 Check((!F->isIntrinsic() ||
5860 (CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i)) ||
5861 IsAttachedCallOperand(F, CBI, i)),
5862 "Cannot take the address of an intrinsic!", &I);
5863 Check(!F->isIntrinsic() || isa<CallInst>(I) || isa<CallBrInst>(I) ||
5864 F->getIntrinsicID() == Intrinsic::donothing ||
5865 F->getIntrinsicID() == Intrinsic::seh_try_begin ||
5866 F->getIntrinsicID() == Intrinsic::seh_try_end ||
5867 F->getIntrinsicID() == Intrinsic::seh_scope_begin ||
5868 F->getIntrinsicID() == Intrinsic::seh_scope_end ||
5869 F->getIntrinsicID() == Intrinsic::coro_resume ||
5870 F->getIntrinsicID() == Intrinsic::coro_destroy ||
5871 F->getIntrinsicID() == Intrinsic::coro_await_suspend_void ||
5872 F->getIntrinsicID() == Intrinsic::coro_await_suspend_bool ||
5873 F->getIntrinsicID() == Intrinsic::coro_await_suspend_handle ||
5874 F->getIntrinsicID() ==
5875 Intrinsic::experimental_patchpoint_void ||
5876 F->getIntrinsicID() == Intrinsic::experimental_patchpoint ||
5877 F->getIntrinsicID() == Intrinsic::fake_use ||
5878 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint ||
5879 F->getIntrinsicID() == Intrinsic::wasm_throw ||
5880 F->getIntrinsicID() == Intrinsic::wasm_rethrow ||
5881 IsAttachedCallOperand(F, CBI, i),
5882 "Cannot invoke an intrinsic other than donothing, patchpoint, "
5883 "statepoint, coro_resume, coro_destroy, clang.arc.attachedcall or "
5884 "wasm.(re)throw",
5885 &I);
5886 Check(F->getParent() == &M, "Referencing function in another module!", &I,
5887 &M, F, F->getParent());
5888 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
5889 Check(OpBB->getParent() == BB->getParent(),
5890 "Referring to a basic block in another function!", &I);
5891 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
5892 Check(OpArg->getParent() == BB->getParent(),
5893 "Referring to an argument in another function!", &I);
5894 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
5895 Check(GV->getParent() == &M, "Referencing global in another module!", &I,
5896 &M, GV, GV->getParent());
5897 } else if (Instruction *OpInst = dyn_cast<Instruction>(I.getOperand(i))) {
5898 Check(OpInst->getFunction() == BB->getParent(),
5899 "Referring to an instruction in another function!", &I);
5900 verifyDominatesUse(I, i);
5901 } else if (isa<InlineAsm>(I.getOperand(i))) {
5902 Check(CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i),
5903 "Cannot take the address of an inline asm!", &I);
5904 } else if (auto *C = dyn_cast<Constant>(I.getOperand(i))) {
5905 visitConstantExprsRecursively(C);
5906 }
5907 }
5908
5909 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
5911 "fpmath requires a floating point result!", &I);
5912 Check(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
5913 if (ConstantFP *CFP0 =
5915 const APFloat &Accuracy = CFP0->getValueAPF();
5916 Check(&Accuracy.getSemantics() == &APFloat::IEEEsingle(),
5917 "fpmath accuracy must have float type", &I);
5918 Check(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
5919 "fpmath accuracy not a positive number!", &I);
5920 } else {
5921 Check(false, "invalid fpmath accuracy!", &I);
5922 }
5923 }
5924
5925 if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
5927 "Ranges are only for loads, calls and invokes!", &I);
5928 visitRangeMetadata(I, Range, I.getType());
5929 }
5930
5931 if (MDNode *MD = I.getMetadata(LLVMContext::MD_nofpclass)) {
5932 Check(isa<LoadInst>(I), "nofpclass is only for loads", &I);
5933 visitNoFPClassMetadata(I, MD, I.getType());
5934 }
5935
5936 if (MDNode *Range = I.getMetadata(LLVMContext::MD_noalias_addrspace)) {
5939 "noalias.addrspace are only for memory operations!", &I);
5940 visitNoaliasAddrspaceMetadata(I, Range, I.getType());
5941 }
5942
5943 if (I.hasMetadata(LLVMContext::MD_invariant_group)) {
5945 "invariant.group metadata is only for loads and stores", &I);
5946 }
5947
5948 if (MDNode *MD = I.getMetadata(LLVMContext::MD_nonnull)) {
5949 Check(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
5950 &I);
5952 "nonnull applies only to load instructions, use attributes"
5953 " for calls or invokes",
5954 &I);
5955 Check(MD->getNumOperands() == 0, "nonnull metadata must be empty", &I);
5956 }
5957
5958 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable))
5959 visitDereferenceableMetadata(I, MD);
5960
5961 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
5962 visitDereferenceableMetadata(I, MD);
5963
5964 if (MDNode *MD = I.getMetadata(LLVMContext::MD_nofree))
5965 visitNofreeMetadata(I, MD);
5966
5967 if (MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa))
5968 TBAAVerifyHelper.visitTBAAMetadata(&I, TBAA);
5969
5970 if (MDNode *MD = I.getMetadata(LLVMContext::MD_noalias))
5971 visitAliasScopeListMetadata(MD);
5972 if (MDNode *MD = I.getMetadata(LLVMContext::MD_alias_scope))
5973 visitAliasScopeListMetadata(MD);
5974
5975 if (MDNode *MD = I.getMetadata(LLVMContext::MD_access_group))
5976 visitAccessGroupMetadata(MD);
5977
5978 if (MDNode *AlignMD = I.getMetadata(LLVMContext::MD_align)) {
5979 Check(I.getType()->isPointerTy(), "align applies only to pointer types",
5980 &I);
5982 "align applies only to load instructions, "
5983 "use attributes for calls or invokes",
5984 &I);
5985 Check(AlignMD->getNumOperands() == 1, "align takes one operand!", &I);
5986 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0));
5987 Check(CI && CI->getType()->isIntegerTy(64),
5988 "align metadata value must be an i64!", &I);
5989 uint64_t Align = CI->getZExtValue();
5990 Check(isPowerOf2_64(Align), "align metadata value must be a power of 2!",
5991 &I);
5992 Check(Align <= Value::MaximumAlignment,
5993 "alignment is larger that implementation defined limit", &I);
5994 }
5995
5996 if (MDNode *MD = I.getMetadata(LLVMContext::MD_prof))
5997 visitProfMetadata(I, MD);
5998
5999 if (MDNode *MD = I.getMetadata(LLVMContext::MD_memprof))
6000 visitMemProfMetadata(I, MD);
6001
6002 if (MDNode *MD = I.getMetadata(LLVMContext::MD_callsite))
6003 visitCallsiteMetadata(I, MD);
6004
6005 if (MDNode *MD = I.getMetadata(LLVMContext::MD_callee_type))
6006 visitCalleeTypeMetadata(I, MD);
6007
6008 if (MDNode *MD = I.getMetadata(LLVMContext::MD_DIAssignID))
6009 visitDIAssignIDMetadata(I, MD);
6010
6011 if (MDNode *MMRA = I.getMetadata(LLVMContext::MD_mmra))
6012 visitMMRAMetadata(I, MMRA);
6013
6014 if (MDNode *Annotation = I.getMetadata(LLVMContext::MD_annotation))
6015 visitAnnotationMetadata(Annotation);
6016
6017 if (MDNode *Captures = I.getMetadata(LLVMContext::MD_captures))
6018 visitCapturesMetadata(I, Captures);
6019
6020 if (MDNode *MD = I.getMetadata(LLVMContext::MD_alloc_token))
6021 visitAllocTokenMetadata(I, MD);
6022
6023 if (MDNode *MD = I.getMetadata(LLVMContext::MD_inline_history))
6024 visitInlineHistoryMetadata(I, MD);
6025
6026 if (MDNode *MD = I.getMetadata(LLVMContext::MD_mem_cache_hint))
6027 visitMemCacheHintMetadata(I, MD);
6028
6029 if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
6030 CheckDI(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N);
6031 visitMDNode(*N, AreDebugLocsAllowed::Yes);
6032
6033 if (auto *DL = dyn_cast<DILocation>(N)) {
6034 if (DL->getAtomGroup()) {
6035 CheckDI(DL->getScope()->getSubprogram()->getKeyInstructionsEnabled(),
6036 "DbgLoc uses atomGroup but DISubprogram doesn't have Key "
6037 "Instructions enabled",
6038 DL, DL->getScope()->getSubprogram());
6039 }
6040 }
6041 }
6042
6044 I.getAllMetadata(MDs);
6045 for (auto Attachment : MDs) {
6046 unsigned Kind = Attachment.first;
6047 auto AllowLocs =
6048 (Kind == LLVMContext::MD_dbg || Kind == LLVMContext::MD_loop)
6049 ? AreDebugLocsAllowed::Yes
6050 : AreDebugLocsAllowed::No;
6051 visitMDNode(*Attachment.second, AllowLocs);
6052 }
6053
6054 InstsInThisBlock.insert(&I);
6055}
6056
6057/// Allow intrinsics to be verified in different ways.
6058void Verifier::visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call) {
6060 Check(IF->isDeclaration(), "Intrinsic functions should never be defined!",
6061 IF);
6062
6063 // Verify that the intrinsic prototype lines up with what the .td files
6064 // describe.
6065 FunctionType *IFTy = IF->getFunctionType();
6066
6067 // Walk the descriptors to extract overloaded types.
6068 std::string ErrMsg;
6069 raw_string_ostream ErrOS(ErrMsg);
6070 SmallVector<Type *, 4> OverloadTys;
6071 bool IsValid = Intrinsic::isSignatureValid(ID, IFTy, OverloadTys, ErrOS);
6072 Check(IsValid, ErrMsg, IF);
6073
6074 // Now that we have the intrinsic ID and the actual argument types (and we
6075 // know they are legal for the intrinsic!) get the intrinsic name through the
6076 // usual means. This allows us to verify the mangling of argument types into
6077 // the name.
6078 const std::string ExpectedName =
6079 Intrinsic::getName(ID, OverloadTys, IF->getParent(), IFTy);
6080 Check(ExpectedName == IF->getName(),
6081 "Intrinsic name not mangled correctly for type arguments! "
6082 "Should be: " +
6083 ExpectedName,
6084 IF);
6085
6086 // If the intrinsic takes MDNode arguments, verify that they are either global
6087 // or are local to *this* function.
6088 for (Value *V : Call.args()) {
6089 if (auto *MD = dyn_cast<MetadataAsValue>(V))
6090 visitMetadataAsValue(*MD, Call.getCaller());
6091 if (auto *Const = dyn_cast<Constant>(V))
6092 Check(!Const->getType()->isX86_AMXTy(),
6093 "const x86_amx is not allowed in argument!");
6094 }
6095
6096 switch (ID) {
6097 default:
6098 break;
6099 case Intrinsic::assume: {
6100 if (Call.hasOperandBundles()) {
6102 Check(Cond && Cond->isOne(),
6103 "assume with operand bundles must have i1 true condition", Call);
6104 }
6105 for (auto &Elem : Call.bundle_op_infos()) {
6106 unsigned ArgCount = Elem.End - Elem.Begin;
6107 // Separate storage assumptions are special insofar as they're the only
6108 // operand bundles allowed on assumes that aren't parameter attributes.
6109 if (Elem.Tag->getKey() == "separate_storage") {
6110 Check(ArgCount == 2,
6111 "separate_storage assumptions should have 2 arguments", Call);
6112 Check(Call.getOperand(Elem.Begin)->getType()->isPointerTy() &&
6113 Call.getOperand(Elem.Begin + 1)->getType()->isPointerTy(),
6114 "arguments to separate_storage assumptions should be pointers",
6115 Call);
6116 continue;
6117 }
6118 Check(Elem.Tag->getKey() == "ignore" ||
6119 Attribute::isExistingAttribute(Elem.Tag->getKey()),
6120 "tags must be valid attribute names", Call);
6121 Attribute::AttrKind Kind =
6122 Attribute::getAttrKindFromName(Elem.Tag->getKey());
6123 if (Kind == Attribute::Alignment) {
6124 Check(ArgCount <= 3 && ArgCount >= 2,
6125 "alignment assumptions should have 2 or 3 arguments", Call);
6126 Check(Call.getOperand(Elem.Begin)->getType()->isPointerTy(),
6127 "first argument should be a pointer", Call);
6128 Check(Call.getOperand(Elem.Begin + 1)->getType()->isIntegerTy(),
6129 "second argument should be an integer", Call);
6130 if (ArgCount == 3)
6131 Check(Call.getOperand(Elem.Begin + 2)->getType()->isIntegerTy(),
6132 "third argument should be an integer if present", Call);
6133 continue;
6134 }
6135 if (Kind == Attribute::Dereferenceable) {
6136 Check(ArgCount == 2,
6137 "dereferenceable assumptions should have 2 arguments", Call);
6138 Check(Call.getOperand(Elem.Begin)->getType()->isPointerTy(),
6139 "first argument should be a pointer", Call);
6140 Check(Call.getOperand(Elem.Begin + 1)->getType()->isIntegerTy(),
6141 "second argument should be an integer", Call);
6142 continue;
6143 }
6144 Check(ArgCount <= 2, "too many arguments", Call);
6145 if (Kind == Attribute::None)
6146 break;
6147 if (Attribute::isIntAttrKind(Kind)) {
6148 Check(ArgCount == 2, "this attribute should have 2 arguments", Call);
6149 Check(isa<ConstantInt>(Call.getOperand(Elem.Begin + 1)),
6150 "the second argument should be a constant integral value", Call);
6151 } else if (Attribute::canUseAsParamAttr(Kind)) {
6152 Check((ArgCount) == 1, "this attribute should have one argument", Call);
6153 } else if (Attribute::canUseAsFnAttr(Kind)) {
6154 Check((ArgCount) == 0, "this attribute has no argument", Call);
6155 }
6156 }
6157 break;
6158 }
6159 case Intrinsic::ucmp:
6160 case Intrinsic::scmp: {
6161 Type *SrcTy = Call.getOperand(0)->getType();
6162 Type *DestTy = Call.getType();
6163
6164 Check(DestTy->getScalarSizeInBits() >= 2,
6165 "result type must be at least 2 bits wide", Call);
6166
6167 bool IsDestTypeVector = DestTy->isVectorTy();
6168 Check(SrcTy->isVectorTy() == IsDestTypeVector,
6169 "ucmp/scmp argument and result types must both be either vector or "
6170 "scalar types",
6171 Call);
6172 if (IsDestTypeVector) {
6173 auto SrcVecLen = cast<VectorType>(SrcTy)->getElementCount();
6174 auto DestVecLen = cast<VectorType>(DestTy)->getElementCount();
6175 Check(SrcVecLen == DestVecLen,
6176 "return type and arguments must have the same number of "
6177 "elements",
6178 Call);
6179 }
6180 break;
6181 }
6182 case Intrinsic::coro_begin:
6183 case Intrinsic::coro_begin_custom_abi:
6185 "id argument of llvm.coro.begin must refer to coro.id");
6186 break;
6187 case Intrinsic::coro_id: {
6189 "align argument only accepts constants");
6190 auto *Promise = Call.getArgOperand(1);
6191 Check(isa<ConstantPointerNull>(Promise) || isa<AllocaInst>(Promise),
6192 "promise argument must refer to an alloca");
6193
6194 auto *CoroAddr = Call.getArgOperand(2)->stripPointerCasts();
6195 bool BeforeCoroEarly = isa<ConstantPointerNull>(CoroAddr);
6196 Check(BeforeCoroEarly || isa<Function>(CoroAddr),
6197 "coro argument must refer to a function");
6198
6199 auto *InfoArg = Call.getArgOperand(3);
6200 bool BeforeCoroSplit = isa<ConstantPointerNull>(InfoArg);
6201 if (BeforeCoroSplit)
6202 break;
6203
6204 Check(!BeforeCoroEarly, "cannot run CoroSplit before CoroEarly");
6205 auto *GV = dyn_cast<GlobalVariable>(InfoArg);
6206 Check(GV && GV->isConstant() && GV->hasDefinitiveInitializer(),
6207 "info argument of llvm.coro.id must refer to an initialized "
6208 "constant");
6209 Constant *Init = GV->getInitializer();
6211 "info argument of llvm.coro.id must refer to either a struct or "
6212 "an array");
6213 break;
6214 }
6215 case Intrinsic::is_fpclass: {
6216 const ConstantInt *TestMask = cast<ConstantInt>(Call.getOperand(1));
6217 Check((TestMask->getZExtValue() & ~static_cast<unsigned>(fcAllFlags)) == 0,
6218 "unsupported bits for llvm.is.fpclass test mask");
6219 break;
6220 }
6221 case Intrinsic::fptrunc_round: {
6222 // Check the rounding mode
6223 Metadata *MD = nullptr;
6225 if (MAV)
6226 MD = MAV->getMetadata();
6227
6228 Check(MD != nullptr, "missing rounding mode argument", Call);
6229
6230 Check(isa<MDString>(MD),
6231 ("invalid value for llvm.fptrunc.round metadata operand"
6232 " (the operand should be a string)"),
6233 MD);
6234
6235 std::optional<RoundingMode> RoundMode =
6236 convertStrToRoundingMode(cast<MDString>(MD)->getString());
6237 Check(RoundMode && *RoundMode != RoundingMode::Dynamic,
6238 "unsupported rounding mode argument", Call);
6239 break;
6240 }
6241 case Intrinsic::convert_to_arbitrary_fp: {
6242 // Check that vector element counts are consistent.
6243 Type *ValueTy = Call.getArgOperand(0)->getType();
6244 Type *IntTy = Call.getType();
6245
6246 if (auto *ValueVecTy = dyn_cast<VectorType>(ValueTy)) {
6247 auto *IntVecTy = dyn_cast<VectorType>(IntTy);
6248 Check(IntVecTy,
6249 "if floating-point operand is a vector, integer operand must also "
6250 "be a vector",
6251 Call);
6252 Check(ValueVecTy->getElementCount() == IntVecTy->getElementCount(),
6253 "floating-point and integer vector operands must have the same "
6254 "element count",
6255 Call);
6256 }
6257
6258 // Check interpretation metadata (argoperand 1).
6259 auto *InterpMAV = dyn_cast<MetadataAsValue>(Call.getArgOperand(1));
6260 Check(InterpMAV, "missing interpretation metadata operand", Call);
6261 auto *InterpStr = dyn_cast<MDString>(InterpMAV->getMetadata());
6262 Check(InterpStr, "interpretation metadata operand must be a string", Call);
6263 StringRef Interp = InterpStr->getString();
6264
6265 Check(!Interp.empty(), "interpretation metadata string must not be empty",
6266 Call);
6267
6268 // Valid interpretation strings: mini-float format names.
6270 "unsupported interpretation metadata string", Call);
6271
6272 // Check rounding mode metadata (argoperand 2).
6273 auto *RoundingMAV = dyn_cast<MetadataAsValue>(Call.getArgOperand(2));
6274 Check(RoundingMAV, "missing rounding mode metadata operand", Call);
6275 auto *RoundingStr = dyn_cast<MDString>(RoundingMAV->getMetadata());
6276 Check(RoundingStr, "rounding mode metadata operand must be a string", Call);
6277
6278 std::optional<RoundingMode> RM =
6279 convertStrToRoundingMode(RoundingStr->getString());
6280 Check(RM && *RM != RoundingMode::Dynamic,
6281 "unsupported rounding mode argument", Call);
6282 break;
6283 }
6284 case Intrinsic::convert_from_arbitrary_fp: {
6285 // Check that vector element counts are consistent.
6286 Type *IntTy = Call.getArgOperand(0)->getType();
6287 Type *ValueTy = Call.getType();
6288
6289 if (auto *ValueVecTy = dyn_cast<VectorType>(ValueTy)) {
6290 auto *IntVecTy = dyn_cast<VectorType>(IntTy);
6291 Check(IntVecTy,
6292 "if floating-point operand is a vector, integer operand must also "
6293 "be a vector",
6294 Call);
6295 Check(ValueVecTy->getElementCount() == IntVecTy->getElementCount(),
6296 "floating-point and integer vector operands must have the same "
6297 "element count",
6298 Call);
6299 }
6300
6301 // Check interpretation metadata (argoperand 1).
6302 auto *InterpMAV = dyn_cast<MetadataAsValue>(Call.getArgOperand(1));
6303 Check(InterpMAV, "missing interpretation metadata operand", Call);
6304 auto *InterpStr = dyn_cast<MDString>(InterpMAV->getMetadata());
6305 Check(InterpStr, "interpretation metadata operand must be a string", Call);
6306 StringRef Interp = InterpStr->getString();
6307
6308 Check(!Interp.empty(), "interpretation metadata string must not be empty",
6309 Call);
6310
6311 // Valid interpretation strings: mini-float format names.
6313 "unsupported interpretation metadata string", Call);
6314 break;
6315 }
6316#define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6317#include "llvm/IR/VPIntrinsics.def"
6318#undef BEGIN_REGISTER_VP_INTRINSIC
6319 visitVPIntrinsic(cast<VPIntrinsic>(Call));
6320 break;
6321#define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC) \
6322 case Intrinsic::INTRINSIC:
6323#include "llvm/IR/ConstrainedOps.def"
6324#undef INSTRUCTION
6325 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(Call));
6326 break;
6327 case Intrinsic::dbg_declare: // llvm.dbg.declare
6328 case Intrinsic::dbg_value: // llvm.dbg.value
6329 case Intrinsic::dbg_assign: // llvm.dbg.assign
6330 case Intrinsic::dbg_label: // llvm.dbg.label
6331 // We no longer interpret debug intrinsics (the old variable-location
6332 // design). They're meaningless as far as LLVM is concerned we could make
6333 // it an error for them to appear, but it's possible we'll have users
6334 // converting back to intrinsics for the forseeable future (such as DXIL),
6335 // so tolerate their existance.
6336 break;
6337 case Intrinsic::memcpy:
6338 case Intrinsic::memcpy_inline:
6339 case Intrinsic::memmove:
6340 case Intrinsic::memset:
6341 case Intrinsic::memset_inline:
6342 break;
6343 case Intrinsic::experimental_memset_pattern: {
6344 const auto Memset = cast<MemSetPatternInst>(&Call);
6345 Check(Memset->getValue()->getType()->isSized(),
6346 "unsized types cannot be used as memset patterns", Call);
6347 break;
6348 }
6349 case Intrinsic::memcpy_element_unordered_atomic:
6350 case Intrinsic::memmove_element_unordered_atomic:
6351 case Intrinsic::memset_element_unordered_atomic: {
6352 const auto *AMI = cast<AnyMemIntrinsic>(&Call);
6353
6354 ConstantInt *ElementSizeCI =
6355 cast<ConstantInt>(AMI->getRawElementSizeInBytes());
6356 const APInt &ElementSizeVal = ElementSizeCI->getValue();
6357 Check(ElementSizeVal.isPowerOf2(),
6358 "element size of the element-wise atomic memory intrinsic "
6359 "must be a power of 2",
6360 Call);
6361
6362 auto IsValidAlignment = [&](MaybeAlign Alignment) {
6363 return Alignment && ElementSizeVal.ule(Alignment->value());
6364 };
6365 Check(IsValidAlignment(AMI->getDestAlign()),
6366 "incorrect alignment of the destination argument", Call);
6367 if (const auto *AMT = dyn_cast<AnyMemTransferInst>(AMI)) {
6368 Check(IsValidAlignment(AMT->getSourceAlign()),
6369 "incorrect alignment of the source argument", Call);
6370 }
6371 break;
6372 }
6373 case Intrinsic::call_preallocated_setup: {
6374 auto *NumArgs = cast<ConstantInt>(Call.getArgOperand(0));
6375 bool FoundCall = false;
6376 for (User *U : Call.users()) {
6377 auto *UseCall = dyn_cast<CallBase>(U);
6378 Check(UseCall != nullptr,
6379 "Uses of llvm.call.preallocated.setup must be calls");
6380 Intrinsic::ID IID = UseCall->getIntrinsicID();
6381 if (IID == Intrinsic::call_preallocated_arg) {
6382 auto *AllocArgIndex = dyn_cast<ConstantInt>(UseCall->getArgOperand(1));
6383 Check(AllocArgIndex != nullptr,
6384 "llvm.call.preallocated.alloc arg index must be a constant");
6385 auto AllocArgIndexInt = AllocArgIndex->getValue();
6386 Check(AllocArgIndexInt.sge(0) &&
6387 AllocArgIndexInt.slt(NumArgs->getValue()),
6388 "llvm.call.preallocated.alloc arg index must be between 0 and "
6389 "corresponding "
6390 "llvm.call.preallocated.setup's argument count");
6391 } else if (IID == Intrinsic::call_preallocated_teardown) {
6392 // nothing to do
6393 } else {
6394 Check(!FoundCall, "Can have at most one call corresponding to a "
6395 "llvm.call.preallocated.setup");
6396 FoundCall = true;
6397 size_t NumPreallocatedArgs = 0;
6398 for (unsigned i = 0; i < UseCall->arg_size(); i++) {
6399 if (UseCall->paramHasAttr(i, Attribute::Preallocated)) {
6400 ++NumPreallocatedArgs;
6401 }
6402 }
6403 Check(NumPreallocatedArgs != 0,
6404 "cannot use preallocated intrinsics on a call without "
6405 "preallocated arguments");
6406 Check(NumArgs->equalsInt(NumPreallocatedArgs),
6407 "llvm.call.preallocated.setup arg size must be equal to number "
6408 "of preallocated arguments "
6409 "at call site",
6410 Call, *UseCall);
6411 // getOperandBundle() cannot be called if more than one of the operand
6412 // bundle exists. There is already a check elsewhere for this, so skip
6413 // here if we see more than one.
6414 if (UseCall->countOperandBundlesOfType(LLVMContext::OB_preallocated) >
6415 1) {
6416 return;
6417 }
6418 auto PreallocatedBundle =
6419 UseCall->getOperandBundle(LLVMContext::OB_preallocated);
6420 Check(PreallocatedBundle,
6421 "Use of llvm.call.preallocated.setup outside intrinsics "
6422 "must be in \"preallocated\" operand bundle");
6423 Check(PreallocatedBundle->Inputs.front().get() == &Call,
6424 "preallocated bundle must have token from corresponding "
6425 "llvm.call.preallocated.setup");
6426 }
6427 }
6428 break;
6429 }
6430 case Intrinsic::call_preallocated_arg: {
6431 auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0));
6432 Check(Token &&
6433 Token->getIntrinsicID() == Intrinsic::call_preallocated_setup,
6434 "llvm.call.preallocated.arg token argument must be a "
6435 "llvm.call.preallocated.setup");
6436 Check(Call.hasFnAttr(Attribute::Preallocated),
6437 "llvm.call.preallocated.arg must be called with a \"preallocated\" "
6438 "call site attribute");
6439 break;
6440 }
6441 case Intrinsic::call_preallocated_teardown: {
6442 auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0));
6443 Check(Token &&
6444 Token->getIntrinsicID() == Intrinsic::call_preallocated_setup,
6445 "llvm.call.preallocated.teardown token argument must be a "
6446 "llvm.call.preallocated.setup");
6447 break;
6448 }
6449 case Intrinsic::gcroot:
6450 case Intrinsic::gcwrite:
6451 case Intrinsic::gcread:
6452 if (ID == Intrinsic::gcroot) {
6453 AllocaInst *AI =
6455 Check(AI, "llvm.gcroot parameter #1 must be an alloca.", Call);
6457 "llvm.gcroot parameter #2 must be a constant.", Call);
6458 if (!AI->getAllocatedType()->isPointerTy()) {
6460 "llvm.gcroot parameter #1 must either be a pointer alloca, "
6461 "or argument #2 must be a non-null constant.",
6462 Call);
6463 }
6464 }
6465
6466 Check(Call.getParent()->getParent()->hasGC(),
6467 "Enclosing function does not use GC.", Call);
6468 break;
6469 case Intrinsic::init_trampoline:
6471 "llvm.init_trampoline parameter #2 must resolve to a function.",
6472 Call);
6473 break;
6474 case Intrinsic::prefetch:
6475 Check(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2,
6476 "rw argument to llvm.prefetch must be 0-1", Call);
6477 Check(cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 4,
6478 "locality argument to llvm.prefetch must be 0-3", Call);
6479 Check(cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue() < 2,
6480 "cache type argument to llvm.prefetch must be 0-1", Call);
6481 break;
6482 case Intrinsic::reloc_none: {
6484 cast<MetadataAsValue>(Call.getArgOperand(0))->getMetadata()),
6485 "llvm.reloc.none argument must be a metadata string", &Call);
6486 break;
6487 }
6488 case Intrinsic::stackprotector:
6490 "llvm.stackprotector parameter #2 must resolve to an alloca.", Call);
6491 break;
6492 case Intrinsic::localescape: {
6493 BasicBlock *BB = Call.getParent();
6494 Check(BB->isEntryBlock(), "llvm.localescape used outside of entry block",
6495 Call);
6496 Check(!SawFrameEscape, "multiple calls to llvm.localescape in one function",
6497 Call);
6498 for (Value *Arg : Call.args()) {
6499 if (isa<ConstantPointerNull>(Arg))
6500 continue; // Null values are allowed as placeholders.
6501 auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
6502 Check(AI && AI->isStaticAlloca(),
6503 "llvm.localescape only accepts static allocas", Call);
6504 }
6505 FrameEscapeInfo[BB->getParent()].first = Call.arg_size();
6506 SawFrameEscape = true;
6507 break;
6508 }
6509 case Intrinsic::localrecover: {
6511 Function *Fn = dyn_cast<Function>(FnArg);
6512 Check(Fn && !Fn->isDeclaration(),
6513 "llvm.localrecover first "
6514 "argument must be function defined in this module",
6515 Call);
6516 auto *IdxArg = cast<ConstantInt>(Call.getArgOperand(2));
6517 auto &Entry = FrameEscapeInfo[Fn];
6518 Entry.second = unsigned(
6519 std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
6520 break;
6521 }
6522
6523 case Intrinsic::experimental_gc_statepoint:
6524 if (auto *CI = dyn_cast<CallInst>(&Call))
6525 Check(!CI->isInlineAsm(),
6526 "gc.statepoint support for inline assembly unimplemented", CI);
6527 Check(Call.getParent()->getParent()->hasGC(),
6528 "Enclosing function does not use GC.", Call);
6529
6530 verifyStatepoint(Call);
6531 break;
6532 case Intrinsic::experimental_gc_result: {
6533 Check(Call.getParent()->getParent()->hasGC(),
6534 "Enclosing function does not use GC.", Call);
6535
6536 auto *Statepoint = Call.getArgOperand(0);
6537 if (isa<UndefValue>(Statepoint))
6538 break;
6539
6540 // Are we tied to a statepoint properly?
6541 const auto *StatepointCall = dyn_cast<CallBase>(Statepoint);
6542 Check(StatepointCall && StatepointCall->getIntrinsicID() ==
6543 Intrinsic::experimental_gc_statepoint,
6544 "gc.result operand #1 must be from a statepoint", Call,
6545 Call.getArgOperand(0));
6546
6547 // Check that result type matches wrapped callee.
6548 auto *TargetFuncType =
6549 cast<FunctionType>(StatepointCall->getParamElementType(2));
6550 Check(Call.getType() == TargetFuncType->getReturnType(),
6551 "gc.result result type does not match wrapped callee", Call);
6552 break;
6553 }
6554 case Intrinsic::experimental_gc_relocate: {
6555 Check(Call.arg_size() == 3, "wrong number of arguments", Call);
6556
6558 "gc.relocate must return a pointer or a vector of pointers", Call);
6559
6560 // Check that this relocate is correctly tied to the statepoint
6561
6562 // This is case for relocate on the unwinding path of an invoke statepoint
6563 if (LandingPadInst *LandingPad =
6565
6566 const BasicBlock *InvokeBB =
6567 LandingPad->getParent()->getUniquePredecessor();
6568
6569 // Landingpad relocates should have only one predecessor with invoke
6570 // statepoint terminator
6571 Check(InvokeBB, "safepoints should have unique landingpads",
6572 LandingPad->getParent());
6573 Check(InvokeBB->getTerminator(), "safepoint block should be well formed",
6574 InvokeBB);
6576 "gc relocate should be linked to a statepoint", InvokeBB);
6577 } else {
6578 // In all other cases relocate should be tied to the statepoint directly.
6579 // This covers relocates on a normal return path of invoke statepoint and
6580 // relocates of a call statepoint.
6581 auto *Token = Call.getArgOperand(0);
6583 "gc relocate is incorrectly tied to the statepoint", Call, Token);
6584 }
6585
6586 // Verify rest of the relocate arguments.
6587 const Value &StatepointCall = *cast<GCRelocateInst>(Call).getStatepoint();
6588
6589 // Both the base and derived must be piped through the safepoint.
6592 "gc.relocate operand #2 must be integer offset", Call);
6593
6594 Value *Derived = Call.getArgOperand(2);
6595 Check(isa<ConstantInt>(Derived),
6596 "gc.relocate operand #3 must be integer offset", Call);
6597
6598 const uint64_t BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
6599 const uint64_t DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
6600
6601 // Check the bounds
6602 if (isa<UndefValue>(StatepointCall))
6603 break;
6604 if (auto Opt = cast<GCStatepointInst>(StatepointCall)
6605 .getOperandBundle(LLVMContext::OB_gc_live)) {
6606 Check(BaseIndex < Opt->Inputs.size(),
6607 "gc.relocate: statepoint base index out of bounds", Call);
6608 Check(DerivedIndex < Opt->Inputs.size(),
6609 "gc.relocate: statepoint derived index out of bounds", Call);
6610 }
6611
6612 // Relocated value must be either a pointer type or vector-of-pointer type,
6613 // but gc_relocate does not need to return the same pointer type as the
6614 // relocated pointer. It can be casted to the correct type later if it's
6615 // desired. However, they must have the same address space and 'vectorness'
6616 GCRelocateInst &Relocate = cast<GCRelocateInst>(Call);
6617 auto *ResultType = Call.getType();
6618 auto *DerivedType = Relocate.getDerivedPtr()->getType();
6619 auto *BaseType = Relocate.getBasePtr()->getType();
6620
6621 Check(BaseType->isPtrOrPtrVectorTy(),
6622 "gc.relocate: relocated value must be a pointer", Call);
6623 Check(DerivedType->isPtrOrPtrVectorTy(),
6624 "gc.relocate: relocated value must be a pointer", Call);
6625
6626 Check(ResultType->isVectorTy() == DerivedType->isVectorTy(),
6627 "gc.relocate: vector relocates to vector and pointer to pointer",
6628 Call);
6629 Check(
6630 ResultType->getPointerAddressSpace() ==
6631 DerivedType->getPointerAddressSpace(),
6632 "gc.relocate: relocating a pointer shouldn't change its address space",
6633 Call);
6634
6635 auto GC = llvm::getGCStrategy(Relocate.getFunction()->getGC());
6636 Check(GC, "gc.relocate: calling function must have GCStrategy",
6637 Call.getFunction());
6638 if (GC) {
6639 auto isGCPtr = [&GC](Type *PTy) {
6640 return GC->isGCManagedPointer(PTy->getScalarType()).value_or(true);
6641 };
6642 Check(isGCPtr(ResultType), "gc.relocate: must return gc pointer", Call);
6643 Check(isGCPtr(BaseType),
6644 "gc.relocate: relocated value must be a gc pointer", Call);
6645 Check(isGCPtr(DerivedType),
6646 "gc.relocate: relocated value must be a gc pointer", Call);
6647 }
6648 break;
6649 }
6650 case Intrinsic::experimental_patchpoint: {
6651 if (Call.getCallingConv() == CallingConv::AnyReg) {
6653 "patchpoint: invalid return type used with anyregcc", Call);
6654 }
6655 break;
6656 }
6657 case Intrinsic::eh_exceptioncode:
6658 case Intrinsic::eh_exceptionpointer: {
6660 "eh.exceptionpointer argument must be a catchpad", Call);
6661 break;
6662 }
6663 case Intrinsic::get_active_lane_mask: {
6665 "get_active_lane_mask: must return a "
6666 "vector",
6667 Call);
6668 auto *ElemTy = Call.getType()->getScalarType();
6669 Check(ElemTy->isIntegerTy(1),
6670 "get_active_lane_mask: element type is not "
6671 "i1",
6672 Call);
6673 break;
6674 }
6675 case Intrinsic::experimental_get_vector_length: {
6676 ConstantInt *VF = cast<ConstantInt>(Call.getArgOperand(1));
6677 Check(!VF->isNegative() && !VF->isZero(),
6678 "get_vector_length: VF must be positive", Call);
6679 break;
6680 }
6681 case Intrinsic::masked_load: {
6682 Check(Call.getType()->isVectorTy(), "masked_load: must return a vector",
6683 Call);
6684
6686 Value *PassThru = Call.getArgOperand(2);
6687 Check(Mask->getType()->isVectorTy(), "masked_load: mask must be vector",
6688 Call);
6689 Check(PassThru->getType() == Call.getType(),
6690 "masked_load: pass through and return type must match", Call);
6691 Check(cast<VectorType>(Mask->getType())->getElementCount() ==
6692 cast<VectorType>(Call.getType())->getElementCount(),
6693 "masked_load: vector mask must be same length as return", Call);
6694 break;
6695 }
6696 case Intrinsic::masked_store: {
6697 Value *Val = Call.getArgOperand(0);
6699 Check(Mask->getType()->isVectorTy(), "masked_store: mask must be vector",
6700 Call);
6701 Check(cast<VectorType>(Mask->getType())->getElementCount() ==
6702 cast<VectorType>(Val->getType())->getElementCount(),
6703 "masked_store: vector mask must be same length as value", Call);
6704 break;
6705 }
6706 case Intrinsic::experimental_guard: {
6707 Check(isa<CallInst>(Call), "experimental_guard cannot be invoked", Call);
6709 "experimental_guard must have exactly one "
6710 "\"deopt\" operand bundle");
6711 break;
6712 }
6713
6714 case Intrinsic::experimental_deoptimize: {
6715 Check(isa<CallInst>(Call), "experimental_deoptimize cannot be invoked",
6716 Call);
6718 "experimental_deoptimize must have exactly one "
6719 "\"deopt\" operand bundle");
6721 "experimental_deoptimize return type must match caller return type");
6722
6723 if (isa<CallInst>(Call)) {
6725 Check(RI,
6726 "calls to experimental_deoptimize must be followed by a return");
6727
6728 if (!Call.getType()->isVoidTy() && RI)
6729 Check(RI->getReturnValue() == &Call,
6730 "calls to experimental_deoptimize must be followed by a return "
6731 "of the value computed by experimental_deoptimize");
6732 }
6733
6734 break;
6735 }
6736 case Intrinsic::vastart: {
6738 "va_start called in a non-varargs function");
6739 break;
6740 }
6741 case Intrinsic::get_dynamic_area_offset: {
6742 auto *IntTy = dyn_cast<IntegerType>(Call.getType());
6743 Check(IntTy && DL.getPointerSizeInBits(DL.getAllocaAddrSpace()) ==
6744 IntTy->getBitWidth(),
6745 "get_dynamic_area_offset result type must be scalar integer matching "
6746 "alloca address space width",
6747 Call);
6748 break;
6749 }
6750 case Intrinsic::masked_udiv:
6751 case Intrinsic::masked_sdiv:
6752 case Intrinsic::masked_urem:
6753 case Intrinsic::masked_srem:
6754 case Intrinsic::vector_reduce_and:
6755 case Intrinsic::vector_reduce_or:
6756 case Intrinsic::vector_reduce_xor:
6757 case Intrinsic::vector_reduce_add:
6758 case Intrinsic::vector_reduce_mul:
6759 case Intrinsic::vector_reduce_smax:
6760 case Intrinsic::vector_reduce_smin:
6761 case Intrinsic::vector_reduce_umax:
6762 case Intrinsic::vector_reduce_umin: {
6763 Type *ArgTy = Call.getArgOperand(0)->getType();
6764 Check(ArgTy->isIntOrIntVectorTy() && ArgTy->isVectorTy(),
6765 "intrinsic has incorrect argument type!");
6766 break;
6767 }
6768 case Intrinsic::vector_reduce_fmax:
6769 case Intrinsic::vector_reduce_fmin: {
6770 Type *ArgTy = Call.getArgOperand(0)->getType();
6771 Check(ArgTy->isFPOrFPVectorTy() && ArgTy->isVectorTy(),
6772 "intrinsic has incorrect argument type!");
6773 break;
6774 }
6775 case Intrinsic::vector_reduce_fadd:
6776 case Intrinsic::vector_reduce_fmul: {
6777 // Unlike the other reductions, the first argument is a start value. The
6778 // second argument is the vector to be reduced.
6779 Type *ArgTy = Call.getArgOperand(1)->getType();
6780 Check(ArgTy->isFPOrFPVectorTy() && ArgTy->isVectorTy(),
6781 "intrinsic has incorrect argument type!");
6782 break;
6783 }
6784 case Intrinsic::smul_fix:
6785 case Intrinsic::smul_fix_sat:
6786 case Intrinsic::umul_fix:
6787 case Intrinsic::umul_fix_sat:
6788 case Intrinsic::sdiv_fix:
6789 case Intrinsic::sdiv_fix_sat:
6790 case Intrinsic::udiv_fix:
6791 case Intrinsic::udiv_fix_sat: {
6792 Value *Op1 = Call.getArgOperand(0);
6793 auto *Op3 = cast<ConstantInt>(Call.getArgOperand(2));
6794
6795 if (ID == Intrinsic::smul_fix || ID == Intrinsic::smul_fix_sat ||
6796 ID == Intrinsic::sdiv_fix || ID == Intrinsic::sdiv_fix_sat) {
6797 Check(Op3->getZExtValue() < Op1->getType()->getScalarSizeInBits(),
6798 "the scale of s[mul|div]_fix[_sat] must be less than the width of "
6799 "the operands");
6800 } else {
6801 Check(Op3->getZExtValue() <= Op1->getType()->getScalarSizeInBits(),
6802 "the scale of u[mul|div]_fix[_sat] must be less than or equal "
6803 "to the width of the operands");
6804 }
6805 break;
6806 }
6807 case Intrinsic::lrint:
6808 case Intrinsic::llrint:
6809 case Intrinsic::lround:
6810 case Intrinsic::llround: {
6811 Type *ValTy = Call.getArgOperand(0)->getType();
6812 Type *ResultTy = Call.getType();
6813 Check(ValTy->isVectorTy() == ResultTy->isVectorTy(),
6814 ExpectedName + ": argument and result disagree on vector use", &Call);
6815 if (auto *VTy = dyn_cast<VectorType>(ValTy)) {
6816 auto *RTy = dyn_cast<VectorType>(ResultTy);
6817 Check(VTy->getElementCount() == RTy->getElementCount(),
6818 ExpectedName + ": argument must be same length as result", &Call);
6819 }
6820 break;
6821 }
6822 case Intrinsic::bswap: {
6823 Type *Ty = Call.getType();
6824 unsigned Size = Ty->getScalarSizeInBits();
6825 Check(Size % 16 == 0, "bswap must be an even number of bytes", &Call);
6826 break;
6827 }
6828 case Intrinsic::invariant_start: {
6829 ConstantInt *InvariantSize = dyn_cast<ConstantInt>(Call.getArgOperand(0));
6830 Check(InvariantSize &&
6831 (!InvariantSize->isNegative() || InvariantSize->isMinusOne()),
6832 "invariant_start parameter must be -1, 0 or a positive number",
6833 &Call);
6834 break;
6835 }
6836 case Intrinsic::matrix_multiply:
6837 case Intrinsic::matrix_transpose:
6838 case Intrinsic::matrix_column_major_load:
6839 case Intrinsic::matrix_column_major_store: {
6841 ConstantInt *Stride = nullptr;
6842 ConstantInt *NumRows;
6843 ConstantInt *NumColumns;
6844 VectorType *ResultTy;
6845 Type *Op0ElemTy = nullptr;
6846 Type *Op1ElemTy = nullptr;
6847 switch (ID) {
6848 case Intrinsic::matrix_multiply: {
6849 NumRows = cast<ConstantInt>(Call.getArgOperand(2));
6850 ConstantInt *N = cast<ConstantInt>(Call.getArgOperand(3));
6851 NumColumns = cast<ConstantInt>(Call.getArgOperand(4));
6853 ->getNumElements() ==
6854 NumRows->getZExtValue() * N->getZExtValue(),
6855 "First argument of a matrix operation does not match specified "
6856 "shape!");
6858 ->getNumElements() ==
6859 N->getZExtValue() * NumColumns->getZExtValue(),
6860 "Second argument of a matrix operation does not match specified "
6861 "shape!");
6862
6863 ResultTy = cast<VectorType>(Call.getType());
6864 Op0ElemTy =
6865 cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
6866 Op1ElemTy =
6867 cast<VectorType>(Call.getArgOperand(1)->getType())->getElementType();
6868 break;
6869 }
6870 case Intrinsic::matrix_transpose:
6871 NumRows = cast<ConstantInt>(Call.getArgOperand(1));
6872 NumColumns = cast<ConstantInt>(Call.getArgOperand(2));
6873 ResultTy = cast<VectorType>(Call.getType());
6874 Op0ElemTy =
6875 cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
6876 break;
6877 case Intrinsic::matrix_column_major_load: {
6879 NumRows = cast<ConstantInt>(Call.getArgOperand(3));
6880 NumColumns = cast<ConstantInt>(Call.getArgOperand(4));
6881 ResultTy = cast<VectorType>(Call.getType());
6882 break;
6883 }
6884 case Intrinsic::matrix_column_major_store: {
6886 NumRows = cast<ConstantInt>(Call.getArgOperand(4));
6887 NumColumns = cast<ConstantInt>(Call.getArgOperand(5));
6888 ResultTy = cast<VectorType>(Call.getArgOperand(0)->getType());
6889 Op0ElemTy =
6890 cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
6891 break;
6892 }
6893 default:
6894 llvm_unreachable("unexpected intrinsic");
6895 }
6896
6897 Check(ResultTy->getElementType()->isIntegerTy() ||
6898 ResultTy->getElementType()->isFloatingPointTy(),
6899 "Result type must be an integer or floating-point type!", IF);
6900
6901 if (Op0ElemTy)
6902 Check(ResultTy->getElementType() == Op0ElemTy,
6903 "Vector element type mismatch of the result and first operand "
6904 "vector!",
6905 IF);
6906
6907 if (Op1ElemTy)
6908 Check(ResultTy->getElementType() == Op1ElemTy,
6909 "Vector element type mismatch of the result and second operand "
6910 "vector!",
6911 IF);
6912
6914 NumRows->getZExtValue() * NumColumns->getZExtValue(),
6915 "Result of a matrix operation does not fit in the returned vector!");
6916
6917 if (Stride) {
6918 Check(Stride->getBitWidth() <= 64, "Stride bitwidth cannot exceed 64!",
6919 IF);
6920 Check(Stride->getZExtValue() >= NumRows->getZExtValue(),
6921 "Stride must be greater or equal than the number of rows!", IF);
6922 }
6923
6924 break;
6925 }
6926 case Intrinsic::stepvector: {
6928 Check(VecTy && VecTy->getScalarType()->isIntegerTy() &&
6929 VecTy->getScalarSizeInBits() >= 8,
6930 "stepvector only supported for vectors of integers "
6931 "with a bitwidth of at least 8.",
6932 &Call);
6933 break;
6934 }
6935 case Intrinsic::experimental_vector_match: {
6936 Value *Op1 = Call.getArgOperand(0);
6937 Value *Op2 = Call.getArgOperand(1);
6939
6940 VectorType *Op1Ty = dyn_cast<VectorType>(Op1->getType());
6941 VectorType *Op2Ty = dyn_cast<VectorType>(Op2->getType());
6942 VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
6943
6944 Check(Op1Ty && Op2Ty && MaskTy, "Operands must be vectors.", &Call);
6946 "Second operand must be a fixed length vector.", &Call);
6947 Check(Op1Ty->getElementType()->isIntegerTy(),
6948 "First operand must be a vector of integers.", &Call);
6949 Check(Op1Ty->getElementType() == Op2Ty->getElementType(),
6950 "First two operands must have the same element type.", &Call);
6951 Check(Op1Ty->getElementCount() == MaskTy->getElementCount(),
6952 "First operand and mask must have the same number of elements.",
6953 &Call);
6954 Check(MaskTy->getElementType()->isIntegerTy(1),
6955 "Mask must be a vector of i1's.", &Call);
6956 Check(Call.getType() == MaskTy, "Return type must match the mask type.",
6957 &Call);
6958 break;
6959 }
6960 case Intrinsic::vector_insert: {
6961 Value *Vec = Call.getArgOperand(0);
6962 Value *SubVec = Call.getArgOperand(1);
6963 Value *Idx = Call.getArgOperand(2);
6964 unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
6965
6966 VectorType *VecTy = cast<VectorType>(Vec->getType());
6967 VectorType *SubVecTy = cast<VectorType>(SubVec->getType());
6968
6969 ElementCount VecEC = VecTy->getElementCount();
6970 ElementCount SubVecEC = SubVecTy->getElementCount();
6971 Check(VecTy->getElementType() == SubVecTy->getElementType(),
6972 "vector_insert parameters must have the same element "
6973 "type.",
6974 &Call);
6975 Check(IdxN % SubVecEC.getKnownMinValue() == 0,
6976 "vector_insert index must be a constant multiple of "
6977 "the subvector's known minimum vector length.");
6978
6979 // If this insertion is not the 'mixed' case where a fixed vector is
6980 // inserted into a scalable vector, ensure that the insertion of the
6981 // subvector does not overrun the parent vector.
6982 if (VecEC.isScalable() == SubVecEC.isScalable()) {
6983 Check(IdxN < VecEC.getKnownMinValue() &&
6984 IdxN + SubVecEC.getKnownMinValue() <= VecEC.getKnownMinValue(),
6985 "subvector operand of vector_insert would overrun the "
6986 "vector being inserted into.");
6987 }
6988 break;
6989 }
6990 case Intrinsic::vector_extract: {
6991 Value *Vec = Call.getArgOperand(0);
6992 Value *Idx = Call.getArgOperand(1);
6993 unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
6994
6995 VectorType *ResultTy = cast<VectorType>(Call.getType());
6996 VectorType *VecTy = cast<VectorType>(Vec->getType());
6997
6998 ElementCount VecEC = VecTy->getElementCount();
6999 ElementCount ResultEC = ResultTy->getElementCount();
7000
7001 Check(ResultTy->getElementType() == VecTy->getElementType(),
7002 "vector_extract result must have the same element "
7003 "type as the input vector.",
7004 &Call);
7005 Check(IdxN % ResultEC.getKnownMinValue() == 0,
7006 "vector_extract index must be a constant multiple of "
7007 "the result type's known minimum vector length.");
7008
7009 // If this extraction is not the 'mixed' case where a fixed vector is
7010 // extracted from a scalable vector, ensure that the extraction does not
7011 // overrun the parent vector.
7012 if (VecEC.isScalable() == ResultEC.isScalable()) {
7013 Check(IdxN < VecEC.getKnownMinValue() &&
7014 IdxN + ResultEC.getKnownMinValue() <= VecEC.getKnownMinValue(),
7015 "vector_extract would overrun.");
7016 }
7017 break;
7018 }
7019 case Intrinsic::vector_partial_reduce_fadd:
7020 case Intrinsic::vector_partial_reduce_add: {
7023
7024 unsigned VecWidth = VecTy->getElementCount().getKnownMinValue();
7025 unsigned AccWidth = AccTy->getElementCount().getKnownMinValue();
7026
7027 Check((VecWidth % AccWidth) == 0,
7028 "Invalid vector widths for partial "
7029 "reduction. The width of the input vector "
7030 "must be a positive integer multiple of "
7031 "the width of the accumulator vector.");
7032 break;
7033 }
7034 case Intrinsic::experimental_noalias_scope_decl: {
7035 NoAliasScopeDecls.push_back(cast<IntrinsicInst>(&Call));
7036 break;
7037 }
7038 case Intrinsic::preserve_array_access_index:
7039 case Intrinsic::preserve_struct_access_index:
7040 case Intrinsic::aarch64_ldaxr:
7041 case Intrinsic::aarch64_ldxr:
7042 case Intrinsic::arm_ldaex:
7043 case Intrinsic::arm_ldrex: {
7044 Type *ElemTy = Call.getParamElementType(0);
7045 Check(ElemTy, "Intrinsic requires elementtype attribute on first argument.",
7046 &Call);
7047 break;
7048 }
7049 case Intrinsic::aarch64_stlxr:
7050 case Intrinsic::aarch64_stxr:
7051 case Intrinsic::arm_stlex:
7052 case Intrinsic::arm_strex: {
7053 Type *ElemTy = Call.getAttributes().getParamElementType(1);
7054 Check(ElemTy,
7055 "Intrinsic requires elementtype attribute on second argument.",
7056 &Call);
7057 break;
7058 }
7059 case Intrinsic::aarch64_prefetch: {
7060 Check(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2,
7061 "write argument to llvm.aarch64.prefetch must be 0 or 1", Call);
7062 Check(cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 4,
7063 "target argument to llvm.aarch64.prefetch must be 0-3", Call);
7064 Check(cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue() < 2,
7065 "stream argument to llvm.aarch64.prefetch must be 0 or 1", Call);
7066 Check(cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue() < 2,
7067 "isdata argument to llvm.aarch64.prefetch must be 0 or 1", Call);
7068 break;
7069 }
7070 case Intrinsic::aarch64_range_prefetch: {
7071 Check(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2,
7072 "write argument to llvm.aarch64.range.prefetch must be 0 or 1", Call);
7073 Check(cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 2,
7074 "stream argument to llvm.aarch64.range.prefetch must be 0 or 1",
7075 Call);
7076 break;
7077 }
7078 case Intrinsic::callbr_landingpad: {
7079 const auto *CBR = dyn_cast<CallBrInst>(Call.getOperand(0));
7080 Check(CBR, "intrinstic requires callbr operand", &Call);
7081 if (!CBR)
7082 break;
7083
7084 const BasicBlock *LandingPadBB = Call.getParent();
7085 const BasicBlock *PredBB = LandingPadBB->getUniquePredecessor();
7086 if (!PredBB) {
7087 CheckFailed("Intrinsic in block must have 1 unique predecessor", &Call);
7088 break;
7089 }
7090 if (!isa<CallBrInst>(PredBB->getTerminator())) {
7091 CheckFailed("Intrinsic must have corresponding callbr in predecessor",
7092 &Call);
7093 break;
7094 }
7095 Check(llvm::is_contained(CBR->getIndirectDests(), LandingPadBB),
7096 "Intrinsic's corresponding callbr must have intrinsic's parent basic "
7097 "block in indirect destination list",
7098 &Call);
7099 const Instruction &First = *LandingPadBB->begin();
7100 Check(&First == &Call, "No other instructions may proceed intrinsic",
7101 &Call);
7102 break;
7103 }
7104 case Intrinsic::structured_gep: {
7105 // Parser should refuse those 2 cases.
7106 assert(Call.arg_size() >= 1);
7108
7109 Check(Call.paramHasAttr(0, Attribute::ElementType),
7110 "Intrinsic first parameter is missing an ElementType attribute",
7111 &Call);
7112
7113 Type *T = Call.getParamAttr(0, Attribute::ElementType).getValueAsType();
7114 for (unsigned I = 1; I < Call.arg_size(); ++I) {
7116 ConstantInt *CI = dyn_cast<ConstantInt>(Index);
7117 Check(Index->getType()->isIntegerTy(),
7118 "Index operand type must be an integer", &Call);
7119
7120 if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
7121 T = AT->getElementType();
7122 } else if (StructType *ST = dyn_cast<StructType>(T)) {
7123 Check(CI, "Indexing into a struct requires a constant int", &Call);
7124 Check(CI->getZExtValue() < ST->getNumElements(),
7125 "Indexing in a struct should be inbounds", &Call);
7126 T = ST->getElementType(CI->getZExtValue());
7127 } else if (VectorType *VT = dyn_cast<VectorType>(T)) {
7128 T = VT->getElementType();
7129 } else {
7130 CheckFailed("Reached a non-composite type with more indices to process",
7131 &Call);
7132 }
7133 }
7134 break;
7135 }
7136 case Intrinsic::structured_alloca:
7137 Check(Call.hasRetAttr(Attribute::ElementType),
7138 "@llvm.structured.alloca calls require elementtype attribute.",
7139 &Call);
7140 break;
7141 case Intrinsic::amdgcn_cs_chain: {
7142 auto CallerCC = Call.getCaller()->getCallingConv();
7143 switch (CallerCC) {
7144 case CallingConv::AMDGPU_CS:
7145 case CallingConv::AMDGPU_CS_Chain:
7146 case CallingConv::AMDGPU_CS_ChainPreserve:
7147 case CallingConv::AMDGPU_ES:
7148 case CallingConv::AMDGPU_GS:
7149 case CallingConv::AMDGPU_HS:
7150 case CallingConv::AMDGPU_LS:
7151 case CallingConv::AMDGPU_VS:
7152 break;
7153 default:
7154 CheckFailed("Intrinsic cannot be called from functions with this "
7155 "calling convention",
7156 &Call);
7157 break;
7158 }
7159
7160 Check(Call.paramHasAttr(2, Attribute::InReg),
7161 "SGPR arguments must have the `inreg` attribute", &Call);
7162 Check(!Call.paramHasAttr(3, Attribute::InReg),
7163 "VGPR arguments must not have the `inreg` attribute", &Call);
7164
7165 auto *Next = Call.getNextNode();
7166 bool IsAMDUnreachable = Next && isa<IntrinsicInst>(Next) &&
7167 cast<IntrinsicInst>(Next)->getIntrinsicID() ==
7168 Intrinsic::amdgcn_unreachable;
7169 Check(Next && (isa<UnreachableInst>(Next) || IsAMDUnreachable),
7170 "llvm.amdgcn.cs.chain must be followed by unreachable", &Call);
7171 break;
7172 }
7173 case Intrinsic::amdgcn_init_exec_from_input: {
7174 const Argument *Arg = dyn_cast<Argument>(Call.getOperand(0));
7175 Check(Arg && Arg->hasInRegAttr(),
7176 "only inreg arguments to the parent function are valid as inputs to "
7177 "this intrinsic",
7178 &Call);
7179 break;
7180 }
7181 case Intrinsic::amdgcn_set_inactive_chain_arg: {
7182 auto CallerCC = Call.getCaller()->getCallingConv();
7183 switch (CallerCC) {
7184 case CallingConv::AMDGPU_CS_Chain:
7185 case CallingConv::AMDGPU_CS_ChainPreserve:
7186 break;
7187 default:
7188 CheckFailed("Intrinsic can only be used from functions with the "
7189 "amdgpu_cs_chain or amdgpu_cs_chain_preserve "
7190 "calling conventions",
7191 &Call);
7192 break;
7193 }
7194
7195 unsigned InactiveIdx = 1;
7196 Check(!Call.paramHasAttr(InactiveIdx, Attribute::InReg),
7197 "Value for inactive lanes must not have the `inreg` attribute",
7198 &Call);
7199 Check(isa<Argument>(Call.getArgOperand(InactiveIdx)),
7200 "Value for inactive lanes must be a function argument", &Call);
7201 Check(!cast<Argument>(Call.getArgOperand(InactiveIdx))->hasInRegAttr(),
7202 "Value for inactive lanes must be a VGPR function argument", &Call);
7203 break;
7204 }
7205 case Intrinsic::amdgcn_call_whole_wave: {
7207 Check(F, "Indirect whole wave calls are not allowed", &Call);
7208
7209 CallingConv::ID CC = F->getCallingConv();
7210 Check(CC == CallingConv::AMDGPU_Gfx_WholeWave,
7211 "Callee must have the amdgpu_gfx_whole_wave calling convention",
7212 &Call);
7213
7214 Check(!F->isVarArg(), "Variadic whole wave calls are not allowed", &Call);
7215
7216 Check(Call.arg_size() == F->arg_size(),
7217 "Call argument count must match callee argument count", &Call);
7218
7219 // The first argument of the call is the callee, and the first argument of
7220 // the callee is the active mask. The rest of the arguments must match.
7221 Check(F->arg_begin()->getType()->isIntegerTy(1),
7222 "Callee must have i1 as its first argument", &Call);
7223 for (auto [CallArg, FuncArg] :
7224 drop_begin(zip_equal(Call.args(), F->args()))) {
7225 Check(CallArg->getType() == FuncArg.getType(),
7226 "Argument types must match", &Call);
7227
7228 // Check that inreg attributes match between call site and function
7229 Check(Call.paramHasAttr(FuncArg.getArgNo(), Attribute::InReg) ==
7230 FuncArg.hasInRegAttr(),
7231 "Argument inreg attributes must match", &Call);
7232 }
7233 break;
7234 }
7235 case Intrinsic::amdgcn_s_prefetch_data: {
7236 Check(
7239 "llvm.amdgcn.s.prefetch.data only supports global or constant memory");
7240 break;
7241 }
7242 case Intrinsic::amdgcn_load_to_lds:
7243 case Intrinsic::amdgcn_load_async_to_lds:
7244 case Intrinsic::amdgcn_global_load_lds:
7245 case Intrinsic::amdgcn_global_load_async_lds:
7246 case Intrinsic::amdgcn_raw_buffer_load_lds:
7247 case Intrinsic::amdgcn_raw_buffer_load_async_lds:
7248 case Intrinsic::amdgcn_raw_ptr_buffer_load_lds:
7249 case Intrinsic::amdgcn_raw_ptr_buffer_load_async_lds:
7250 case Intrinsic::amdgcn_struct_buffer_load_lds:
7251 case Intrinsic::amdgcn_struct_buffer_load_async_lds:
7252 case Intrinsic::amdgcn_struct_ptr_buffer_load_lds:
7253 case Intrinsic::amdgcn_struct_ptr_buffer_load_async_lds: {
7254 // The data byte size immarg is operand 2 for every load-to-LDS intrinsic.
7255 uint64_t Size = cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue();
7256 Check(Size == 1 || Size == 2 || Size == 4 || Size == 12 || Size == 16,
7257 "invalid data size for load-to-LDS intrinsic; must be 1, 2, 4, 12, "
7258 "or 16",
7259 &Call);
7260 break;
7261 }
7262 case Intrinsic::amdgcn_mfma_scale_f32_16x16x128_f8f6f4:
7263 case Intrinsic::amdgcn_mfma_scale_f32_32x32x64_f8f6f4: {
7264 Value *Src0 = Call.getArgOperand(0);
7265 Value *Src1 = Call.getArgOperand(1);
7266
7267 uint64_t CBSZ = cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue();
7268 uint64_t BLGP = cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue();
7269 Check(CBSZ <= 4, "invalid value for cbsz format", Call,
7270 Call.getArgOperand(3));
7271 Check(BLGP <= 4, "invalid value for blgp format", Call,
7272 Call.getArgOperand(4));
7273
7274 // AMDGPU::MFMAScaleFormats values
7275 auto getFormatNumRegs = [](unsigned FormatVal) {
7276 switch (FormatVal) {
7277 case 0:
7278 case 1:
7279 return 8u;
7280 case 2:
7281 case 3:
7282 return 6u;
7283 case 4:
7284 return 4u;
7285 default:
7286 llvm_unreachable("invalid format value");
7287 }
7288 };
7289
7290 auto isValidSrcASrcBVector = [](FixedVectorType *Ty) {
7291 if (!Ty || !Ty->getElementType()->isIntegerTy(32))
7292 return false;
7293 unsigned NumElts = Ty->getNumElements();
7294 return NumElts == 4 || NumElts == 6 || NumElts == 8;
7295 };
7296
7297 auto *Src0Ty = dyn_cast<FixedVectorType>(Src0->getType());
7298 auto *Src1Ty = dyn_cast<FixedVectorType>(Src1->getType());
7299 Check(isValidSrcASrcBVector(Src0Ty),
7300 "operand 0 must be 4, 6 or 8 element i32 vector", &Call, Src0);
7301 Check(isValidSrcASrcBVector(Src1Ty),
7302 "operand 1 must be 4, 6 or 8 element i32 vector", &Call, Src1);
7303
7304 // Permit excess registers for the format.
7305 Check(Src0Ty->getNumElements() >= getFormatNumRegs(CBSZ),
7306 "invalid vector type for format", &Call, Src0, Call.getArgOperand(3));
7307 Check(Src1Ty->getNumElements() >= getFormatNumRegs(BLGP),
7308 "invalid vector type for format", &Call, Src1, Call.getArgOperand(5));
7309 break;
7310 }
7311 case Intrinsic::amdgcn_wmma_f32_16x16x128_f8f6f4:
7312 case Intrinsic::amdgcn_wmma_scale_f32_16x16x128_f8f6f4:
7313 case Intrinsic::amdgcn_wmma_scale16_f32_16x16x128_f8f6f4: {
7314 Value *Src0 = Call.getArgOperand(1);
7315 Value *Src1 = Call.getArgOperand(3);
7316
7317 unsigned FmtA = cast<ConstantInt>(Call.getArgOperand(0))->getZExtValue();
7318 unsigned FmtB = cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue();
7319 Check(FmtA <= 4, "invalid value for matrix format", Call,
7320 Call.getArgOperand(0));
7321 Check(FmtB <= 4, "invalid value for matrix format", Call,
7322 Call.getArgOperand(2));
7323
7324 // AMDGPU::MatrixFMT values
7325 auto getFormatNumRegs = [](unsigned FormatVal) {
7326 switch (FormatVal) {
7327 case 0:
7328 case 1:
7329 return 16u;
7330 case 2:
7331 case 3:
7332 return 12u;
7333 case 4:
7334 return 8u;
7335 default:
7336 llvm_unreachable("invalid format value");
7337 }
7338 };
7339
7340 auto isValidSrcASrcBVector = [](FixedVectorType *Ty) {
7341 if (!Ty || !Ty->getElementType()->isIntegerTy(32))
7342 return false;
7343 unsigned NumElts = Ty->getNumElements();
7344 return NumElts == 16 || NumElts == 12 || NumElts == 8;
7345 };
7346
7347 auto *Src0Ty = dyn_cast<FixedVectorType>(Src0->getType());
7348 auto *Src1Ty = dyn_cast<FixedVectorType>(Src1->getType());
7349 Check(isValidSrcASrcBVector(Src0Ty),
7350 "operand 1 must be 8, 12 or 16 element i32 vector", &Call, Src0);
7351 Check(isValidSrcASrcBVector(Src1Ty),
7352 "operand 3 must be 8, 12 or 16 element i32 vector", &Call, Src1);
7353
7354 // Permit excess registers for the format.
7355 Check(Src0Ty->getNumElements() >= getFormatNumRegs(FmtA),
7356 "invalid vector type for format", &Call, Src0, Call.getArgOperand(0));
7357 Check(Src1Ty->getNumElements() >= getFormatNumRegs(FmtB),
7358 "invalid vector type for format", &Call, Src1, Call.getArgOperand(2));
7359 break;
7360 }
7361 case Intrinsic::amdgcn_cooperative_atomic_load_32x4B:
7362 case Intrinsic::amdgcn_cooperative_atomic_load_16x8B:
7363 case Intrinsic::amdgcn_cooperative_atomic_load_8x16B:
7364 case Intrinsic::amdgcn_cooperative_atomic_store_32x4B:
7365 case Intrinsic::amdgcn_cooperative_atomic_store_16x8B:
7366 case Intrinsic::amdgcn_cooperative_atomic_store_8x16B: {
7367 // Check we only use this intrinsic on the FLAT or GLOBAL address spaces.
7368 Value *PtrArg = Call.getArgOperand(0);
7369 const unsigned AS = PtrArg->getType()->getPointerAddressSpace();
7371 "cooperative atomic intrinsics require a generic or global pointer",
7372 &Call, PtrArg);
7373
7374 // Last argument must be a MD string
7376 MDNode *MD = cast<MDNode>(Op->getMetadata());
7377 Check((MD->getNumOperands() == 1) && isa<MDString>(MD->getOperand(0)),
7378 "cooperative atomic intrinsics require that the last argument is a "
7379 "metadata string",
7380 &Call, Op);
7381 break;
7382 }
7383 case Intrinsic::amdgcn_av_load_b128:
7384 case Intrinsic::amdgcn_av_store_b128: {
7385 // Last argument must be a MD string
7387 auto *MD = dyn_cast<MDNode>(Op->getMetadata());
7388 Check(MD && (MD->getNumOperands() == 1) && isa<MDString>(MD->getOperand(0)),
7389 "the last argument to av load/store intrinsics must be a "
7390 "metadata string",
7391 &Call, Op);
7392 break;
7393 }
7394 case Intrinsic::nvvm_setmaxnreg_inc_sync_aligned_u32:
7395 case Intrinsic::nvvm_setmaxnreg_dec_sync_aligned_u32: {
7396 Value *V = Call.getArgOperand(0);
7397 unsigned RegCount = cast<ConstantInt>(V)->getZExtValue();
7398 Check(RegCount % 8 == 0,
7399 "reg_count argument to nvvm.setmaxnreg must be in multiples of 8");
7400 break;
7401 }
7402 case Intrinsic::experimental_convergence_entry:
7403 case Intrinsic::experimental_convergence_anchor:
7404 break;
7405 case Intrinsic::experimental_convergence_loop:
7406 break;
7407 case Intrinsic::ptrmask: {
7408 Type *Ty0 = Call.getArgOperand(0)->getType();
7409 Type *Ty1 = Call.getArgOperand(1)->getType();
7411 "llvm.ptrmask intrinsic first argument must be pointer or vector "
7412 "of pointers",
7413 &Call);
7414 Check(
7415 Ty0->isVectorTy() == Ty1->isVectorTy(),
7416 "llvm.ptrmask intrinsic arguments must be both scalars or both vectors",
7417 &Call);
7418 if (Ty0->isVectorTy())
7419 Check(cast<VectorType>(Ty0)->getElementCount() ==
7420 cast<VectorType>(Ty1)->getElementCount(),
7421 "llvm.ptrmask intrinsic arguments must have the same number of "
7422 "elements",
7423 &Call);
7424 Check(DL.getIndexTypeSizeInBits(Ty0) == Ty1->getScalarSizeInBits(),
7425 "llvm.ptrmask intrinsic second argument bitwidth must match "
7426 "pointer index type size of first argument",
7427 &Call);
7428 break;
7429 }
7430 case Intrinsic::thread_pointer: {
7432 DL.getDefaultGlobalsAddressSpace(),
7433 "llvm.thread.pointer intrinsic return type must be for the globals "
7434 "address space",
7435 &Call);
7436 break;
7437 }
7438 case Intrinsic::threadlocal_address: {
7439 const Value &Arg0 = *Call.getArgOperand(0);
7440 Check(isa<GlobalValue>(Arg0),
7441 "llvm.threadlocal.address first argument must be a GlobalValue");
7442 Check(cast<GlobalValue>(Arg0).isThreadLocal(),
7443 "llvm.threadlocal.address operand isThreadLocal() must be true");
7444 break;
7445 }
7446 case Intrinsic::lifetime_start:
7447 case Intrinsic::lifetime_end: {
7448 Value *Ptr = Call.getArgOperand(0);
7449 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Ptr);
7450 Check(isa<AllocaInst>(Ptr) || isa<PoisonValue>(Ptr) ||
7451 (II && II->getIntrinsicID() == Intrinsic::structured_alloca),
7452 "llvm.lifetime.start/end can only be used on alloca or poison",
7453 &Call);
7454 break;
7455 }
7456 case Intrinsic::sponentry: {
7457 const unsigned StackAS = DL.getAllocaAddrSpace();
7458 const Type *RetTy = Call.getFunctionType()->getReturnType();
7459 Check(RetTy->getPointerAddressSpace() == StackAS,
7460 "llvm.sponentry must return a pointer to the stack", &Call);
7461 break;
7462 }
7463 case Intrinsic::write_volatile_register: {
7464 auto *MD = cast<MDNode>(
7465 cast<MetadataAsValue>(Call.getArgOperand(0))->getMetadata());
7466 Check(MD->getNumOperands() == 1 && isa<MDString>(MD->getOperand(0)),
7467 "llvm.write_volatile_register metadata must be a single MDString",
7468 &Call);
7469 break;
7470 }
7471 };
7472
7473 // Verify that there aren't any unmediated control transfers between funclets.
7475 Function *F = Call.getParent()->getParent();
7476 if (F->hasPersonalityFn() &&
7477 isScopedEHPersonality(classifyEHPersonality(F->getPersonalityFn()))) {
7478 // Run EH funclet coloring on-demand and cache results for other intrinsic
7479 // calls in this function
7480 if (BlockEHFuncletColors.empty())
7481 BlockEHFuncletColors = colorEHFunclets(*F);
7482
7483 // Check for catch-/cleanup-pad in first funclet block
7484 bool InEHFunclet = false;
7485 BasicBlock *CallBB = Call.getParent();
7486 const ColorVector &CV = BlockEHFuncletColors.find(CallBB)->second;
7487 assert(CV.size() > 0 && "Uncolored block");
7488 for (BasicBlock *ColorFirstBB : CV)
7489 if (auto It = ColorFirstBB->getFirstNonPHIIt();
7490 It != ColorFirstBB->end())
7492 InEHFunclet = true;
7493
7494 // Check for funclet operand bundle
7495 bool HasToken = false;
7496 for (unsigned I = 0, E = Call.getNumOperandBundles(); I != E; ++I)
7498 HasToken = true;
7499
7500 // This would cause silent code truncation in WinEHPrepare
7501 if (InEHFunclet)
7502 Check(HasToken, "Missing funclet token on intrinsic call", &Call);
7503 }
7504 }
7505}
7506
7507/// Carefully grab the subprogram from a local scope.
7508///
7509/// This carefully grabs the subprogram from a local scope, avoiding the
7510/// built-in assertions that would typically fire.
7512 if (!LocalScope)
7513 return nullptr;
7514
7515 if (auto *SP = dyn_cast<DISubprogram>(LocalScope))
7516 return SP;
7517
7518 if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope))
7519 return getSubprogram(LB->getRawScope());
7520
7521 // Just return null; broken scope chains are checked elsewhere.
7522 assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope");
7523 return nullptr;
7524}
7525
7526void Verifier::visit(DbgLabelRecord &DLR) {
7528 "invalid #dbg_label intrinsic variable", &DLR, DLR.getRawLabel());
7529
7530 // Ignore broken !dbg attachments; they're checked elsewhere.
7531 if (MDNode *N = DLR.getDebugLoc().getAsMDNode())
7532 if (!isa<DILocation>(N))
7533 return;
7534
7535 BasicBlock *BB = DLR.getParent();
7536 Function *F = BB ? BB->getParent() : nullptr;
7537
7538 // The scopes for variables and !dbg attachments must agree.
7539 DILabel *Label = DLR.getLabel();
7540 DILocation *Loc = DLR.getDebugLoc();
7541 CheckDI(Loc, "#dbg_label record requires a !dbg attachment", &DLR, BB, F);
7542
7543 DISubprogram *LabelSP = getSubprogram(Label->getRawScope());
7544 DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
7545 if (!LabelSP || !LocSP)
7546 return;
7547
7548 CheckDI(LabelSP == LocSP,
7549 "mismatched subprogram between #dbg_label label and !dbg attachment",
7550 &DLR, BB, F, Label, Label->getScope()->getSubprogram(), Loc,
7551 Loc->getScope()->getSubprogram());
7552}
7553
7554void Verifier::visit(DbgVariableRecord &DVR) {
7555 BasicBlock *BB = DVR.getParent();
7556 Function *F = BB->getParent();
7557
7558 CheckDI(DVR.getType() == DbgVariableRecord::LocationType::Value ||
7559 DVR.getType() == DbgVariableRecord::LocationType::Declare ||
7560 DVR.getType() == DbgVariableRecord::LocationType::DeclareValue ||
7561 DVR.getType() == DbgVariableRecord::LocationType::Assign,
7562 "invalid #dbg record type", &DVR, DVR.getType(), BB, F);
7563
7564 // The location for a DbgVariableRecord must be either a ValueAsMetadata,
7565 // DIArgList, or an empty MDNode (which is a legacy representation for an
7566 // "undef" location).
7567 auto *MD = DVR.getRawLocation();
7568 CheckDI(MD && (isa<ValueAsMetadata>(MD) || isa<DIArgList>(MD) ||
7569 (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands())),
7570 "invalid #dbg record address/value", &DVR, MD, BB, F);
7571 if (auto *VAM = dyn_cast<ValueAsMetadata>(MD)) {
7572 visitValueAsMetadata(*VAM, F);
7573 if (DVR.isDbgDeclare()) {
7574 // Allow integers here to support inttoptr salvage.
7575 Type *Ty = VAM->getValue()->getType();
7576 CheckDI(Ty->isPointerTy() || Ty->isIntegerTy(),
7577 "location of #dbg_declare must be a pointer or int", &DVR, MD, BB,
7578 F);
7579 }
7580 } else if (auto *AL = dyn_cast<DIArgList>(MD)) {
7581 visitDIArgList(*AL, F);
7582 }
7583
7585 "invalid #dbg record variable", &DVR, DVR.getRawVariable(), BB, F);
7586 visitMDNode(*DVR.getRawVariable(), AreDebugLocsAllowed::No);
7587
7589 "invalid #dbg record expression", &DVR, DVR.getRawExpression(), BB,
7590 F);
7591 visitMDNode(*DVR.getExpression(), AreDebugLocsAllowed::No);
7592
7593 if (DVR.isDbgAssign()) {
7595 "invalid #dbg_assign DIAssignID", &DVR, DVR.getRawAssignID(), BB,
7596 F);
7597 visitMDNode(*cast<DIAssignID>(DVR.getRawAssignID()),
7598 AreDebugLocsAllowed::No);
7599
7600 const auto *RawAddr = DVR.getRawAddress();
7601 // Similarly to the location above, the address for an assign
7602 // DbgVariableRecord must be a ValueAsMetadata or an empty MDNode, which
7603 // represents an undef address.
7604 CheckDI(
7605 isa<ValueAsMetadata>(RawAddr) ||
7606 (isa<MDNode>(RawAddr) && !cast<MDNode>(RawAddr)->getNumOperands()),
7607 "invalid #dbg_assign address", &DVR, DVR.getRawAddress(), BB, F);
7608 if (auto *VAM = dyn_cast<ValueAsMetadata>(RawAddr))
7609 visitValueAsMetadata(*VAM, F);
7610
7612 "invalid #dbg_assign address expression", &DVR,
7613 DVR.getRawAddressExpression(), BB, F);
7614 visitMDNode(*DVR.getAddressExpression(), AreDebugLocsAllowed::No);
7615
7616 // All of the linked instructions should be in the same function as DVR.
7617 for (Instruction *I : at::getAssignmentInsts(&DVR))
7618 CheckDI(DVR.getFunction() == I->getFunction(),
7619 "inst not in same function as #dbg_assign", I, &DVR, BB, F);
7620 }
7621
7622 // This check is redundant with one in visitLocalVariable().
7623 DILocalVariable *Var = DVR.getVariable();
7624 CheckDI(isType(Var->getRawType()), "invalid type ref", Var, Var->getRawType(),
7625 BB, F);
7626
7627 auto *DLNode = DVR.getDebugLoc().getAsMDNode();
7628 CheckDI(isa_and_nonnull<DILocation>(DLNode), "invalid #dbg record DILocation",
7629 &DVR, DLNode, BB, F);
7630 DILocation *Loc = DVR.getDebugLoc();
7631
7632 // The scopes for variables and !dbg attachments must agree.
7633 DISubprogram *VarSP = getSubprogram(Var->getRawScope());
7634 DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
7635 if (!VarSP || !LocSP)
7636 return; // Broken scope chains are checked elsewhere.
7637
7638 CheckDI(VarSP == LocSP,
7639 "mismatched subprogram between #dbg record variable and DILocation",
7640 &DVR, BB, F, Var, Var->getScope()->getSubprogram(), Loc,
7641 Loc->getScope()->getSubprogram(), BB, F);
7642
7643 verifyFnArgs(DVR);
7644}
7645
7646void Verifier::visitVPIntrinsic(VPIntrinsic &VPI) {
7647 if (auto *VPCast = dyn_cast<VPCastIntrinsic>(&VPI)) {
7648 auto *RetTy = cast<VectorType>(VPCast->getType());
7649 auto *ValTy = cast<VectorType>(VPCast->getOperand(0)->getType());
7650 Check(RetTy->getElementCount() == ValTy->getElementCount(),
7651 "VP cast intrinsic first argument and result vector lengths must be "
7652 "equal",
7653 *VPCast);
7654
7655 switch (VPCast->getIntrinsicID()) {
7656 default:
7657 llvm_unreachable("Unknown VP cast intrinsic");
7658 case Intrinsic::vp_trunc:
7659 Check(RetTy->isIntOrIntVectorTy() && ValTy->isIntOrIntVectorTy(),
7660 "llvm.vp.trunc intrinsic first argument and result element type "
7661 "must be integer",
7662 *VPCast);
7663 Check(RetTy->getScalarSizeInBits() < ValTy->getScalarSizeInBits(),
7664 "llvm.vp.trunc intrinsic the bit size of first argument must be "
7665 "larger than the bit size of the return type",
7666 *VPCast);
7667 break;
7668 case Intrinsic::vp_zext:
7669 case Intrinsic::vp_sext:
7670 Check(RetTy->isIntOrIntVectorTy() && ValTy->isIntOrIntVectorTy(),
7671 "llvm.vp.zext or llvm.vp.sext intrinsic first argument and result "
7672 "element type must be integer",
7673 *VPCast);
7674 Check(RetTy->getScalarSizeInBits() > ValTy->getScalarSizeInBits(),
7675 "llvm.vp.zext or llvm.vp.sext intrinsic the bit size of first "
7676 "argument must be smaller than the bit size of the return type",
7677 *VPCast);
7678 break;
7679 case Intrinsic::vp_fptoui:
7680 case Intrinsic::vp_fptosi:
7681 case Intrinsic::vp_lrint:
7682 case Intrinsic::vp_llrint:
7683 Check(
7684 RetTy->isIntOrIntVectorTy() && ValTy->isFPOrFPVectorTy(),
7685 "llvm.vp.fptoui, llvm.vp.fptosi, llvm.vp.lrint or llvm.vp.llrint" "intrinsic first argument element "
7686 "type must be floating-point and result element type must be integer",
7687 *VPCast);
7688 break;
7689 case Intrinsic::vp_uitofp:
7690 case Intrinsic::vp_sitofp:
7691 Check(
7692 RetTy->isFPOrFPVectorTy() && ValTy->isIntOrIntVectorTy(),
7693 "llvm.vp.uitofp or llvm.vp.sitofp intrinsic first argument element "
7694 "type must be integer and result element type must be floating-point",
7695 *VPCast);
7696 break;
7697 case Intrinsic::vp_fptrunc:
7698 Check(RetTy->isFPOrFPVectorTy() && ValTy->isFPOrFPVectorTy(),
7699 "llvm.vp.fptrunc intrinsic first argument and result element type "
7700 "must be floating-point",
7701 *VPCast);
7702 Check(RetTy->getScalarSizeInBits() < ValTy->getScalarSizeInBits(),
7703 "llvm.vp.fptrunc intrinsic the bit size of first argument must be "
7704 "larger than the bit size of the return type",
7705 *VPCast);
7706 break;
7707 case Intrinsic::vp_fpext:
7708 Check(RetTy->isFPOrFPVectorTy() && ValTy->isFPOrFPVectorTy(),
7709 "llvm.vp.fpext intrinsic first argument and result element type "
7710 "must be floating-point",
7711 *VPCast);
7712 Check(RetTy->getScalarSizeInBits() > ValTy->getScalarSizeInBits(),
7713 "llvm.vp.fpext intrinsic the bit size of first argument must be "
7714 "smaller than the bit size of the return type",
7715 *VPCast);
7716 break;
7717 case Intrinsic::vp_ptrtoint:
7718 Check(RetTy->isIntOrIntVectorTy() && ValTy->isPtrOrPtrVectorTy(),
7719 "llvm.vp.ptrtoint intrinsic first argument element type must be "
7720 "pointer and result element type must be integer",
7721 *VPCast);
7722 break;
7723 case Intrinsic::vp_inttoptr:
7724 Check(RetTy->isPtrOrPtrVectorTy() && ValTy->isIntOrIntVectorTy(),
7725 "llvm.vp.inttoptr intrinsic first argument element type must be "
7726 "integer and result element type must be pointer",
7727 *VPCast);
7728 break;
7729 }
7730 }
7731
7732 switch (VPI.getIntrinsicID()) {
7733 case Intrinsic::vp_fcmp: {
7734 auto Pred = cast<VPCmpIntrinsic>(&VPI)->getPredicate();
7736 "invalid predicate for VP FP comparison intrinsic", &VPI);
7737 break;
7738 }
7739 case Intrinsic::vp_icmp: {
7740 auto Pred = cast<VPCmpIntrinsic>(&VPI)->getPredicate();
7742 "invalid predicate for VP integer comparison intrinsic", &VPI);
7743 break;
7744 }
7745 case Intrinsic::vp_is_fpclass: {
7746 auto TestMask = cast<ConstantInt>(VPI.getOperand(1));
7747 Check((TestMask->getZExtValue() & ~static_cast<unsigned>(fcAllFlags)) == 0,
7748 "unsupported bits for llvm.vp.is.fpclass test mask");
7749 break;
7750 }
7751 case Intrinsic::experimental_vp_splice: {
7752 VectorType *VecTy = cast<VectorType>(VPI.getType());
7753 int64_t Idx = cast<ConstantInt>(VPI.getArgOperand(2))->getSExtValue();
7754 int64_t KnownMinNumElements = VecTy->getElementCount().getKnownMinValue();
7755 if (VPI.getParent() && VPI.getParent()->getParent()) {
7756 AttributeList Attrs = VPI.getParent()->getParent()->getAttributes();
7757 if (Attrs.hasFnAttr(Attribute::VScaleRange))
7758 KnownMinNumElements *= Attrs.getFnAttrs().getVScaleRangeMin();
7759 }
7760 Check((Idx < 0 && std::abs(Idx) <= KnownMinNumElements) ||
7761 (Idx >= 0 && Idx < KnownMinNumElements),
7762 "The splice index exceeds the range [-VL, VL-1] where VL is the "
7763 "known minimum number of elements in the vector. For scalable "
7764 "vectors the minimum number of elements is determined from "
7765 "vscale_range.",
7766 &VPI);
7767 break;
7768 }
7769 }
7770}
7771
7772void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) {
7773 unsigned NumOperands = FPI.getNonMetadataArgCount();
7774 bool HasRoundingMD =
7776
7777 // Add the expected number of metadata operands.
7778 NumOperands += (1 + HasRoundingMD);
7779
7780 // Compare intrinsics carry an extra predicate metadata operand.
7782 NumOperands += 1;
7783 Check((FPI.arg_size() == NumOperands),
7784 "invalid arguments for constrained FP intrinsic", &FPI);
7785
7786 switch (FPI.getIntrinsicID()) {
7787 case Intrinsic::experimental_constrained_lrint:
7788 case Intrinsic::experimental_constrained_llrint: {
7789 Type *ValTy = FPI.getArgOperand(0)->getType();
7790 Type *ResultTy = FPI.getType();
7791 Check(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
7792 "Intrinsic does not support vectors", &FPI);
7793 break;
7794 }
7795
7796 case Intrinsic::experimental_constrained_lround:
7797 case Intrinsic::experimental_constrained_llround: {
7798 Type *ValTy = FPI.getArgOperand(0)->getType();
7799 Type *ResultTy = FPI.getType();
7800 Check(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
7801 "Intrinsic does not support vectors", &FPI);
7802 break;
7803 }
7804
7805 case Intrinsic::experimental_constrained_fcmp:
7806 case Intrinsic::experimental_constrained_fcmps: {
7807 auto Pred = cast<ConstrainedFPCmpIntrinsic>(&FPI)->getPredicate();
7809 "invalid predicate for constrained FP comparison intrinsic", &FPI);
7810 break;
7811 }
7812
7813 case Intrinsic::experimental_constrained_fptosi:
7814 case Intrinsic::experimental_constrained_fptoui: {
7815 Value *Operand = FPI.getArgOperand(0);
7816 ElementCount SrcEC;
7817 Check(Operand->getType()->isFPOrFPVectorTy(),
7818 "Intrinsic first argument must be floating point", &FPI);
7819 if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
7820 SrcEC = cast<VectorType>(OperandT)->getElementCount();
7821 }
7822
7823 Operand = &FPI;
7824 Check(SrcEC.isNonZero() == Operand->getType()->isVectorTy(),
7825 "Intrinsic first argument and result disagree on vector use", &FPI);
7826 Check(Operand->getType()->isIntOrIntVectorTy(),
7827 "Intrinsic result must be an integer", &FPI);
7828 if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
7829 Check(SrcEC == cast<VectorType>(OperandT)->getElementCount(),
7830 "Intrinsic first argument and result vector lengths must be equal",
7831 &FPI);
7832 }
7833 break;
7834 }
7835
7836 case Intrinsic::experimental_constrained_sitofp:
7837 case Intrinsic::experimental_constrained_uitofp: {
7838 Value *Operand = FPI.getArgOperand(0);
7839 ElementCount SrcEC;
7840 Check(Operand->getType()->isIntOrIntVectorTy(),
7841 "Intrinsic first argument must be integer", &FPI);
7842 if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
7843 SrcEC = cast<VectorType>(OperandT)->getElementCount();
7844 }
7845
7846 Operand = &FPI;
7847 Check(SrcEC.isNonZero() == Operand->getType()->isVectorTy(),
7848 "Intrinsic first argument and result disagree on vector use", &FPI);
7849 Check(Operand->getType()->isFPOrFPVectorTy(),
7850 "Intrinsic result must be a floating point", &FPI);
7851 if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
7852 Check(SrcEC == cast<VectorType>(OperandT)->getElementCount(),
7853 "Intrinsic first argument and result vector lengths must be equal",
7854 &FPI);
7855 }
7856 break;
7857 }
7858
7859 case Intrinsic::experimental_constrained_fptrunc:
7860 case Intrinsic::experimental_constrained_fpext: {
7861 Value *Operand = FPI.getArgOperand(0);
7862 Type *OperandTy = Operand->getType();
7863 Value *Result = &FPI;
7864 Type *ResultTy = Result->getType();
7865 Check(OperandTy->isFPOrFPVectorTy(),
7866 "Intrinsic first argument must be FP or FP vector", &FPI);
7867 Check(ResultTy->isFPOrFPVectorTy(),
7868 "Intrinsic result must be FP or FP vector", &FPI);
7869 Check(OperandTy->isVectorTy() == ResultTy->isVectorTy(),
7870 "Intrinsic first argument and result disagree on vector use", &FPI);
7871 if (OperandTy->isVectorTy()) {
7872 Check(cast<VectorType>(OperandTy)->getElementCount() ==
7873 cast<VectorType>(ResultTy)->getElementCount(),
7874 "Intrinsic first argument and result vector lengths must be equal",
7875 &FPI);
7876 }
7877 if (FPI.getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) {
7878 Check(OperandTy->getScalarSizeInBits() > ResultTy->getScalarSizeInBits(),
7879 "Intrinsic first argument's type must be larger than result type",
7880 &FPI);
7881 } else {
7882 Check(OperandTy->getScalarSizeInBits() < ResultTy->getScalarSizeInBits(),
7883 "Intrinsic first argument's type must be smaller than result type",
7884 &FPI);
7885 }
7886 break;
7887 }
7888
7889 default:
7890 break;
7891 }
7892
7893 // If a non-metadata argument is passed in a metadata slot then the
7894 // error will be caught earlier when the incorrect argument doesn't
7895 // match the specification in the intrinsic call table. Thus, no
7896 // argument type check is needed here.
7897
7898 Check(FPI.getExceptionBehavior().has_value(),
7899 "invalid exception behavior argument", &FPI);
7900 if (HasRoundingMD) {
7901 Check(FPI.getRoundingMode().has_value(), "invalid rounding mode argument",
7902 &FPI);
7903 }
7904}
7905
7906void Verifier::verifyFragmentExpression(const DbgVariableRecord &DVR) {
7907 DILocalVariable *V = dyn_cast_or_null<DILocalVariable>(DVR.getRawVariable());
7908 DIExpression *E = dyn_cast_or_null<DIExpression>(DVR.getRawExpression());
7909
7910 // We don't know whether this intrinsic verified correctly.
7911 if (!V || !E || !E->isValid())
7912 return;
7913
7914 // Nothing to do if this isn't a DW_OP_LLVM_fragment expression.
7915 auto Fragment = E->getFragmentInfo();
7916 if (!Fragment)
7917 return;
7918
7919 // The frontend helps out GDB by emitting the members of local anonymous
7920 // unions as artificial local variables with shared storage. When SROA splits
7921 // the storage for artificial local variables that are smaller than the entire
7922 // union, the overhang piece will be outside of the allotted space for the
7923 // variable and this check fails.
7924 // FIXME: Remove this check as soon as clang stops doing this; it hides bugs.
7925 if (V->isArtificial())
7926 return;
7927
7928 verifyFragmentExpression(*V, *Fragment, &DVR);
7929}
7930
7931template <typename ValueOrMetadata>
7932void Verifier::verifyFragmentExpression(const DIVariable &V,
7934 ValueOrMetadata *Desc) {
7935 // If there's no size, the type is broken, but that should be checked
7936 // elsewhere.
7937 auto VarSize = V.getSizeInBits();
7938 if (!VarSize)
7939 return;
7940
7941 unsigned FragSize = Fragment.SizeInBits;
7942 unsigned FragOffset = Fragment.OffsetInBits;
7943 CheckDI(FragSize + FragOffset <= *VarSize,
7944 "fragment is larger than or outside of variable", Desc, &V);
7945 CheckDI(FragSize != *VarSize, "fragment covers entire variable", Desc, &V);
7946}
7947
7948void Verifier::verifyFnArgs(const DbgVariableRecord &DVR) {
7949 // This function does not take the scope of noninlined function arguments into
7950 // account. Don't run it if current function is nodebug, because it may
7951 // contain inlined debug intrinsics.
7952 if (!HasDebugInfo)
7953 return;
7954
7955 // For performance reasons only check non-inlined ones.
7956 if (DVR.getDebugLoc()->getInlinedAt())
7957 return;
7958
7959 DILocalVariable *Var = DVR.getVariable();
7960 CheckDI(Var, "#dbg record without variable");
7961
7962 unsigned ArgNo = Var->getArg();
7963 if (!ArgNo)
7964 return;
7965
7966 // Verify there are no duplicate function argument debug info entries.
7967 // These will cause hard-to-debug assertions in the DWARF backend.
7968 if (DebugFnArgs.size() < ArgNo)
7969 DebugFnArgs.resize(ArgNo, nullptr);
7970
7971 auto *Prev = DebugFnArgs[ArgNo - 1];
7972 DebugFnArgs[ArgNo - 1] = Var;
7973 CheckDI(!Prev || (Prev == Var), "conflicting debug info for argument", &DVR,
7974 Prev, Var);
7975}
7976
7977void Verifier::verifyNotEntryValue(const DbgVariableRecord &DVR) {
7978 DIExpression *E = dyn_cast_or_null<DIExpression>(DVR.getRawExpression());
7979
7980 // We don't know whether this intrinsic verified correctly.
7981 if (!E || !E->isValid())
7982 return;
7983
7985 Value *VarValue = DVR.getVariableLocationOp(0);
7986 if (isa<UndefValue>(VarValue) || isa<PoisonValue>(VarValue))
7987 return;
7988 // We allow EntryValues for swift async arguments, as they have an
7989 // ABI-guarantee to be turned into a specific register.
7990 if (auto *ArgLoc = dyn_cast_or_null<Argument>(VarValue);
7991 ArgLoc && ArgLoc->hasAttribute(Attribute::SwiftAsync))
7992 return;
7993 }
7994
7995 CheckDI(!E->isEntryValue(),
7996 "Entry values are only allowed in MIR unless they target a "
7997 "swiftasync Argument",
7998 &DVR);
7999}
8000
8001void Verifier::verifyCompileUnits() {
8002 // When more than one Module is imported into the same context, such as during
8003 // an LTO build before linking the modules, ODR type uniquing may cause types
8004 // to point to a different CU. This check does not make sense in this case.
8005 if (M.getContext().isODRUniquingDebugTypes())
8006 return;
8007 auto *CUs = M.getNamedMetadata("llvm.dbg.cu");
8008 SmallPtrSet<const Metadata *, 2> Listed;
8009 if (CUs)
8010 Listed.insert_range(CUs->operands());
8011 for (const auto *CU : CUVisited)
8012 CheckDI(Listed.count(CU), "DICompileUnit not listed in llvm.dbg.cu", CU);
8013 CUVisited.clear();
8014}
8015
8016void Verifier::verifyDeoptimizeCallingConvs() {
8017 if (DeoptimizeDeclarations.empty())
8018 return;
8019
8020 const Function *First = DeoptimizeDeclarations[0];
8021 for (const auto *F : ArrayRef(DeoptimizeDeclarations).slice(1)) {
8022 Check(First->getCallingConv() == F->getCallingConv(),
8023 "All llvm.experimental.deoptimize declarations must have the same "
8024 "calling convention",
8025 First, F);
8026 }
8027}
8028
8029void Verifier::verifyAttachedCallBundle(const CallBase &Call,
8030 const OperandBundleUse &BU) {
8031 FunctionType *FTy = Call.getFunctionType();
8032
8033 Check((FTy->getReturnType()->isPointerTy() ||
8034 (Call.doesNotReturn() && FTy->getReturnType()->isVoidTy())),
8035 "a call with operand bundle \"clang.arc.attachedcall\" must call a "
8036 "function returning a pointer or a non-returning function that has a "
8037 "void return type",
8038 Call);
8039
8040 Check(BU.Inputs.size() == 1 && isa<Function>(BU.Inputs.front()),
8041 "operand bundle \"clang.arc.attachedcall\" requires one function as "
8042 "an argument",
8043 Call);
8044
8045 auto *Fn = cast<Function>(BU.Inputs.front());
8046 Intrinsic::ID IID = Fn->getIntrinsicID();
8047
8048 if (IID) {
8049 Check((IID == Intrinsic::objc_retainAutoreleasedReturnValue ||
8050 IID == Intrinsic::objc_claimAutoreleasedReturnValue ||
8051 IID == Intrinsic::objc_unsafeClaimAutoreleasedReturnValue),
8052 "invalid function argument", Call);
8053 } else {
8054 StringRef FnName = Fn->getName();
8055 Check((FnName == "objc_retainAutoreleasedReturnValue" ||
8056 FnName == "objc_claimAutoreleasedReturnValue" ||
8057 FnName == "objc_unsafeClaimAutoreleasedReturnValue"),
8058 "invalid function argument", Call);
8059 }
8060}
8061
8062void Verifier::verifyNoAliasScopeDecl() {
8063 if (NoAliasScopeDecls.empty())
8064 return;
8065
8066 // only a single scope must be declared at a time.
8067 for (auto *II : NoAliasScopeDecls) {
8068 assert(II->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl &&
8069 "Not a llvm.experimental.noalias.scope.decl ?");
8070 const auto *ScopeListMV = dyn_cast<MetadataAsValue>(
8072 Check(ScopeListMV != nullptr,
8073 "llvm.experimental.noalias.scope.decl must have a MetadataAsValue "
8074 "argument",
8075 II);
8076
8077 const auto *ScopeListMD = dyn_cast<MDNode>(ScopeListMV->getMetadata());
8078 Check(ScopeListMD != nullptr, "!id.scope.list must point to an MDNode", II);
8079 Check(ScopeListMD->getNumOperands() == 1,
8080 "!id.scope.list must point to a list with a single scope", II);
8081 visitAliasScopeListMetadata(ScopeListMD);
8082 }
8083
8084 // Only check the domination rule when requested. Once all passes have been
8085 // adapted this option can go away.
8087 return;
8088
8089 // Now sort the intrinsics based on the scope MDNode so that declarations of
8090 // the same scopes are next to each other.
8091 auto GetScope = [](IntrinsicInst *II) {
8092 const auto *ScopeListMV = cast<MetadataAsValue>(
8094 return &cast<MDNode>(ScopeListMV->getMetadata())->getOperand(0);
8095 };
8096
8097 // We are sorting on MDNode pointers here. For valid input IR this is ok.
8098 // TODO: Sort on Metadata ID to avoid non-deterministic error messages.
8099 auto Compare = [GetScope](IntrinsicInst *Lhs, IntrinsicInst *Rhs) {
8100 return GetScope(Lhs) < GetScope(Rhs);
8101 };
8102
8103 llvm::sort(NoAliasScopeDecls, Compare);
8104
8105 // Go over the intrinsics and check that for the same scope, they are not
8106 // dominating each other.
8107 auto ItCurrent = NoAliasScopeDecls.begin();
8108 while (ItCurrent != NoAliasScopeDecls.end()) {
8109 auto CurScope = GetScope(*ItCurrent);
8110 auto ItNext = ItCurrent;
8111 do {
8112 ++ItNext;
8113 } while (ItNext != NoAliasScopeDecls.end() &&
8114 GetScope(*ItNext) == CurScope);
8115
8116 // [ItCurrent, ItNext) represents the declarations for the same scope.
8117 // Ensure they are not dominating each other.. but only if it is not too
8118 // expensive.
8119 if (ItNext - ItCurrent < 32)
8120 for (auto *I : llvm::make_range(ItCurrent, ItNext))
8121 for (auto *J : llvm::make_range(ItCurrent, ItNext))
8122 if (I != J)
8123 Check(!DT.dominates(I, J),
8124 "llvm.experimental.noalias.scope.decl dominates another one "
8125 "with the same scope",
8126 I);
8127 ItCurrent = ItNext;
8128 }
8129}
8130
8131//===----------------------------------------------------------------------===//
8132// Implement the public interfaces to this file...
8133//===----------------------------------------------------------------------===//
8134
8136 Function &F = const_cast<Function &>(f);
8137
8138 // Don't use a raw_null_ostream. Printing IR is expensive.
8139 Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/true, *f.getParent());
8140
8141 // Note that this function's return value is inverted from what you would
8142 // expect of a function called "verify".
8143 return !V.verify(F);
8144}
8145
8147 bool *BrokenDebugInfo) {
8148 // Don't use a raw_null_ostream. Printing IR is expensive.
8149 Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/!BrokenDebugInfo, M);
8150
8151 bool Broken = false;
8152 for (const Function &F : M)
8153 Broken |= !V.verify(F);
8154
8155 Broken |= !V.verify();
8156 if (BrokenDebugInfo)
8157 *BrokenDebugInfo = V.hasBrokenDebugInfo();
8158 // Note that this function's return value is inverted from what you would
8159 // expect of a function called "verify".
8160 return Broken;
8161}
8162
8163namespace {
8164
8165struct VerifierLegacyPass : public FunctionPass {
8166 static char ID;
8167
8168 std::unique_ptr<Verifier> V;
8169 bool FatalErrors = true;
8170
8171 VerifierLegacyPass() : FunctionPass(ID) {}
8172 explicit VerifierLegacyPass(bool FatalErrors)
8173 : FunctionPass(ID), FatalErrors(FatalErrors) {}
8174
8175 bool doInitialization(Module &M) override {
8176 V = std::make_unique<Verifier>(
8177 &dbgs(), /*ShouldTreatBrokenDebugInfoAsError=*/false, M);
8178 return false;
8179 }
8180
8181 bool runOnFunction(Function &F) override {
8182 if (!V->verify(F) && FatalErrors) {
8183 errs() << "in function " << F.getName() << '\n';
8184 report_fatal_error("Broken function found, compilation aborted!");
8185 }
8186 return false;
8187 }
8188
8189 bool doFinalization(Module &M) override {
8190 bool HasErrors = false;
8191 for (Function &F : M)
8192 if (F.isDeclaration())
8193 HasErrors |= !V->verify(F);
8194
8195 HasErrors |= !V->verify();
8196 if (FatalErrors && (HasErrors || V->hasBrokenDebugInfo()))
8197 report_fatal_error("Broken module found, compilation aborted!");
8198 return false;
8199 }
8200
8201 void getAnalysisUsage(AnalysisUsage &AU) const override {
8202 AU.setPreservesAll();
8203 }
8204};
8205
8206} // end anonymous namespace
8207
8208/// Helper to issue failure from the TBAA verification
8209template <typename... Tys> void TBAAVerifier::CheckFailed(Tys &&... Args) {
8210 if (Diagnostic)
8211 return Diagnostic->CheckFailed(Args...);
8212}
8213
8214#define CheckTBAA(C, ...) \
8215 do { \
8216 if (!(C)) { \
8217 CheckFailed(__VA_ARGS__); \
8218 return false; \
8219 } \
8220 } while (false)
8221
8222/// Verify that \p BaseNode can be used as the "base type" in the struct-path
8223/// TBAA scheme. This means \p BaseNode is either a scalar node, or a
8224/// struct-type node describing an aggregate data structure (like a struct).
8225TBAAVerifier::TBAABaseNodeSummary
8226TBAAVerifier::verifyTBAABaseNode(const Instruction *I, const MDNode *BaseNode,
8227 bool IsNewFormat) {
8228 if (BaseNode->getNumOperands() < 2) {
8229 CheckFailed("Base nodes must have at least two operands", I, BaseNode);
8230 return {true, ~0u};
8231 }
8232
8233 auto Itr = TBAABaseNodes.find(BaseNode);
8234 if (Itr != TBAABaseNodes.end())
8235 return Itr->second;
8236
8237 auto Result = verifyTBAABaseNodeImpl(I, BaseNode, IsNewFormat);
8238 auto InsertResult = TBAABaseNodes.insert({BaseNode, Result});
8239 (void)InsertResult;
8240 assert(InsertResult.second && "We just checked!");
8241 return Result;
8242}
8243
8244TBAAVerifier::TBAABaseNodeSummary
8245TBAAVerifier::verifyTBAABaseNodeImpl(const Instruction *I,
8246 const MDNode *BaseNode, bool IsNewFormat) {
8247 const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {true, ~0u};
8248
8249 if (BaseNode->getNumOperands() == 2) {
8250 // Scalar nodes can only be accessed at offset 0.
8251 return isValidScalarTBAANode(BaseNode)
8252 ? TBAAVerifier::TBAABaseNodeSummary({false, 0})
8253 : InvalidNode;
8254 }
8255
8256 if (IsNewFormat) {
8257 if (BaseNode->getNumOperands() % 3 != 0) {
8258 CheckFailed("Access tag nodes must have the number of operands that is a "
8259 "multiple of 3!", BaseNode);
8260 return InvalidNode;
8261 }
8262 } else {
8263 if (BaseNode->getNumOperands() % 2 != 1) {
8264 CheckFailed("Struct tag nodes must have an odd number of operands!",
8265 BaseNode);
8266 return InvalidNode;
8267 }
8268 }
8269
8270 // Check the type size field.
8271 if (IsNewFormat) {
8272 auto *TypeSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
8273 BaseNode->getOperand(1));
8274 if (!TypeSizeNode) {
8275 CheckFailed("Type size nodes must be constants!", I, BaseNode);
8276 return InvalidNode;
8277 }
8278 }
8279
8280 // Check the type name field. In the new format it can be anything.
8281 if (!IsNewFormat && !isa<MDString>(BaseNode->getOperand(0))) {
8282 CheckFailed("Struct tag nodes have a string as their first operand",
8283 BaseNode);
8284 return InvalidNode;
8285 }
8286
8287 bool Failed = false;
8288
8289 std::optional<APInt> PrevOffset;
8290 unsigned BitWidth = ~0u;
8291
8292 // We've already checked that BaseNode is not a degenerate root node with one
8293 // operand in \c verifyTBAABaseNode, so this loop should run at least once.
8294 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
8295 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
8296 for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
8297 Idx += NumOpsPerField) {
8298 const MDOperand &FieldTy = BaseNode->getOperand(Idx);
8299 const MDOperand &FieldOffset = BaseNode->getOperand(Idx + 1);
8300 if (!isa<MDNode>(FieldTy)) {
8301 CheckFailed("Incorrect field entry in struct type node!", I, BaseNode);
8302 Failed = true;
8303 continue;
8304 }
8305
8306 auto *OffsetEntryCI =
8308 if (!OffsetEntryCI) {
8309 CheckFailed("Offset entries must be constants!", I, BaseNode);
8310 Failed = true;
8311 continue;
8312 }
8313
8314 if (BitWidth == ~0u)
8315 BitWidth = OffsetEntryCI->getBitWidth();
8316
8317 if (OffsetEntryCI->getBitWidth() != BitWidth) {
8318 CheckFailed(
8319 "Bitwidth between the offsets and struct type entries must match", I,
8320 BaseNode);
8321 Failed = true;
8322 continue;
8323 }
8324
8325 // NB! As far as I can tell, we generate a non-strictly increasing offset
8326 // sequence only from structs that have zero size bit fields. When
8327 // recursing into a contained struct in \c getFieldNodeFromTBAABaseNode we
8328 // pick the field lexically the latest in struct type metadata node. This
8329 // mirrors the actual behavior of the alias analysis implementation.
8330 bool IsAscending =
8331 !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue());
8332
8333 if (!IsAscending) {
8334 CheckFailed("Offsets must be increasing!", I, BaseNode);
8335 Failed = true;
8336 }
8337
8338 PrevOffset = OffsetEntryCI->getValue();
8339
8340 if (IsNewFormat) {
8341 auto *MemberSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
8342 BaseNode->getOperand(Idx + 2));
8343 if (!MemberSizeNode) {
8344 CheckFailed("Member size entries must be constants!", I, BaseNode);
8345 Failed = true;
8346 continue;
8347 }
8348 }
8349 }
8350
8351 return Failed ? InvalidNode
8352 : TBAAVerifier::TBAABaseNodeSummary(false, BitWidth);
8353}
8354
8355static bool IsRootTBAANode(const MDNode *MD) {
8356 return MD->getNumOperands() < 2;
8357}
8358
8359static bool IsScalarTBAANodeImpl(const MDNode *MD,
8361 if (MD->getNumOperands() != 2 && MD->getNumOperands() != 3)
8362 return false;
8363
8364 if (!isa<MDString>(MD->getOperand(0)))
8365 return false;
8366
8367 if (MD->getNumOperands() == 3) {
8369 if (!(Offset && Offset->isZero() && isa<MDString>(MD->getOperand(0))))
8370 return false;
8371 }
8372
8373 auto *Parent = dyn_cast_or_null<MDNode>(MD->getOperand(1));
8374 return Parent && Visited.insert(Parent).second &&
8375 (IsRootTBAANode(Parent) || IsScalarTBAANodeImpl(Parent, Visited));
8376}
8377
8378bool TBAAVerifier::isValidScalarTBAANode(const MDNode *MD) {
8379 auto ResultIt = TBAAScalarNodes.find(MD);
8380 if (ResultIt != TBAAScalarNodes.end())
8381 return ResultIt->second;
8382
8383 SmallPtrSet<const MDNode *, 4> Visited;
8384 bool Result = IsScalarTBAANodeImpl(MD, Visited);
8385 auto InsertResult = TBAAScalarNodes.insert({MD, Result});
8386 (void)InsertResult;
8387 assert(InsertResult.second && "Just checked!");
8388
8389 return Result;
8390}
8391
8392/// Returns the field node at the offset \p Offset in \p BaseNode. Update \p
8393/// Offset in place to be the offset within the field node returned.
8394///
8395/// We assume we've okayed \p BaseNode via \c verifyTBAABaseNode.
8396MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(const Instruction *I,
8397 const MDNode *BaseNode,
8398 APInt &Offset,
8399 bool IsNewFormat) {
8400 assert(BaseNode->getNumOperands() >= 2 && "Invalid base node!");
8401
8402 // Scalar nodes have only one possible "field" -- their parent in the access
8403 // hierarchy. Offset must be zero at this point, but our caller is supposed
8404 // to check that.
8405 if (BaseNode->getNumOperands() == 2)
8406 return cast<MDNode>(BaseNode->getOperand(1));
8407
8408 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
8409 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
8410 for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
8411 Idx += NumOpsPerField) {
8412 auto *OffsetEntryCI =
8413 mdconst::extract<ConstantInt>(BaseNode->getOperand(Idx + 1));
8414 if (OffsetEntryCI->getValue().ugt(Offset)) {
8415 if (Idx == FirstFieldOpNo) {
8416 CheckFailed("Could not find TBAA parent in struct type node", I,
8417 BaseNode, &Offset);
8418 return nullptr;
8419 }
8420
8421 unsigned PrevIdx = Idx - NumOpsPerField;
8422 auto *PrevOffsetEntryCI =
8423 mdconst::extract<ConstantInt>(BaseNode->getOperand(PrevIdx + 1));
8424 Offset -= PrevOffsetEntryCI->getValue();
8425 return cast<MDNode>(BaseNode->getOperand(PrevIdx));
8426 }
8427 }
8428
8429 unsigned LastIdx = BaseNode->getNumOperands() - NumOpsPerField;
8430 auto *LastOffsetEntryCI = mdconst::extract<ConstantInt>(
8431 BaseNode->getOperand(LastIdx + 1));
8432 Offset -= LastOffsetEntryCI->getValue();
8433 return cast<MDNode>(BaseNode->getOperand(LastIdx));
8434}
8435
8437 if (!Type || Type->getNumOperands() < 3)
8438 return false;
8439
8440 // In the new format type nodes shall have a reference to the parent type as
8441 // its first operand.
8442 return isa_and_nonnull<MDNode>(Type->getOperand(0));
8443}
8444
8446 CheckTBAA(MD->getNumOperands() > 0, "TBAA metadata cannot have 0 operands", I,
8447 MD);
8448
8449 if (I)
8453 "This instruction shall not have a TBAA access tag!", I);
8454
8455 bool IsStructPathTBAA =
8456 isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3;
8457
8458 CheckTBAA(IsStructPathTBAA,
8459 "Old-style TBAA is no longer allowed, use struct-path TBAA instead",
8460 I);
8461
8462 MDNode *BaseNode = dyn_cast_or_null<MDNode>(MD->getOperand(0));
8463 MDNode *AccessType = dyn_cast_or_null<MDNode>(MD->getOperand(1));
8464
8465 bool IsNewFormat = isNewFormatTBAATypeNode(AccessType);
8466
8467 if (IsNewFormat) {
8468 CheckTBAA(MD->getNumOperands() == 4 || MD->getNumOperands() == 5,
8469 "Access tag metadata must have either 4 or 5 operands", I, MD);
8470 } else {
8471 CheckTBAA(MD->getNumOperands() < 5,
8472 "Struct tag metadata must have either 3 or 4 operands", I, MD);
8473 }
8474
8475 // Check the access size field.
8476 if (IsNewFormat) {
8477 auto *AccessSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
8478 MD->getOperand(3));
8479 CheckTBAA(AccessSizeNode, "Access size field must be a constant", I, MD);
8480 }
8481
8482 // Check the immutability flag.
8483 unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3;
8484 if (MD->getNumOperands() == ImmutabilityFlagOpNo + 1) {
8485 auto *IsImmutableCI = mdconst::dyn_extract_or_null<ConstantInt>(
8486 MD->getOperand(ImmutabilityFlagOpNo));
8487 CheckTBAA(IsImmutableCI,
8488 "Immutability tag on struct tag metadata must be a constant", I,
8489 MD);
8490 CheckTBAA(
8491 IsImmutableCI->isZero() || IsImmutableCI->isOne(),
8492 "Immutability part of the struct tag metadata must be either 0 or 1", I,
8493 MD);
8494 }
8495
8496 CheckTBAA(BaseNode && AccessType,
8497 "Malformed struct tag metadata: base and access-type "
8498 "should be non-null and point to Metadata nodes",
8499 I, MD, BaseNode, AccessType);
8500
8501 if (!IsNewFormat) {
8502 CheckTBAA(isValidScalarTBAANode(AccessType),
8503 "Access type node must be a valid scalar type", I, MD,
8504 AccessType);
8505 }
8506
8508 CheckTBAA(OffsetCI, "Offset must be constant integer", I, MD);
8509
8510 APInt Offset = OffsetCI->getValue();
8511 bool SeenAccessTypeInPath = false;
8512
8513 SmallPtrSet<MDNode *, 4> StructPath;
8514
8515 for (/* empty */; BaseNode && !IsRootTBAANode(BaseNode);
8516 BaseNode =
8517 getFieldNodeFromTBAABaseNode(I, BaseNode, Offset, IsNewFormat)) {
8518 if (!StructPath.insert(BaseNode).second) {
8519 CheckFailed("Cycle detected in struct path", I, MD);
8520 return false;
8521 }
8522
8523 bool Invalid;
8524 unsigned BaseNodeBitWidth;
8525 std::tie(Invalid, BaseNodeBitWidth) =
8526 verifyTBAABaseNode(I, BaseNode, IsNewFormat);
8527
8528 // If the base node is invalid in itself, then we've already printed all the
8529 // errors we wanted to print.
8530 if (Invalid)
8531 return false;
8532
8533 SeenAccessTypeInPath |= BaseNode == AccessType;
8534
8535 if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType)
8536 CheckTBAA(Offset == 0, "Offset not zero at the point of scalar access", I,
8537 MD, &Offset);
8538
8539 CheckTBAA(BaseNodeBitWidth == Offset.getBitWidth() ||
8540 (BaseNodeBitWidth == 0 && Offset == 0) ||
8541 (IsNewFormat && BaseNodeBitWidth == ~0u),
8542 "Access bit-width not the same as description bit-width", I, MD,
8543 BaseNodeBitWidth, Offset.getBitWidth());
8544
8545 if (IsNewFormat && SeenAccessTypeInPath)
8546 break;
8547 }
8548
8549 CheckTBAA(SeenAccessTypeInPath, "Did not see access type in access path!", I,
8550 MD);
8551 return true;
8552}
8553
8554char VerifierLegacyPass::ID = 0;
8555INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
8556
8558 return new VerifierLegacyPass(FatalErrors);
8559}
8560
8561AnalysisKey VerifierAnalysis::Key;
8568
8573
8575 auto Res = AM.getResult<VerifierAnalysis>(M);
8576 if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken))
8577 report_fatal_error("Broken module found, compilation aborted!");
8578
8579 return PreservedAnalyses::all();
8580}
8581
8583 auto res = AM.getResult<VerifierAnalysis>(F);
8584 if (res.IRBroken && FatalErrors)
8585 report_fatal_error("Broken function found, compilation aborted!");
8586
8587 return PreservedAnalyses::all();
8588}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU address space definition.
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Atomic ordering constants.
@ RetAttr
@ FnAttr
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file declares the LLVM IR specialization of the GenericConvergenceVerifier template.
static DISubprogram * getSubprogram(bool IsDistinct, Ts &&...Args)
dxil translate DXIL Translate Metadata
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
static bool runOnFunction(Function &F, bool PostInlining)
This file contains the declarations of entities that describe floating point environment and related ...
#define Check(C,...)
Hexagon Common GEP
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
static constexpr Value * getValue(Ty &ValueOrUse)
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
This file provides utility for Memory Model Relaxation Annotations (MMRAs).
static bool isContiguous(const ConstantRange &A, const ConstantRange &B)
This file contains the declarations for metadata subclasses.
#define T
#define T1
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t High
uint64_t IntrinsicInst * II
#define P(N)
ppc ctr loops verify
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
static unsigned getNumElements(Type *Ty)
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
This file contains some templates that are useful if you are working with the STL at all.
verify safepoint Safepoint IR Verifier
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static bool IsScalarTBAANodeImpl(const MDNode *MD, SmallPtrSetImpl< const MDNode * > &Visited)
static bool isType(const Metadata *MD)
static Instruction * getSuccPad(Instruction *Terminator)
static bool isMDTuple(const Metadata *MD)
static bool isNewFormatTBAATypeNode(llvm::MDNode *Type)
#define CheckDI(C,...)
We know that a debug info condition should be true, if not print an error message.
Definition Verifier.cpp:692
static void forEachUser(const Value *User, SmallPtrSet< const Value *, 32 > &Visited, llvm::function_ref< bool(const Value *)> Callback)
Definition Verifier.cpp:733
static bool isDINode(const Metadata *MD)
static bool isScope(const Metadata *MD)
static cl::opt< bool > VerifyNoAliasScopeDomination("verify-noalias-scope-decl-dom", cl::Hidden, cl::init(false), cl::desc("Ensure that llvm.experimental.noalias.scope.decl for identical " "scopes are not dominating"))
static bool isTypeCongruent(Type *L, Type *R)
Two types are "congruent" if they are identical, or if they are both pointer types with different poi...
#define CheckTBAA(C,...)
static bool isConstantIntMetadataOperand(const Metadata *MD)
static bool IsRootTBAANode(const MDNode *MD)
static Value * getParentPad(Value *EHPad)
static bool hasConflictingReferenceFlags(unsigned Flags)
Detect mutually exclusive flags.
static AttrBuilder getParameterABIAttributes(LLVMContext &C, unsigned I, AttributeList Attrs)
static const char PassName[]
static LLVM_ABI bool isValidArbitraryFPFormat(StringRef Format)
Returns true if the given string is a valid arbitrary floating-point format interpretation for llvm....
Definition APFloat.cpp:6012
bool isFiniteNonZero() const
Definition APFloat.h:1548
bool isNegative() const
Definition APFloat.h:1538
const fltSemantics & getSemantics() const
Definition APFloat.h:1546
Class for arbitrary precision integers.
Definition APInt.h:78
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1208
bool isMinValue() const
Determine if this is the smallest unsigned value.
Definition APInt.h:418
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1157
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:441
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1585
bool isMaxValue() const
Determine if this is the largest unsigned value.
Definition APInt.h:400
This class represents a conversion between pointers from one address space to another.
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
LLVM_ABI bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
unsigned getAddressSpace() const
Return the address space for the allocation.
LLVM_ABI bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1.
const Value * getArraySize() const
Get the number of elements allocated.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
void setPreservesAll()
Set by analyses that do not transform their input at all.
LLVM_ABI bool hasInRegAttr() const
Return true if this argument has the inreg attribute.
Definition Function.cpp:292
bool isElementwise() const
Return true if this RMW has elementwise vector semantics.
static bool isFPOperation(BinOp Op)
BinOp getOperation() const
static LLVM_ABI StringRef getOperationName(BinOp Op)
AtomicOrdering getOrdering() const
Returns the ordering constraint of this rmw instruction.
bool contains(Attribute::AttrKind A) const
Return true if the builder has the specified attribute.
LLVM_ABI bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
LLVM_ABI std::string getAsString(bool InAttrGrp=false) const
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:105
LLVM_ABI const ConstantRange & getValueAsConstantRange() const
Return the attribute's value as a ConstantRange.
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:124
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:261
LLVM_ABI Type * getValueAsType() const
Return the attribute's value as a Type.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:461
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:530
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI bool isEntryBlock() const
Return true if this is the entry block of the containing function.
const Instruction & front() const
Definition BasicBlock.h:484
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
This class represents a no-op cast from one type to another.
static LLVM_ABI BlockAddress * lookup(const BasicBlock *BB)
Lookup an existing BlockAddress constant for the given BasicBlock.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
bool isInlineAsm() const
Check if this call is an inline asm statement.
bool hasInAllocaArgument() const
Determine if there are is an inalloca argument.
OperandBundleUse getOperandBundleAt(unsigned Index) const
Return the operand bundle at a specific index.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool doesNotAccessMemory(unsigned OpNo) const
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
bool hasRetAttr(Attribute::AttrKind Kind) const
Determine whether the return value has the given attribute.
unsigned getNumOperandBundles() const
Return the number of operand bundles associated with this User.
CallingConv::ID getCallingConv() const
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
Attribute getParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Get the attribute of a given kind from a given arg.
iterator_range< bundle_op_iterator > bundle_op_infos()
Return the range [bundle_op_info_begin, bundle_op_info_end).
unsigned countOperandBundlesOfType(StringRef Name) const
Return the number of operand bundles with the tag Name attached to this instruction.
bool onlyReadsMemory(unsigned OpNo) const
Value * getCalledOperand() const
Type * getParamElementType(unsigned ArgNo) const
Extract the elementtype type for a parameter.
Value * getArgOperand(unsigned i) const
FunctionType * getFunctionType() const
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
bool doesNotReturn() const
Determine if the call cannot return.
LLVM_ABI bool onlyAccessesArgMemory() const
Determine if the call can access memmory only using pointers based on its arguments.
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
bool hasOperandBundles() const
Return true if this User has any operand bundles.
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
BasicBlock * getIndirectDest(unsigned i) const
unsigned getNumIndirectDests() const
Return the number of callbr indirect dest labels.
bool isMustTailCall() const
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
unsigned getNumHandlers() const
return the number of 'handlers' in this catchswitch instruction, except the default handler
Value * getParentPad() const
BasicBlock * getUnwindDest() const
handler_range handlers()
iteration adapter for range-for loops.
BasicBlock * getUnwindDest() const
bool isFPPredicate() const
Definition InstrTypes.h:845
bool isIntPredicate() const
Definition InstrTypes.h:846
static bool isIntPredicate(Predicate P)
Definition InstrTypes.h:839
Value * getCondition() const
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
Definition Constants.h:231
bool isNegative() const
Definition Constants.h:214
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
Constant * getAddrDiscriminator() const
The address discriminator if any, or the null constant.
Definition Constants.h:1258
Constant * getPointer() const
The pointer that is signed in this ptrauth signed pointer.
Definition Constants.h:1245
ConstantInt * getKey() const
The Key ID, an i32 constant.
Definition Constants.h:1248
Constant * getDeactivationSymbol() const
Definition Constants.h:1267
ConstantInt * getDiscriminator() const
The integer discriminator, an i64 constant, or 0.
Definition Constants.h:1251
static LLVM_ABI bool isOrderedRanges(ArrayRef< ConstantRange > RangesRef)
This class represents a range of values.
const APInt & getLower() const
Return the lower value for this range.
const APInt & getUpper() const
Return the upper value for this range.
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
static LLVM_ABI ConstantTokenNone * get(LLVMContext &Context)
Return the ConstantTokenNone.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:64
LLVM_ABI std::optional< fp::ExceptionBehavior > getExceptionBehavior() const
LLVM_ABI std::optional< RoundingMode > getRoundingMode() const
LLVM_ABI unsigned getNonMetadataArgCount() const
DbgVariableFragmentInfo FragmentInfo
@ FixedPointBinary
Scale factor 2^Factor.
@ FixedPointDecimal
Scale factor 10^Factor.
@ FixedPointRational
Arbitrary rational scale factor.
DIGlobalVariable * getVariable() const
LLVM_ABI DISubprogram * getSubprogram() const
Get the subprogram for this scope.
DILocalScope * getScope() const
Get the local scope for this variable.
Metadata * getRawScope() const
Base class for scope-like contexts.
Subprogram description. Uses SubclassData1.
static const DIScope * getRawRetainedNodeScope(const MDNode *N)
Base class for template parameters.
Base class for types.
Base class for variables.
Metadata * getRawType() const
Metadata * getRawScope() const
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Records a position in IR for a source label (DILabel).
Base class for non-instruction debug metadata records that have positions within IR.
LLVM_ABI void print(raw_ostream &O, bool IsForDebug=false) const
DebugLoc getDebugLoc() const
LLVM_ABI const BasicBlock * getParent() const
LLVM_ABI Function * getFunction()
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LLVM_ABI Value * getVariableLocationOp(unsigned OpIdx) const
DIExpression * getExpression() const
DILocalVariable * getVariable() const
Metadata * getRawLocation() const
Returns the metadata operand for the first location description.
@ End
Marks the end of the concrete types.
@ Any
To indicate all LocationTypes in searches.
DIExpression * getAddressExpression() const
LLVM_ABI MDNode * getAsMDNode() const
Return this as a bar MDNode.
Definition DebugLoc.cpp:73
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:252
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:225
bool empty() const
Definition DenseMap.h:173
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:286
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:155
This instruction extracts a single (scalar) element from a VectorType value.
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *Idx)
Return true if an extractelement instruction can be formed with the specified operands.
ArrayRef< unsigned > getIndices() const
static LLVM_ABI Type * getIndexedType(Type *Agg, ArrayRef< unsigned > Idxs)
Returns the type of the element that would be extracted with an extractvalue instruction with the spe...
This instruction compares its operands according to the predicate given to the constructor.
This class represents an extension of floating point types.
static bool isSupportedFloatingPointType(Type *Ty)
Returns true if Ty is a supported floating-point type for phi, select, or call FPMathOperators.
Definition Operator.h:302
This class represents a cast from floating point to signed integer.
This class represents a cast from floating point to unsigned integer.
This class represents a truncation of floating point types.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this fence instruction.
op_range arg_operands()
arg_operands - iteration adapter for range-for loops.
Value * getParentPad() const
Convenience accessors.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
Type * getReturnType() const
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:211
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Definition Function.h:246
DISubprogram * getSubprogram() const
Get the attached subprogram.
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:272
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition Function.h:905
const Function & getFunction() const
Definition Function.h:166
const std::string & getGC() const
Definition Function.cpp:818
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:216
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
Definition Function.h:229
LLVM_ABI Value * getBasePtr() const
LLVM_ABI Value * getDerivedPtr() const
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
static bool isValidLinkage(LinkageTypes L)
Definition GlobalAlias.h:98
const Constant * getAliasee() const
Definition GlobalAlias.h:87
LLVM_ABI const Function * getResolverFunction() const
Definition Globals.cpp:688
static bool isValidLinkage(LinkageTypes L)
Definition GlobalIFunc.h:86
const Constant * getResolver() const
Definition GlobalIFunc.h:73
LLVM_ABI void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
Appends all metadata attached to this value to MDs, sorting by KindID.
bool hasComdat() const
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this GlobalObject.
bool hasExternalLinkage() const
bool isDSOLocal() const
bool isImplicitDSOLocal() const
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:337
bool hasValidDeclarationLinkage() const
LinkageTypes getLinkage() const
bool hasDefaultVisibility() const
bool hasPrivateLinkage() const
bool hasHiddenVisibility() const
bool hasExternalWeakLinkage() const
bool hasDLLImportStorageClass() const
bool hasDLLExportStorageClass() const
bool isDeclarationForLinker() const
unsigned getAddressSpace() const
Module * getParent()
Get the module that this global value is contained inside of...
PointerType * getType() const
Global values are always pointers.
LLVM_ABI bool isInterposable() const
Return true if this global's definition can be substituted with an arbitrary definition at link time ...
Definition Globals.cpp:116
bool hasComdat() const
bool hasCommonLinkage() const
bool hasGlobalUnnamedAddr() const
bool hasAppendingLinkage() const
bool hasAvailableExternallyLinkage() const
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
MaybeAlign getAlign() const
Returns the alignment of the given variable.
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
Definition Globals.cpp:569
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
This instruction compares its operands according to the predicate given to the constructor.
BasicBlock * getDestination(unsigned i)
Return the specified destination.
unsigned getNumDestinations() const
return the number of possible destinations in this indirectbr instruction.
unsigned getNumSuccessors() const
This instruction inserts a single (scalar) element into a VectorType value.
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
ArrayRef< unsigned > getIndices() const
Base class for instruction visitors.
Definition InstVisitor.h:78
void visit(Iterator Start, Iterator End)
Definition InstVisitor.h:87
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI bool isAtomic() const LLVM_READONLY
Return true if this instruction has an AtomicOrdering of unordered or higher.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
This class represents a cast from an integer to a pointer.
static LLVM_ABI bool mayLowerToFunctionCall(Intrinsic::ID IID)
Check if the intrinsic might lower into a regular function call in the course of IR transformations.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
bool isCleanup() const
Return 'true' if this landingpad instruction is a cleanup.
unsigned getNumClauses() const
Get the number of clauses for this landing pad.
bool isCatch(unsigned Idx) const
Return 'true' if the clause and index Idx is a catch clause.
bool isFilter(unsigned Idx) const
Return 'true' if the clause and index Idx is a filter clause.
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this load instruction.
Align getAlign() const
Return the alignment of the access that is being performed.
Metadata node.
Definition Metadata.h:1075
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1439
bool isTemporary() const
Definition Metadata.h:1259
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1437
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1445
bool isDistinct() const
Definition Metadata.h:1258
bool isResolved() const
Check if node is fully resolved.
Definition Metadata.h:1255
LLVMContext & getContext() const
Definition Metadata.h:1239
bool equalsStr(StringRef Str) const
Definition Metadata.h:919
Metadata * get() const
Definition Metadata.h:926
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:632
static LLVM_ABI bool isTagMD(const Metadata *MD)
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
static LLVM_ABI MetadataAsValue * getIfExists(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:118
Metadata * getMetadata() const
Definition Metadata.h:202
Root of the metadata hierarchy.
Definition Metadata.h:64
LLVM_ABI void print(raw_ostream &OS, const Module *M=nullptr, bool IsForDebug=false) const
Print.
unsigned getMetadataID() const
Definition Metadata.h:104
Manage lifetime of a slot tracker for printing IR.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
Definition Module.cpp:358
LLVM_ABI StringRef getName() const
LLVM_ABI void print(raw_ostream &ROS, bool IsForDebug=false) const
LLVM_ABI unsigned getNumOperands() const
iterator_range< op_iterator > operands()
Definition Metadata.h:1851
op_range incoming_values()
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
This class represents a cast from a pointer to an address (non-capturing ptrtoint).
This class represents a cast from a pointer to an integer.
Value * getValue() const
Convenience accessor.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
This class represents a sign extension of integer types.
This class represents a cast from signed integer to floating point.
static LLVM_ABI const char * areInvalidOperands(Value *Cond, Value *True, Value *False)
Return a string if the specified operands are invalid for a select operation, otherwise return null.
This instruction constructs a fixed permutation of two input vectors.
static LLVM_ABI bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
static LLVM_ABI void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void reserve(size_type N)
iterator insert(iterator I, T &&Elt)
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:730
static constexpr size_t npos
Definition StringRef.h:58
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition StringRef.h:490
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
std::pair< typename Base::iterator, bool > insert(StringRef key)
Definition StringSet.h:39
unsigned getNumElements() const
Random access to the elements.
LLVM_ABI Type * getTypeAtIndex(const Value *V) const
Given an index value into the type, return the type of the element.
Definition Type.cpp:784
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Returns true if this struct contains a scalable vector.
Definition Type.cpp:506
Verify that the TBAA Metadatas are valid.
Definition Verifier.h:40
LLVM_ABI bool visitTBAAMetadata(const Instruction *I, const MDNode *MD)
Visit an instruction, or a TBAA node itself as part of a metadata, and return true if it is valid,...
unsigned size() const
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:47
This class represents a truncation of integer types.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isByteTy() const
True if this is an instance of ByteType.
Definition Type.h:242
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
LLVM_ABI bool containsNonGlobalTargetExtType(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this type is or contains a target extension type that disallows being used as a global...
Definition Type.cpp:74
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition Type.h:279
LLVM_ABI bool containsNonLocalTargetExtType(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this type is or contains a target extension type that disallows being used as a local.
Definition Type.cpp:90
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this is a type whose size is a known multiple of vscale.
Definition Type.cpp:61
bool isLabelTy() const
Return true if this is 'label'.
Definition Type.h:230
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:263
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
LLVM_ABI bool isTokenLikeTy() const
Returns true if this is 'token' or a token-like target type.s.
Definition Type.cpp:1140
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
Definition Type.h:311
LLVM_ABI bool canLosslesslyBitCastTo(Type *Ty) const
Return true if this type could be converted with a lossless BitCast to type 'Ty'.
Definition Type.cpp:153
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition Type.h:326
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:285
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:270
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:227
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
bool isMetadataTy() const
Return true if this is 'metadata'.
Definition Type.h:233
This class represents a cast unsigned integer to floating point.
op_range operands()
Definition User.h:267
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
Value * getValue() const
Definition Metadata.h:499
LLVM Value Representation.
Definition Value.h:75
iterator_range< user_iterator > materialized_users()
Definition Value.h:420
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI const Value * stripPointerCastsAndAliases() const
Strip off pointer casts, all-zero GEPs, address space casts, and aliases.
Definition Value.cpp:716
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
LLVM_ABI const Value * stripInBoundsOffsets(function_ref< void(const Value *)> Func=[](const Value *) {}) const
Strip off pointer casts and inbounds GEPs.
Definition Value.cpp:823
iterator_range< user_iterator > users()
Definition Value.h:426
bool materialized_use_empty() const
Definition Value.h:351
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:712
bool hasName() const
Definition Value.h:261
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:318
Check a module for errors, and report separate error states for IR and debug info errors.
Definition Verifier.h:109
LLVM_ABI Result run(Module &M, ModuleAnalysisManager &)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
This class represents zero extension of integer types.
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:212
constexpr bool isNonZero() const
Definition TypeSize.h:155
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
CallInst * Call
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ FLAT_ADDRESS
Address space for flat memory.
@ GLOBAL_ADDRESS
Address space for global memory (RAT0, VTX0).
@ PRIVATE_ADDRESS
Address space for private memory.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
bool isFlatGlobalAddrSpace(unsigned AS)
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ Entry
Definition COFF.h:862
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI bool hasConstrainedFPRoundingModeOperand(ID QID)
Returns true if the intrinsic ID is for one of the "ConstrainedFloating-Point Intrinsics" that take r...
LLVM_ABI StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
static const int NoAliasScopeDeclScopeArg
Definition Intrinsics.h:42
LLVM_ABI bool isSignatureValid(Intrinsic::ID ID, FunctionType *FT, SmallVectorImpl< Type * > &OverloadTys, raw_ostream &OS=nulls())
Returns true if FT is a valid function type for intrinsic ID.
std::variant< std::monostate, Loc::Single, Loc::Multi, Loc::MMI, Loc::EntryValue > Variant
Alias for the std::variant specialization base class of DbgVariable.
Definition DwarfDebug.h:190
Flag
These should be considered private to the implementation of the MCInstrDesc class.
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h:58
LLVM_ABI std::optional< VFInfo > tryDemangleForVFABI(StringRef MangledName, const FunctionType *FTy)
Function to construct a VFInfo out of a mangled names in the following format:
@ CE
Windows NT (Windows on ARM)
Definition MCAsmInfo.h:50
LLVM_ABI AssignmentInstRange getAssignmentInsts(DIAssignID *ID)
Return a range of instructions (typically just one) that have ID as an attachment.
initializer< Ty > init(const Ty &Val)
@ DW_LLVM_LANG_DIALECT_max
Definition Dwarf.h:212
@ DW_MACINFO_undef
Definition Dwarf.h:824
@ DW_MACINFO_start_file
Definition Dwarf.h:825
@ DW_MACINFO_define
Definition Dwarf.h:823
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract_or_null(Y &&MD)
Extract a Value from Metadata, if any, allowing null.
Definition Metadata.h:709
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)
Extract a Value from Metadata, allowing null.
Definition Metadata.h:683
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
Definition Metadata.h:696
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:668
@ User
could "use" a pointer
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
@ Offset
Definition DWP.cpp:558
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1738
LLVM_ABI bool canInstructionHaveMMRAs(const Instruction &I)
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
Definition STLExtras.h:840
LLVM_ABI unsigned getBranchWeightOffset(const MDNode *ProfileData)
Return the offset to the first branch weight data.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:165
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2553
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
AllocFnKind
Definition Attributes.h:53
testing::Matcher< const detail::ErrorHolder & > Failed()
Definition Error.h:198
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2207
LLVM_ABI DenseMap< BasicBlock *, ColorVector > colorEHFunclets(Function &F)
If an EH funclet personality is in use (see isFuncletEHPersonality), this will recompute which blocks...
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:243
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:284
gep_type_iterator gep_type_end(const User *GEP)
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
Op::Description Desc
bool isScopedEHPersonality(EHPersonality Pers)
Returns true if this personality uses scope-style EH IR instructions: catchswitch,...
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
GenericConvergenceVerifier< SSAContext > ConvergenceVerifier
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:279
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1635
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
generic_gep_type_iterator<> gep_type_iterator
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
iterator_range< SplittingIterator > split(StringRef Str, StringRef Separator)
Split the specified string over a separator and return a range-compatible iterable over its partition...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI bool isValueProfileMD(const MDNode *ProfileData)
Checks if an MDNode contains value profiling Metadata.
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_ABI unsigned getNumBranchWeights(const MDNode &ProfileData)
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
LLVM_ABI FunctionPass * createVerifierPass(bool FatalErrors=true)
FunctionAddr VTableAddr Next
Definition InstrProf.h:141
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
TinyPtrVector< BasicBlock * > ColorVector
LLVM_ABI const char * LLVMLoopEstimatedTripCount
Profile-based loop metadata that should be accessed only by using llvm::getLoopEstimatedTripCount and...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI std::optional< RoundingMode > convertStrToRoundingMode(StringRef)
Returns a valid RoundingMode enumerator when given a string that is valid as input in constrained int...
Definition FPEnv.cpp:25
gep_type_iterator gep_type_begin(const User *GEP)
LLVM_ABI std::unique_ptr< GCStrategy > getGCStrategy(const StringRef Name)
Lookup the GCStrategy object associated with the given gc name.
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1946
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
bool isHexDigit(char C)
Checks if character C is a hexadecimal numeric character.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
constexpr bool isCallableCC(CallingConv::ID CC)
LLVM_ABI bool verifyModule(const Module &M, raw_ostream *OS=nullptr, bool *BrokenDebugInfo=nullptr)
Check a module for errors.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
#define N
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:77
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
static LLVM_ABI const char * SyntheticFunctionEntryCount
static LLVM_ABI const char * UnknownBranchWeightsMarker
static LLVM_ABI const char * ValueProfile
static LLVM_ABI const char * FunctionEntryCount
static LLVM_ABI const char * BranchWeights
uint32_t getTagID() const
Return the tag of this operand bundle as an integer.
ArrayRef< Use > Inputs
void DebugInfoCheckFailed(const Twine &Message)
A debug info check failed.
Definition Verifier.cpp:309
VerifierSupport(raw_ostream *OS, const Module &M)
Definition Verifier.cpp:158
bool Broken
Track the brokenness of the module while recursively visiting.
Definition Verifier.cpp:152
void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs)
A check failed (with values to print).
Definition Verifier.cpp:302
bool BrokenDebugInfo
Broken debug info can be "recovered" from by stripping the debug info.
Definition Verifier.cpp:154
LLVMContext & Context
Definition Verifier.cpp:149
bool TreatBrokenDebugInfoAsError
Whether to treat broken debug info as an error.
Definition Verifier.cpp:156
void CheckFailed(const Twine &Message)
A check failed, so printout out the condition and the message.
Definition Verifier.cpp:291
const Module & M
Definition Verifier.cpp:145
const DataLayout & DL
Definition Verifier.cpp:148
void DebugInfoCheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs)
A debug info check failed (with values to print).
Definition Verifier.cpp:318
const Triple & TT
Definition Verifier.cpp:147
ModuleSlotTracker MST
Definition Verifier.cpp:146