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