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