LLVM 23.0.0git
Verifier.cpp
Go to the documentation of this file.
1//===-- Verifier.cpp - Implement the Module Verifier -----------------------==//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the function verifier interface, that can be used for some
10// basic correctness checking of input to the system.
11//
12// Note that this does not provide full `Java style' security and verifications,
13// instead it just tries to ensure that code is well-formed.
14//
15// * Both of a binary operator's parameters are of the same type
16// * Verify that the indices of mem access instructions match other operands
17// * Verify that arithmetic and other things are only performed on first-class
18// types. Verify that shifts & logicals only happen on integrals f.e.
19// * All of the constants in a switch statement are of the correct type
20// * The code is in valid SSA form
21// * It should be illegal to put a label into any other type (like a structure)
22// or to return one. [except constant arrays!]
23// * Only phi nodes can be self referential: 'add i32 %0, %0 ; <int>:0' is bad
24// * PHI nodes must have an entry for each predecessor, with no extras.
25// * PHI nodes must be the first thing in a basic block, all grouped together
26// * All basic blocks should only end with terminator insts, not contain them
27// * The entry node to a function must not have predecessors
28// * All Instructions must be embedded into a basic block
29// * Functions cannot take a void-typed parameter
30// * Verify that a function's argument list agrees with it's declared type.
31// * It is illegal to specify a name for a void value.
32// * It is illegal to have a internal global value with no initializer
33// * It is illegal to have a ret instruction that returns a value that does not
34// agree with the function return value type.
35// * Function call argument types match the function prototype
36// * A landing pad is defined by a landingpad instruction, and can be jumped to
37// only by the unwind edge of an invoke instruction.
38// * A landingpad instruction must be the first non-PHI instruction in the
39// block.
40// * Landingpad instructions must be in a function with a personality function.
41// * Convergence control intrinsics are introduced in ConvergentOperations.rst.
42// The applied restrictions are too numerous to list here.
43// * The convergence entry intrinsic and the loop heart must be the first
44// non-PHI instruction in their respective block. This does not conflict with
45// the landing pads, since these two kinds cannot occur in the same block.
46// * All other things that are tested by asserts spread about the code...
47//
48//===----------------------------------------------------------------------===//
49
50#include "llvm/IR/Verifier.h"
51#include "llvm/ADT/APFloat.h"
52#include "llvm/ADT/APInt.h"
53#include "llvm/ADT/ArrayRef.h"
54#include "llvm/ADT/DenseMap.h"
55#include "llvm/ADT/MapVector.h"
56#include "llvm/ADT/STLExtras.h"
60#include "llvm/ADT/StringRef.h"
61#include "llvm/ADT/Twine.h"
63#include "llvm/IR/Argument.h"
65#include "llvm/IR/Attributes.h"
66#include "llvm/IR/BasicBlock.h"
68#include "llvm/IR/CFG.h"
69#include "llvm/IR/CallingConv.h"
70#include "llvm/IR/Comdat.h"
71#include "llvm/IR/Constant.h"
74#include "llvm/IR/Constants.h"
76#include "llvm/IR/DataLayout.h"
77#include "llvm/IR/DebugInfo.h"
79#include "llvm/IR/DebugLoc.h"
81#include "llvm/IR/Dominators.h"
83#include "llvm/IR/FPEnv.h"
84#include "llvm/IR/Function.h"
85#include "llvm/IR/GCStrategy.h"
87#include "llvm/IR/GlobalAlias.h"
88#include "llvm/IR/GlobalValue.h"
90#include "llvm/IR/InlineAsm.h"
91#include "llvm/IR/InstVisitor.h"
92#include "llvm/IR/InstrTypes.h"
93#include "llvm/IR/Instruction.h"
96#include "llvm/IR/Intrinsics.h"
97#include "llvm/IR/IntrinsicsAArch64.h"
98#include "llvm/IR/IntrinsicsAMDGPU.h"
99#include "llvm/IR/IntrinsicsARM.h"
100#include "llvm/IR/IntrinsicsNVPTX.h"
101#include "llvm/IR/IntrinsicsWebAssembly.h"
102#include "llvm/IR/LLVMContext.h"
104#include "llvm/IR/Metadata.h"
105#include "llvm/IR/Module.h"
107#include "llvm/IR/PassManager.h"
109#include "llvm/IR/Statepoint.h"
110#include "llvm/IR/Type.h"
111#include "llvm/IR/Use.h"
112#include "llvm/IR/User.h"
114#include "llvm/IR/Value.h"
116#include "llvm/Pass.h"
120#include "llvm/Support/Casting.h"
124#include "llvm/Support/ModRef.h"
128#include <algorithm>
129#include <cassert>
130#include <cstdint>
131#include <memory>
132#include <optional>
133#include <queue>
134#include <string>
135#include <utility>
136
137using namespace llvm;
138
140 "verify-noalias-scope-decl-dom", cl::Hidden, cl::init(false),
141 cl::desc("Ensure that llvm.experimental.noalias.scope.decl for identical "
142 "scopes are not dominating"));
143
146 const Module &M;
148 const Triple &TT;
151
152 /// Track the brokenness of the module while recursively visiting.
153 bool Broken = false;
154 /// Broken debug info can be "recovered" from by stripping the debug info.
155 bool BrokenDebugInfo = false;
156 /// Whether to treat broken debug info as an error.
158
160 : OS(OS), M(M), MST(&M), TT(M.getTargetTriple()), DL(M.getDataLayout()),
161 Context(M.getContext()) {}
162
163private:
164 void Write(const Module *M) {
165 *OS << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
166 }
167
168 void Write(const Value *V) {
169 if (V)
170 Write(*V);
171 }
172
173 void Write(const Value &V) {
174 if (isa<Instruction>(V)) {
175 V.print(*OS, MST);
176 *OS << '\n';
177 } else {
178 V.printAsOperand(*OS, true, MST);
179 *OS << '\n';
180 }
181 }
182
183 void Write(const DbgRecord *DR) {
184 if (DR) {
185 DR->print(*OS, MST, false);
186 *OS << '\n';
187 }
188 }
189
191 switch (Type) {
193 *OS << "value";
194 break;
196 *OS << "declare";
197 break;
199 *OS << "declare_value";
200 break;
202 *OS << "assign";
203 break;
205 *OS << "end";
206 break;
208 *OS << "any";
209 break;
210 };
211 }
212
213 void Write(const Metadata *MD) {
214 if (!MD)
215 return;
216 MD->print(*OS, MST, &M);
217 *OS << '\n';
218 }
219
220 template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) {
221 Write(MD.get());
222 }
223
224 void Write(const NamedMDNode *NMD) {
225 if (!NMD)
226 return;
227 NMD->print(*OS, MST);
228 *OS << '\n';
229 }
230
231 void Write(Type *T) {
232 if (!T)
233 return;
234 *OS << ' ' << *T;
235 }
236
237 void Write(const Comdat *C) {
238 if (!C)
239 return;
240 *OS << *C;
241 }
242
243 void Write(const APInt *AI) {
244 if (!AI)
245 return;
246 *OS << *AI << '\n';
247 }
248
249 void Write(const unsigned i) { *OS << i << '\n'; }
250
251 // NOLINTNEXTLINE(readability-identifier-naming)
252 void Write(const Attribute *A) {
253 if (!A)
254 return;
255 *OS << A->getAsString() << '\n';
256 }
257
258 // NOLINTNEXTLINE(readability-identifier-naming)
259 void Write(const AttributeSet *AS) {
260 if (!AS)
261 return;
262 *OS << AS->getAsString() << '\n';
263 }
264
265 // NOLINTNEXTLINE(readability-identifier-naming)
266 void Write(const AttributeList *AL) {
267 if (!AL)
268 return;
269 AL->print(*OS);
270 }
271
272 void Write(Printable P) { *OS << P << '\n'; }
273
274 template <typename T> void Write(ArrayRef<T> Vs) {
275 for (const T &V : Vs)
276 Write(V);
277 }
278
279 template <typename T1, typename... Ts>
280 void WriteTs(const T1 &V1, const Ts &... Vs) {
281 Write(V1);
282 WriteTs(Vs...);
283 }
284
285 template <typename... Ts> void WriteTs() {}
286
287public:
288 /// A check failed, so printout out the condition and the message.
289 ///
290 /// This provides a nice place to put a breakpoint if you want to see why
291 /// something is not correct.
292 void CheckFailed(const Twine &Message) {
293 if (OS)
294 *OS << Message << '\n';
295 Broken = true;
296 }
297
298 /// A check failed (with values to print).
299 ///
300 /// This calls the Message-only version so that the above is easier to set a
301 /// breakpoint on.
302 template <typename T1, typename... Ts>
303 void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
304 CheckFailed(Message);
305 if (OS)
306 WriteTs(V1, Vs...);
307 }
308
309 /// A debug info check failed.
310 void DebugInfoCheckFailed(const Twine &Message) {
311 if (OS)
312 *OS << Message << '\n';
314 BrokenDebugInfo = true;
315 }
316
317 /// A debug info check failed (with values to print).
318 template <typename T1, typename... Ts>
319 void DebugInfoCheckFailed(const Twine &Message, const T1 &V1,
320 const Ts &... Vs) {
321 DebugInfoCheckFailed(Message);
322 if (OS)
323 WriteTs(V1, Vs...);
324 }
325};
326
327namespace {
328
329class Verifier : public InstVisitor<Verifier>, VerifierSupport {
330 friend class InstVisitor<Verifier>;
331 DominatorTree DT;
332
333 /// When verifying a basic block, keep track of all of the
334 /// instructions we have seen so far.
335 ///
336 /// This allows us to do efficient dominance checks for the case when an
337 /// instruction has an operand that is an instruction in the same block.
338 SmallPtrSet<Instruction *, 16> InstsInThisBlock;
339
340 /// Keep track of the metadata nodes that have been checked already.
342
343 /// Keep track which DISubprogram is attached to which function.
345
346 /// Track all DICompileUnits visited.
348
349 /// The result type for a landingpad.
350 Type *LandingPadResultTy;
351
352 /// Whether we've seen a call to @llvm.localescape in this function
353 /// already.
354 bool SawFrameEscape;
355
356 /// Whether the current function has a DISubprogram attached to it.
357 bool HasDebugInfo = false;
358
359 /// Stores the count of how many objects were passed to llvm.localescape for a
360 /// given function and the largest index passed to llvm.localrecover.
362
363 // Maps catchswitches and cleanuppads that unwind to siblings to the
364 // terminators that indicate the unwind, used to detect cycles therein.
366
367 /// Cache which blocks are in which funclet, if an EH funclet personality is
368 /// in use. Otherwise empty.
369 DenseMap<BasicBlock *, ColorVector> BlockEHFuncletColors;
370
371 /// Cache of constants visited in search of ConstantExprs.
372 SmallPtrSet<const Constant *, 32> ConstantExprVisited;
373
374 /// Cache of declarations of the llvm.experimental.deoptimize.<ty> intrinsic.
375 SmallVector<const Function *, 4> DeoptimizeDeclarations;
376
377 /// Cache of attribute lists verified.
378 SmallPtrSet<const void *, 32> AttributeListsVisited;
379
380 // Verify that this GlobalValue is only used in this module.
381 // This map is used to avoid visiting uses twice. We can arrive at a user
382 // twice, if they have multiple operands. In particular for very large
383 // constant expressions, we can arrive at a particular user many times.
384 SmallPtrSet<const Value *, 32> GlobalValueVisited;
385
386 // Keeps track of duplicate function argument debug info.
388
389 TBAAVerifier TBAAVerifyHelper;
390 ConvergenceVerifier ConvergenceVerifyHelper;
391
392 SmallVector<IntrinsicInst *, 4> NoAliasScopeDecls;
393
394 void checkAtomicMemAccessSize(Type *Ty, const Instruction *I);
395
396public:
397 explicit Verifier(raw_ostream *OS, bool ShouldTreatBrokenDebugInfoAsError,
398 const Module &M)
399 : VerifierSupport(OS, M), LandingPadResultTy(nullptr),
400 SawFrameEscape(false), TBAAVerifyHelper(this) {
401 TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
402 }
403
404 bool hasBrokenDebugInfo() const { return BrokenDebugInfo; }
405
406 bool verify(const Function &F) {
407 llvm::TimeTraceScope timeScope("Verifier");
408 assert(F.getParent() == &M &&
409 "An instance of this class only works with a specific module!");
410
411 // First ensure the function is well-enough formed to compute dominance
412 // information, and directly compute a dominance tree. We don't rely on the
413 // pass manager to provide this as it isolates us from a potentially
414 // out-of-date dominator tree and makes it significantly more complex to run
415 // this code outside of a pass manager.
416
417 // First check that every basic block has a terminator, otherwise we can't
418 // even inspect the CFG.
419 for (const BasicBlock &BB : F) {
420 if (!BB.empty() && BB.back().isTerminator())
421 continue;
422
423 if (OS) {
424 *OS << "Basic Block in function '" << F.getName()
425 << "' does not have terminator!\n";
426 BB.printAsOperand(*OS, true, MST);
427 *OS << "\n";
428 }
429 return false;
430 }
431
432 // FIXME: It's really gross that we have to cast away constness here.
433 if (!F.empty())
434 DT.recalculate(const_cast<Function &>(F));
435
436 auto FailureCB = [this](const Twine &Message) {
437 this->CheckFailed(Message);
438 };
439 ConvergenceVerifyHelper.initialize(OS, FailureCB, F);
440
441 Broken = false;
442 // FIXME: We strip const here because the inst visitor strips const.
443 visit(const_cast<Function &>(F));
444 verifySiblingFuncletUnwinds();
445
446 if (ConvergenceVerifyHelper.sawTokens())
447 ConvergenceVerifyHelper.verify(DT);
448
449 InstsInThisBlock.clear();
450 DebugFnArgs.clear();
451 LandingPadResultTy = nullptr;
452 SawFrameEscape = false;
453 SiblingFuncletInfo.clear();
454 verifyNoAliasScopeDecl();
455 NoAliasScopeDecls.clear();
456
457 return !Broken;
458 }
459
460 /// Verify the module that this instance of \c Verifier was initialized with.
461 bool verify() {
462 Broken = false;
463
464 // Collect all declarations of the llvm.experimental.deoptimize intrinsic.
465 for (const Function &F : M)
466 if (F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
467 DeoptimizeDeclarations.push_back(&F);
468
469 // Now that we've visited every function, verify that we never asked to
470 // recover a frame index that wasn't escaped.
471 verifyFrameRecoverIndices();
472 for (const GlobalVariable &GV : M.globals())
473 visitGlobalVariable(GV);
474
475 for (const GlobalAlias &GA : M.aliases())
476 visitGlobalAlias(GA);
477
478 for (const GlobalIFunc &GI : M.ifuncs())
479 visitGlobalIFunc(GI);
480
481 for (const NamedMDNode &NMD : M.named_metadata())
482 visitNamedMDNode(NMD);
483
484 for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
485 visitComdat(SMEC.getValue());
486
487 visitModuleFlags();
488 visitModuleIdents();
489 visitModuleCommandLines();
490 visitModuleErrnoTBAA();
491
492 verifyCompileUnits();
493
494 verifyDeoptimizeCallingConvs();
495 DISubprogramAttachments.clear();
496 return !Broken;
497 }
498
499private:
500 /// Whether a metadata node is allowed to be, or contain, a DILocation.
501 enum class AreDebugLocsAllowed { No, Yes };
502
503 /// Metadata that should be treated as a range, with slightly different
504 /// requirements.
505 enum class RangeLikeMetadataKind {
506 Range, // MD_range
507 AbsoluteSymbol, // MD_absolute_symbol
508 NoaliasAddrspace // MD_noalias_addrspace
509 };
510
511 // Verification methods...
512 void visitGlobalValue(const GlobalValue &GV);
513 void visitGlobalVariable(const GlobalVariable &GV);
514 void visitGlobalAlias(const GlobalAlias &GA);
515 void visitGlobalIFunc(const GlobalIFunc &GI);
516 void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
517 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
518 const GlobalAlias &A, const Constant &C);
519 void visitNamedMDNode(const NamedMDNode &NMD);
520 void visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs);
521 void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
522 void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
523 void visitDIArgList(const DIArgList &AL, Function *F);
524 void visitComdat(const Comdat &C);
525 void visitModuleIdents();
526 void visitModuleCommandLines();
527 void visitModuleErrnoTBAA();
528 void visitModuleFlags();
529 void visitModuleFlag(const MDNode *Op,
530 DenseMap<const MDString *, const MDNode *> &SeenIDs,
531 SmallVectorImpl<const MDNode *> &Requirements);
532 void visitModuleFlagCGProfileEntry(const MDOperand &MDO);
533 void visitFunction(const Function &F);
534 void visitBasicBlock(BasicBlock &BB);
535 void verifyRangeLikeMetadata(const Value &V, const MDNode *Range, Type *Ty,
536 RangeLikeMetadataKind Kind);
537 void visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty);
538 void visitNoFPClassMetadata(Instruction &I, MDNode *Range, Type *Ty);
539 void visitNoaliasAddrspaceMetadata(Instruction &I, MDNode *Range, Type *Ty);
540 void visitDereferenceableMetadata(Instruction &I, MDNode *MD);
541 void visitNofreeMetadata(Instruction &I, MDNode *MD);
542 void visitProfMetadata(Instruction &I, MDNode *MD);
543 void visitCallStackMetadata(MDNode *MD);
544 void visitMemProfMetadata(Instruction &I, MDNode *MD);
545 void visitCallsiteMetadata(Instruction &I, MDNode *MD);
546 void visitCalleeTypeMetadata(Instruction &I, MDNode *MD);
547 void visitDIAssignIDMetadata(Instruction &I, MDNode *MD);
548 void visitMMRAMetadata(Instruction &I, MDNode *MD);
549 void visitAnnotationMetadata(MDNode *Annotation);
550 void visitAliasScopeMetadata(const MDNode *MD);
551 void visitAliasScopeListMetadata(const MDNode *MD);
552 void visitAccessGroupMetadata(const MDNode *MD);
553 void visitCapturesMetadata(Instruction &I, const MDNode *Captures);
554 void visitAllocTokenMetadata(Instruction &I, MDNode *MD);
555 void visitInlineHistoryMetadata(Instruction &I, MDNode *MD);
556 void visitMemCacheHintMetadata(Instruction &I, MDNode *MD);
557
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 UpperBound = FT->getNumParams() + (FT->isVarArg() ? 1 : 0);
2733 unsigned FormatIdx;
2734 Check(!Args[1].getAsInteger(10, FormatIdx),
2735 "modular-format attribute format string index is not an integer", V);
2736 Check(FormatIdx > 0,
2737 "modular-format attribute format string index must be greater than 0",
2738 V);
2739 Check(FormatIdx <= UpperBound,
2740 "modular-format attribute format string index is out of bounds", V);
2741 unsigned FirstArgIdx;
2742 Check(!Args[2].getAsInteger(10, FirstArgIdx),
2743 "modular-format attribute first arg index is not an integer", V);
2744 Check(FirstArgIdx <= UpperBound,
2745 "modular-format attribute first arg index is out of bounds", V);
2746 Check(!Args[3].empty(),
2747 "modular-format attribute modular implementation function name "
2748 "cannot be empty",
2749 V);
2750 Check(!Args[4].empty(),
2751 "modular-format attribute implementation name cannot be empty", V);
2752 }
2753
2754 if (auto A = Attrs.getFnAttr("target-features"); A.isValid()) {
2755 StringRef S = A.getValueAsString();
2756 if (!S.empty()) {
2757 for (auto FeatureFlag : split(S, ',')) {
2758 if (FeatureFlag.empty())
2759 CheckFailed(
2760 "target-features attribute should not contain an empty string");
2761 else
2762 Check(FeatureFlag[0] == '+' || FeatureFlag[0] == '-',
2763 "target feature '" + FeatureFlag +
2764 "' must start with a '+' or '-'",
2765 V);
2766 }
2767 }
2768 }
2769}
2770void Verifier::verifyUnknownProfileMetadata(MDNode *MD) {
2771 Check(MD->getNumOperands() == 2,
2772 "'unknown' !prof should have a single additional operand", MD);
2773 auto *PassName = dyn_cast<MDString>(MD->getOperand(1));
2774 Check(PassName != nullptr,
2775 "'unknown' !prof should have an additional operand of type "
2776 "string");
2777 Check(!PassName->getString().empty(),
2778 "the 'unknown' !prof operand should not be an empty string");
2779}
2780
2781void Verifier::verifyFunctionMetadata(
2782 ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
2783 for (const auto &Pair : MDs) {
2784 if (Pair.first == LLVMContext::MD_prof) {
2785 MDNode *MD = Pair.second;
2786 Check(MD->getNumOperands() >= 2,
2787 "!prof annotations should have no less than 2 operands", MD);
2788 // We may have functions that are synthesized by the compiler, e.g. in
2789 // WPD, that we can't currently determine the entry count.
2790 if (MD->getOperand(0).equalsStr(
2792 verifyUnknownProfileMetadata(MD);
2793 continue;
2794 }
2795
2796 // Check first operand.
2797 Check(MD->getOperand(0) != nullptr, "first operand should not be null",
2798 MD);
2800 "expected string with name of the !prof annotation", MD);
2801 MDString *MDS = cast<MDString>(MD->getOperand(0));
2802 StringRef ProfName = MDS->getString();
2805 "first operand should be 'function_entry_count'"
2806 " or 'synthetic_function_entry_count'",
2807 MD);
2808
2809 // Check second operand.
2810 Check(MD->getOperand(1) != nullptr, "second operand should not be null",
2811 MD);
2813 "expected integer argument to function_entry_count", MD);
2814 } else if (Pair.first == LLVMContext::MD_kcfi_type) {
2815 MDNode *MD = Pair.second;
2816 Check(MD->getNumOperands() == 1,
2817 "!kcfi_type must have exactly one operand", MD);
2818 Check(MD->getOperand(0) != nullptr, "!kcfi_type operand must not be null",
2819 MD);
2821 "expected a constant operand for !kcfi_type", MD);
2822 Constant *C = cast<ConstantAsMetadata>(MD->getOperand(0))->getValue();
2823 Check(isa<ConstantInt>(C) && isa<IntegerType>(C->getType()),
2824 "expected a constant integer operand for !kcfi_type", MD);
2826 "expected a 32-bit integer constant operand for !kcfi_type", MD);
2827 }
2828 }
2829}
2830
2831void Verifier::visitConstantExprsRecursively(const Constant *EntryC) {
2832 if (EntryC->getNumOperands() == 0)
2833 return;
2834
2835 if (!ConstantExprVisited.insert(EntryC).second)
2836 return;
2837
2839 Stack.push_back(EntryC);
2840
2841 while (!Stack.empty()) {
2842 const Constant *C = Stack.pop_back_val();
2843
2844 // Check this constant expression.
2845 if (const auto *CE = dyn_cast<ConstantExpr>(C))
2846 visitConstantExpr(CE);
2847
2848 if (const auto *CPA = dyn_cast<ConstantPtrAuth>(C))
2849 visitConstantPtrAuth(CPA);
2850
2851 if (const auto *GV = dyn_cast<GlobalValue>(C)) {
2852 // Global Values get visited separately, but we do need to make sure
2853 // that the global value is in the correct module
2854 Check(GV->getParent() == &M, "Referencing global in another module!",
2855 EntryC, &M, GV, GV->getParent());
2856 continue;
2857 }
2858
2859 // Visit all sub-expressions.
2860 for (const Use &U : C->operands()) {
2861 const auto *OpC = dyn_cast<Constant>(U);
2862 if (!OpC)
2863 continue;
2864 if (!ConstantExprVisited.insert(OpC).second)
2865 continue;
2866 Stack.push_back(OpC);
2867 }
2868 }
2869}
2870
2871void Verifier::visitConstantExpr(const ConstantExpr *CE) {
2872 if (CE->getOpcode() == Instruction::BitCast)
2873 Check(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
2874 CE->getType()),
2875 "Invalid bitcast", CE);
2876 else if (CE->getOpcode() == Instruction::PtrToAddr)
2877 checkPtrToAddr(CE->getOperand(0)->getType(), CE->getType(), *CE);
2878}
2879
2880void Verifier::visitConstantPtrAuth(const ConstantPtrAuth *CPA) {
2881 Check(CPA->getPointer()->getType()->isPointerTy(),
2882 "signed ptrauth constant base pointer must have pointer type");
2883
2884 Check(CPA->getType() == CPA->getPointer()->getType(),
2885 "signed ptrauth constant must have same type as its base pointer");
2886
2887 Check(CPA->getKey()->getBitWidth() == 32,
2888 "signed ptrauth constant key must be i32 constant integer");
2889
2891 "signed ptrauth constant address discriminator must be a pointer");
2892
2893 Check(CPA->getDiscriminator()->getBitWidth() == 64,
2894 "signed ptrauth constant discriminator must be i64 constant integer");
2895
2897 "signed ptrauth constant deactivation symbol must be a pointer");
2898
2901 "signed ptrauth constant deactivation symbol must be a global value "
2902 "or null");
2903}
2904
2905bool Verifier::verifyAttributeCount(AttributeList Attrs, unsigned Params) {
2906 // There shouldn't be more attribute sets than there are parameters plus the
2907 // function and return value.
2908 return Attrs.getNumAttrSets() <= Params + 2;
2909}
2910
2911void Verifier::verifyInlineAsmCall(const CallBase &Call) {
2912 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
2913 unsigned ArgNo = 0;
2914 unsigned LabelNo = 0;
2915 for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
2916 if (CI.Type == InlineAsm::isLabel) {
2917 ++LabelNo;
2918 continue;
2919 }
2920
2921 // Only deal with constraints that correspond to call arguments.
2922 if (!CI.hasArg())
2923 continue;
2924
2925 if (CI.isIndirect) {
2926 const Value *Arg = Call.getArgOperand(ArgNo);
2927 Check(Arg->getType()->isPointerTy(),
2928 "Operand for indirect constraint must have pointer type", &Call);
2929
2931 "Operand for indirect constraint must have elementtype attribute",
2932 &Call);
2933 } else {
2934 Check(!Call.paramHasAttr(ArgNo, Attribute::ElementType),
2935 "Elementtype attribute can only be applied for indirect "
2936 "constraints",
2937 &Call);
2938 }
2939
2940 ArgNo++;
2941 }
2942
2943 if (auto *CallBr = dyn_cast<CallBrInst>(&Call)) {
2944 Check(LabelNo == CallBr->getNumIndirectDests(),
2945 "Number of label constraints does not match number of callbr dests",
2946 &Call);
2947 } else {
2948 Check(LabelNo == 0, "Label constraints can only be used with callbr",
2949 &Call);
2950 }
2951}
2952
2953/// Verify that statepoint intrinsic is well formed.
2954void Verifier::verifyStatepoint(const CallBase &Call) {
2955 assert(Call.getIntrinsicID() == Intrinsic::experimental_gc_statepoint);
2956
2959 "gc.statepoint must read and write all memory to preserve "
2960 "reordering restrictions required by safepoint semantics",
2961 Call);
2962
2963 const int64_t NumPatchBytes =
2964 cast<ConstantInt>(Call.getArgOperand(1))->getSExtValue();
2965 assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!");
2966 Check(NumPatchBytes >= 0,
2967 "gc.statepoint number of patchable bytes must be "
2968 "positive",
2969 Call);
2970
2971 Type *TargetElemType = Call.getParamElementType(2);
2972 Check(TargetElemType,
2973 "gc.statepoint callee argument must have elementtype attribute", Call);
2974 FunctionType *TargetFuncType = dyn_cast<FunctionType>(TargetElemType);
2975 Check(TargetFuncType,
2976 "gc.statepoint callee elementtype must be function type", Call);
2977
2978 const int NumCallArgs = cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue();
2979 Check(NumCallArgs >= 0,
2980 "gc.statepoint number of arguments to underlying call "
2981 "must be positive",
2982 Call);
2983 const int NumParams = (int)TargetFuncType->getNumParams();
2984 if (TargetFuncType->isVarArg()) {
2985 Check(NumCallArgs >= NumParams,
2986 "gc.statepoint mismatch in number of vararg call args", Call);
2987
2988 // TODO: Remove this limitation
2989 Check(TargetFuncType->getReturnType()->isVoidTy(),
2990 "gc.statepoint doesn't support wrapping non-void "
2991 "vararg functions yet",
2992 Call);
2993 } else
2994 Check(NumCallArgs == NumParams,
2995 "gc.statepoint mismatch in number of call args", Call);
2996
2997 const uint64_t Flags
2998 = cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue();
2999 Check((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
3000 "unknown flag used in gc.statepoint flags argument", Call);
3001
3002 // Verify that the types of the call parameter arguments match
3003 // the type of the wrapped callee.
3004 AttributeList Attrs = Call.getAttributes();
3005 for (int i = 0; i < NumParams; i++) {
3006 Type *ParamType = TargetFuncType->getParamType(i);
3007 Type *ArgType = Call.getArgOperand(5 + i)->getType();
3008 Check(ArgType == ParamType,
3009 "gc.statepoint call argument does not match wrapped "
3010 "function type",
3011 Call);
3012
3013 if (TargetFuncType->isVarArg()) {
3014 AttributeSet ArgAttrs = Attrs.getParamAttrs(5 + i);
3015 Check(!ArgAttrs.hasAttribute(Attribute::StructRet),
3016 "Attribute 'sret' cannot be used for vararg call arguments!", Call);
3017 }
3018 }
3019
3020 const int EndCallArgsInx = 4 + NumCallArgs;
3021
3022 const Value *NumTransitionArgsV = Call.getArgOperand(EndCallArgsInx + 1);
3023 Check(isa<ConstantInt>(NumTransitionArgsV),
3024 "gc.statepoint number of transition arguments "
3025 "must be constant integer",
3026 Call);
3027 const int NumTransitionArgs =
3028 cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
3029 Check(NumTransitionArgs == 0,
3030 "gc.statepoint w/inline transition bundle is deprecated", Call);
3031 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
3032
3033 const Value *NumDeoptArgsV = Call.getArgOperand(EndTransitionArgsInx + 1);
3034 Check(isa<ConstantInt>(NumDeoptArgsV),
3035 "gc.statepoint number of deoptimization arguments "
3036 "must be constant integer",
3037 Call);
3038 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
3039 Check(NumDeoptArgs == 0,
3040 "gc.statepoint w/inline deopt operands is deprecated", Call);
3041
3042 const int ExpectedNumArgs = 7 + NumCallArgs;
3043 Check(ExpectedNumArgs == (int)Call.arg_size(),
3044 "gc.statepoint too many arguments", Call);
3045
3046 // Check that the only uses of this gc.statepoint are gc.result or
3047 // gc.relocate calls which are tied to this statepoint and thus part
3048 // of the same statepoint sequence
3049 for (const User *U : Call.users()) {
3050 const CallInst *UserCall = dyn_cast<const CallInst>(U);
3051 Check(UserCall, "illegal use of statepoint token", Call, U);
3052 if (!UserCall)
3053 continue;
3054 Check(isa<GCRelocateInst>(UserCall) || isa<GCResultInst>(UserCall),
3055 "gc.result or gc.relocate are the only value uses "
3056 "of a gc.statepoint",
3057 Call, U);
3058 if (isa<GCResultInst>(UserCall)) {
3059 Check(UserCall->getArgOperand(0) == &Call,
3060 "gc.result connected to wrong gc.statepoint", Call, UserCall);
3061 } else if (isa<GCRelocateInst>(Call)) {
3062 Check(UserCall->getArgOperand(0) == &Call,
3063 "gc.relocate connected to wrong gc.statepoint", Call, UserCall);
3064 }
3065 }
3066
3067 // Note: It is legal for a single derived pointer to be listed multiple
3068 // times. It's non-optimal, but it is legal. It can also happen after
3069 // insertion if we strip a bitcast away.
3070 // Note: It is really tempting to check that each base is relocated and
3071 // that a derived pointer is never reused as a base pointer. This turns
3072 // out to be problematic since optimizations run after safepoint insertion
3073 // can recognize equality properties that the insertion logic doesn't know
3074 // about. See example statepoint.ll in the verifier subdirectory
3075}
3076
3077void Verifier::verifyFrameRecoverIndices() {
3078 for (auto &Counts : FrameEscapeInfo) {
3079 Function *F = Counts.first;
3080 unsigned EscapedObjectCount = Counts.second.first;
3081 unsigned MaxRecoveredIndex = Counts.second.second;
3082 Check(MaxRecoveredIndex <= EscapedObjectCount,
3083 "all indices passed to llvm.localrecover must be less than the "
3084 "number of arguments passed to llvm.localescape in the parent "
3085 "function",
3086 F);
3087 }
3088}
3089
3090static Instruction *getSuccPad(Instruction *Terminator) {
3091 BasicBlock *UnwindDest;
3092 if (auto *II = dyn_cast<InvokeInst>(Terminator))
3093 UnwindDest = II->getUnwindDest();
3094 else if (auto *CSI = dyn_cast<CatchSwitchInst>(Terminator))
3095 UnwindDest = CSI->getUnwindDest();
3096 else
3097 UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest();
3098 return &*UnwindDest->getFirstNonPHIIt();
3099}
3100
3101void Verifier::verifySiblingFuncletUnwinds() {
3102 llvm::TimeTraceScope timeScope("Verifier verify sibling funclet unwinds");
3103 SmallPtrSet<Instruction *, 8> Visited;
3104 SmallPtrSet<Instruction *, 8> Active;
3105 for (const auto &Pair : SiblingFuncletInfo) {
3106 Instruction *PredPad = Pair.first;
3107 if (Visited.count(PredPad))
3108 continue;
3109 Active.insert(PredPad);
3110 Instruction *Terminator = Pair.second;
3111 do {
3112 Instruction *SuccPad = getSuccPad(Terminator);
3113 if (Active.count(SuccPad)) {
3114 // Found a cycle; report error
3115 Instruction *CyclePad = SuccPad;
3116 SmallVector<Instruction *, 8> CycleNodes;
3117 do {
3118 CycleNodes.push_back(CyclePad);
3119 Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
3120 if (CycleTerminator != CyclePad)
3121 CycleNodes.push_back(CycleTerminator);
3122 CyclePad = getSuccPad(CycleTerminator);
3123 } while (CyclePad != SuccPad);
3124 Check(false, "EH pads can't handle each other's exceptions",
3125 ArrayRef<Instruction *>(CycleNodes));
3126 }
3127 // Don't re-walk a node we've already checked
3128 if (!Visited.insert(SuccPad).second)
3129 break;
3130 // Walk to this successor if it has a map entry.
3131 PredPad = SuccPad;
3132 auto TermI = SiblingFuncletInfo.find(PredPad);
3133 if (TermI == SiblingFuncletInfo.end())
3134 break;
3135 Terminator = TermI->second;
3136 Active.insert(PredPad);
3137 } while (true);
3138 // Each node only has one successor, so we've walked all the active
3139 // nodes' successors.
3140 Active.clear();
3141 }
3142}
3143
3144// visitFunction - Verify that a function is ok.
3145//
3146void Verifier::visitFunction(const Function &F) {
3147 visitGlobalValue(F);
3148
3149 // Check function arguments.
3150 FunctionType *FT = F.getFunctionType();
3151 unsigned NumArgs = F.arg_size();
3152
3153 Check(&Context == &F.getContext(),
3154 "Function context does not match Module context!", &F);
3155
3156 Check(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
3157 Check(FT->getNumParams() == NumArgs,
3158 "# formal arguments must match # of arguments for function type!", &F,
3159 FT);
3160 Check(F.getReturnType()->isFirstClassType() ||
3161 F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
3162 "Functions cannot return aggregate values!", &F);
3163
3164 Check(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
3165 "Invalid struct return type!", &F);
3166
3167 if (MaybeAlign A = F.getAlign()) {
3168 Check(A->value() <= Value::MaximumAlignment,
3169 "huge alignment values are unsupported", &F);
3170 }
3171
3172 AttributeList Attrs = F.getAttributes();
3173
3174 Check(verifyAttributeCount(Attrs, FT->getNumParams()),
3175 "Attribute after last parameter!", &F);
3176
3177 bool IsIntrinsic = F.isIntrinsic();
3178
3179 // Check function attributes.
3180 verifyFunctionAttrs(FT, Attrs, &F, IsIntrinsic, /* IsInlineAsm */ false);
3181
3182 // On function declarations/definitions, we do not support the builtin
3183 // attribute. We do not check this in VerifyFunctionAttrs since that is
3184 // checking for Attributes that can/can not ever be on functions.
3185 Check(!Attrs.hasFnAttr(Attribute::Builtin),
3186 "Attribute 'builtin' can only be applied to a callsite.", &F);
3187
3188 Check(!Attrs.hasAttrSomewhere(Attribute::ElementType),
3189 "Attribute 'elementtype' can only be applied to a callsite.", &F);
3190
3191 if (Attrs.hasFnAttr(Attribute::Naked))
3192 for (const Argument &Arg : F.args())
3193 Check(Arg.use_empty(), "cannot use argument of naked function", &Arg);
3194
3195 // Check that this function meets the restrictions on this calling convention.
3196 // Sometimes varargs is used for perfectly forwarding thunks, so some of these
3197 // restrictions can be lifted.
3198 switch (F.getCallingConv()) {
3199 default:
3200 case CallingConv::C:
3201 break;
3202 case CallingConv::X86_INTR: {
3203 Check(F.arg_empty() || Attrs.hasParamAttr(0, Attribute::ByVal),
3204 "Calling convention parameter requires byval", &F);
3205 break;
3206 }
3207 case CallingConv::AMDGPU_KERNEL:
3208 case CallingConv::SPIR_KERNEL:
3209 case CallingConv::AMDGPU_CS_Chain:
3210 case CallingConv::AMDGPU_CS_ChainPreserve:
3211 Check(F.getReturnType()->isVoidTy(),
3212 "Calling convention requires void return type", &F);
3213 [[fallthrough]];
3214 case CallingConv::AMDGPU_VS:
3215 case CallingConv::AMDGPU_HS:
3216 case CallingConv::AMDGPU_GS:
3217 case CallingConv::AMDGPU_PS:
3218 case CallingConv::AMDGPU_CS:
3219 Check(!F.hasStructRetAttr(), "Calling convention does not allow sret", &F);
3220 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3221 const unsigned StackAS = DL.getAllocaAddrSpace();
3222 unsigned i = 0;
3223 for (const Argument &Arg : F.args()) {
3224 Check(!Attrs.hasParamAttr(i, Attribute::ByVal),
3225 "Calling convention disallows byval", &F);
3226 Check(!Attrs.hasParamAttr(i, Attribute::Preallocated),
3227 "Calling convention disallows preallocated", &F);
3228 Check(!Attrs.hasParamAttr(i, Attribute::InAlloca),
3229 "Calling convention disallows inalloca", &F);
3230
3231 if (Attrs.hasParamAttr(i, Attribute::ByRef)) {
3232 // FIXME: Should also disallow LDS and GDS, but we don't have the enum
3233 // value here.
3234 Check(Arg.getType()->getPointerAddressSpace() != StackAS,
3235 "Calling convention disallows stack byref", &F);
3236 }
3237
3238 ++i;
3239 }
3240 }
3241
3242 [[fallthrough]];
3243 case CallingConv::Fast:
3244 case CallingConv::Cold:
3245 case CallingConv::Intel_OCL_BI:
3246 case CallingConv::PTX_Kernel:
3247 case CallingConv::PTX_Device:
3248 Check(!F.isVarArg(),
3249 "Calling convention does not support varargs or "
3250 "perfect forwarding!",
3251 &F);
3252 break;
3253 case CallingConv::AMDGPU_Gfx_WholeWave:
3254 Check(!F.arg_empty() && F.arg_begin()->getType()->isIntegerTy(1),
3255 "Calling convention requires first argument to be i1", &F);
3256 Check(!F.arg_begin()->hasInRegAttr(),
3257 "Calling convention requires first argument to not be inreg", &F);
3258 Check(!F.isVarArg(),
3259 "Calling convention does not support varargs or "
3260 "perfect forwarding!",
3261 &F);
3262 break;
3263 }
3264
3265 // Check that the argument values match the function type for this function...
3266 unsigned i = 0;
3267 for (const Argument &Arg : F.args()) {
3268 Check(Arg.getType() == FT->getParamType(i),
3269 "Argument value does not match function argument type!", &Arg,
3270 FT->getParamType(i));
3271 Check(Arg.getType()->isFirstClassType(),
3272 "Function arguments must have first-class types!", &Arg);
3273 if (!IsIntrinsic) {
3274 Check(!Arg.getType()->isMetadataTy(),
3275 "Function takes metadata but isn't an intrinsic", &Arg, &F);
3276 Check(!Arg.getType()->isTokenLikeTy(),
3277 "Function takes token but isn't an intrinsic", &Arg, &F);
3278 Check(!Arg.getType()->isX86_AMXTy(),
3279 "Function takes x86_amx but isn't an intrinsic", &Arg, &F);
3280 }
3281
3282 // Check that swifterror argument is only used by loads and stores.
3283 if (Attrs.hasParamAttr(i, Attribute::SwiftError)) {
3284 verifySwiftErrorValue(&Arg);
3285 }
3286 ++i;
3287 }
3288
3289 if (!IsIntrinsic) {
3290 Check(!F.getReturnType()->isTokenLikeTy(),
3291 "Function returns a token but isn't an intrinsic", &F);
3292 Check(!F.getReturnType()->isX86_AMXTy(),
3293 "Function returns a x86_amx but isn't an intrinsic", &F);
3294 }
3295
3296 // Get the function metadata attachments.
3298 F.getAllMetadata(MDs);
3299 assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync");
3300 verifyFunctionMetadata(MDs);
3301
3302 // Check validity of the personality function
3303 if (F.hasPersonalityFn()) {
3304 auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
3305 if (Per)
3306 Check(Per->getParent() == F.getParent(),
3307 "Referencing personality function in another module!", &F,
3308 F.getParent(), Per, Per->getParent());
3309 }
3310
3311 // EH funclet coloring can be expensive, recompute on-demand
3312 BlockEHFuncletColors.clear();
3313
3314 if (F.isMaterializable()) {
3315 // Function has a body somewhere we can't see.
3316 Check(MDs.empty(), "unmaterialized function cannot have metadata", &F,
3317 MDs.empty() ? nullptr : MDs.front().second);
3318 } else if (F.isDeclaration()) {
3319 for (const auto &I : MDs) {
3320 // This is used for call site debug information.
3321 CheckDI(I.first != LLVMContext::MD_dbg ||
3322 !cast<DISubprogram>(I.second)->isDistinct(),
3323 "function declaration may only have a unique !dbg attachment",
3324 &F);
3325 Check(I.first != LLVMContext::MD_prof,
3326 "function declaration may not have a !prof attachment", &F);
3327
3328 // Verify the metadata itself.
3329 visitMDNode(*I.second, AreDebugLocsAllowed::Yes);
3330 }
3331 Check(!F.hasPersonalityFn(),
3332 "Function declaration shouldn't have a personality routine", &F);
3333 } else {
3334 // Verify that this function (which has a body) is not named "llvm.*". It
3335 // is not legal to define intrinsics.
3336 Check(!IsIntrinsic, "llvm intrinsics cannot be defined!", &F);
3337
3338 // Check the entry node
3339 const BasicBlock *Entry = &F.getEntryBlock();
3340 Check(pred_empty(Entry),
3341 "Entry block to function must not have predecessors!", Entry);
3342
3343 // The address of the entry block cannot be taken, unless it is dead.
3344 if (Entry->hasAddressTaken()) {
3345 Check(!BlockAddress::lookup(Entry)->isConstantUsed(),
3346 "blockaddress may not be used with the entry block!", Entry);
3347 }
3348
3349 unsigned NumDebugAttachments = 0, NumProfAttachments = 0,
3350 NumKCFIAttachments = 0;
3351 // Visit metadata attachments.
3352 for (const auto &I : MDs) {
3353 // Verify that the attachment is legal.
3354 auto AllowLocs = AreDebugLocsAllowed::No;
3355 switch (I.first) {
3356 default:
3357 break;
3358 case LLVMContext::MD_dbg: {
3359 ++NumDebugAttachments;
3360 CheckDI(NumDebugAttachments == 1,
3361 "function must have a single !dbg attachment", &F, I.second);
3362 CheckDI(isa<DISubprogram>(I.second),
3363 "function !dbg attachment must be a subprogram", &F, I.second);
3364 CheckDI(cast<DISubprogram>(I.second)->isDistinct(),
3365 "function definition may only have a distinct !dbg attachment",
3366 &F);
3367
3368 auto *SP = cast<DISubprogram>(I.second);
3369 const Function *&AttachedTo = DISubprogramAttachments[SP];
3370 CheckDI(!AttachedTo || AttachedTo == &F,
3371 "DISubprogram attached to more than one function", SP, &F);
3372 AttachedTo = &F;
3373 AllowLocs = AreDebugLocsAllowed::Yes;
3374 break;
3375 }
3376 case LLVMContext::MD_prof:
3377 ++NumProfAttachments;
3378 Check(NumProfAttachments == 1,
3379 "function must have a single !prof attachment", &F, I.second);
3380 break;
3381 case LLVMContext::MD_kcfi_type:
3382 ++NumKCFIAttachments;
3383 Check(NumKCFIAttachments == 1,
3384 "function must have a single !kcfi_type attachment", &F,
3385 I.second);
3386 break;
3387 }
3388
3389 // Verify the metadata itself.
3390 visitMDNode(*I.second, AllowLocs);
3391 }
3392 }
3393
3394 // If this function is actually an intrinsic, verify that it is only used in
3395 // direct call/invokes, never having its "address taken".
3396 // Only do this if the module is materialized, otherwise we don't have all the
3397 // uses.
3398 if (F.isIntrinsic() && F.getParent()->isMaterialized()) {
3399 const User *U;
3400 if (F.hasAddressTaken(&U, false, true, false,
3401 /*IgnoreARCAttachedCall=*/true))
3402 Check(false, "Invalid user of intrinsic instruction!", U);
3403 }
3404
3405 // Check intrinsics' signatures.
3406 switch (F.getIntrinsicID()) {
3407 case Intrinsic::experimental_gc_get_pointer_base: {
3408 FunctionType *FT = F.getFunctionType();
3409 Check(FT->getNumParams() == 1, "wrong number of parameters", F);
3410 Check(isa<PointerType>(F.getReturnType()),
3411 "gc.get.pointer.base must return a pointer", F);
3412 Check(FT->getParamType(0) == F.getReturnType(),
3413 "gc.get.pointer.base operand and result must be of the same type", F);
3414 break;
3415 }
3416 case Intrinsic::experimental_gc_get_pointer_offset: {
3417 FunctionType *FT = F.getFunctionType();
3418 Check(FT->getNumParams() == 1, "wrong number of parameters", F);
3419 Check(isa<PointerType>(FT->getParamType(0)),
3420 "gc.get.pointer.offset operand must be a pointer", F);
3421 Check(F.getReturnType()->isIntegerTy(),
3422 "gc.get.pointer.offset must return integer", F);
3423 break;
3424 }
3425 }
3426
3427 auto *N = F.getSubprogram();
3428 HasDebugInfo = (N != nullptr);
3429 if (!HasDebugInfo)
3430 return;
3431
3432 // Check that all !dbg attachments lead to back to N.
3433 //
3434 // FIXME: Check this incrementally while visiting !dbg attachments.
3435 // FIXME: Only check when N is the canonical subprogram for F.
3436 SmallPtrSet<const MDNode *, 32> Seen;
3437 auto VisitDebugLoc = [&](const Instruction &I, const MDNode *Node) {
3438 // Be careful about using DILocation here since we might be dealing with
3439 // broken code (this is the Verifier after all).
3440 const DILocation *DL = dyn_cast_or_null<DILocation>(Node);
3441 if (!DL)
3442 return;
3443 if (!Seen.insert(DL).second)
3444 return;
3445
3446 Metadata *Parent = DL->getRawScope();
3447 CheckDI(Parent && isa<DILocalScope>(Parent),
3448 "DILocation's scope must be a DILocalScope", N, &F, &I, DL, Parent);
3449
3450 DILocalScope *Scope = DL->getInlinedAtScope();
3451 Check(Scope, "Failed to find DILocalScope", DL);
3452
3453 if (!Seen.insert(Scope).second)
3454 return;
3455
3456 DISubprogram *SP = Scope->getSubprogram();
3457
3458 // Scope and SP could be the same MDNode and we don't want to skip
3459 // validation in that case
3460 if ((Scope != SP) && !Seen.insert(SP).second)
3461 return;
3462
3463 CheckDI(SP->describes(&F),
3464 "!dbg attachment points at wrong subprogram for function", N, &F,
3465 &I, DL, Scope, SP);
3466 };
3467 for (auto &BB : F)
3468 for (auto &I : BB) {
3469 VisitDebugLoc(I, I.getDebugLoc().getAsMDNode());
3470 // The llvm.loop annotations also contain two DILocations.
3471 if (auto MD = I.getMetadata(LLVMContext::MD_loop))
3472 for (unsigned i = 1; i < MD->getNumOperands(); ++i)
3473 VisitDebugLoc(I, dyn_cast_or_null<MDNode>(MD->getOperand(i)));
3474 if (BrokenDebugInfo)
3475 return;
3476 }
3477}
3478
3479// verifyBasicBlock - Verify that a basic block is well formed...
3480//
3481void Verifier::visitBasicBlock(BasicBlock &BB) {
3482 InstsInThisBlock.clear();
3483 ConvergenceVerifyHelper.visit(BB);
3484
3485 // Ensure that basic blocks have terminators!
3486 Check(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
3487
3488 // Check constraints that this basic block imposes on all of the PHI nodes in
3489 // it.
3490 if (isa<PHINode>(BB.front())) {
3491 SmallVector<BasicBlock *, 8> Preds(predecessors(&BB));
3493 llvm::sort(Preds);
3494 for (const PHINode &PN : BB.phis()) {
3495 Check(PN.getNumIncomingValues() == Preds.size(),
3496 "PHINode should have one entry for each predecessor of its "
3497 "parent basic block!",
3498 &PN);
3499
3500 // Get and sort all incoming values in the PHI node...
3501 Values.clear();
3502 Values.reserve(PN.getNumIncomingValues());
3503 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3504 Values.push_back(
3505 std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
3506 llvm::sort(Values);
3507
3508 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
3509 // Check to make sure that if there is more than one entry for a
3510 // particular basic block in this PHI node, that the incoming values are
3511 // all identical.
3512 //
3513 Check(i == 0 || Values[i].first != Values[i - 1].first ||
3514 Values[i].second == Values[i - 1].second,
3515 "PHI node has multiple entries for the same basic block with "
3516 "different incoming values!",
3517 &PN, Values[i].first, Values[i].second, Values[i - 1].second);
3518
3519 // Check to make sure that the predecessors and PHI node entries are
3520 // matched up.
3521 Check(Values[i].first == Preds[i],
3522 "PHI node entries do not match predecessors!", &PN,
3523 Values[i].first, Preds[i]);
3524 }
3525 }
3526 }
3527
3528 // Check that all instructions have their parent pointers set up correctly.
3529 for (auto &I : BB)
3530 {
3531 Check(I.getParent() == &BB, "Instruction has bogus parent pointer!");
3532 }
3533
3534 // Confirm that no issues arise from the debug program.
3535 CheckDI(!BB.getTrailingDbgRecords(), "Basic Block has trailing DbgRecords!",
3536 &BB);
3537}
3538
3539void Verifier::visitTerminator(Instruction &I) {
3540 // Ensure that terminators only exist at the end of the basic block.
3541 Check(&I == I.getParent()->getTerminator(),
3542 "Terminator found in the middle of a basic block!", I.getParent());
3543 visitInstruction(I);
3544}
3545
3546void Verifier::visitCondBrInst(CondBrInst &BI) {
3548 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
3549 visitTerminator(BI);
3550}
3551
3552void Verifier::visitReturnInst(ReturnInst &RI) {
3553 Function *F = RI.getParent()->getParent();
3554 unsigned N = RI.getNumOperands();
3555 if (F->getReturnType()->isVoidTy())
3556 Check(N == 0,
3557 "Found return instr that returns non-void in Function of void "
3558 "return type!",
3559 &RI, F->getReturnType());
3560 else
3561 Check(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
3562 "Function return type does not match operand "
3563 "type of return inst!",
3564 &RI, F->getReturnType());
3565
3566 // Check to make sure that the return value has necessary properties for
3567 // terminators...
3568 visitTerminator(RI);
3569}
3570
3571void Verifier::visitSwitchInst(SwitchInst &SI) {
3572 Check(SI.getType()->isVoidTy(), "Switch must have void result type!", &SI);
3573 // Check to make sure that all of the constants in the switch instruction
3574 // have the same type as the switched-on value.
3575 Type *SwitchTy = SI.getCondition()->getType();
3576 SmallPtrSet<ConstantInt*, 32> Constants;
3577 for (auto &Case : SI.cases()) {
3578 Check(isa<ConstantInt>(Case.getCaseValue()),
3579 "Case value is not a constant integer.", &SI);
3580 Check(Case.getCaseValue()->getType() == SwitchTy,
3581 "Switch constants must all be same type as switch value!", &SI);
3582 Check(Constants.insert(Case.getCaseValue()).second,
3583 "Duplicate integer as switch case", &SI, Case.getCaseValue());
3584 }
3585
3586 visitTerminator(SI);
3587}
3588
3589void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
3591 "Indirectbr operand must have pointer type!", &BI);
3592 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
3594 "Indirectbr destinations must all have pointer type!", &BI);
3595
3596 visitTerminator(BI);
3597}
3598
3599void Verifier::visitCallBrInst(CallBrInst &CBI) {
3600 if (!CBI.isInlineAsm()) {
3602 "Callbr: indirect function / invalid signature");
3603 Check(!CBI.hasOperandBundles(),
3604 "Callbr for intrinsics currently doesn't support operand bundles");
3605
3606 switch (CBI.getIntrinsicID()) {
3607 case Intrinsic::amdgcn_kill: {
3608 Check(CBI.getNumIndirectDests() == 1,
3609 "Callbr amdgcn_kill only supports one indirect dest");
3610 bool Unreachable = isa<UnreachableInst>(CBI.getIndirectDest(0)->begin());
3611 CallInst *Call = dyn_cast<CallInst>(CBI.getIndirectDest(0)->begin());
3612 Check(Unreachable || (Call && Call->getIntrinsicID() ==
3613 Intrinsic::amdgcn_unreachable),
3614 "Callbr amdgcn_kill indirect dest needs to be unreachable");
3615 break;
3616 }
3617 default:
3618 CheckFailed(
3619 "Callbr currently only supports asm-goto and selected intrinsics");
3620 }
3621 visitIntrinsicCall(CBI.getIntrinsicID(), CBI);
3622 } else {
3623 const InlineAsm *IA = cast<InlineAsm>(CBI.getCalledOperand());
3624 Check(!IA->canThrow(), "Unwinding from Callbr is not allowed");
3625
3626 verifyInlineAsmCall(CBI);
3627 }
3628 visitTerminator(CBI);
3629}
3630
3631void Verifier::visitSelectInst(SelectInst &SI) {
3632 Check(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
3633 SI.getOperand(2)),
3634 "Invalid operands for select instruction!", &SI);
3635
3636 Check(SI.getTrueValue()->getType() == SI.getType(),
3637 "Select values must have same type as select instruction!", &SI);
3638 visitInstruction(SI);
3639}
3640
3641/// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
3642/// a pass, if any exist, it's an error.
3643///
3644void Verifier::visitUserOp1(Instruction &I) {
3645 Check(false, "User-defined operators should not live outside of a pass!", &I);
3646}
3647
3648void Verifier::visitTruncInst(TruncInst &I) {
3649 // Get the source and destination types
3650 Type *SrcTy = I.getOperand(0)->getType();
3651 Type *DestTy = I.getType();
3652
3653 // Get the size of the types in bits, we'll need this later
3654 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3655 unsigned DestBitSize = DestTy->getScalarSizeInBits();
3656
3657 Check(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
3658 Check(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
3659 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
3660 "trunc source and destination must both be a vector or neither", &I);
3661 Check(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
3662
3663 visitInstruction(I);
3664}
3665
3666void Verifier::visitZExtInst(ZExtInst &I) {
3667 // Get the source and destination types
3668 Type *SrcTy = I.getOperand(0)->getType();
3669 Type *DestTy = I.getType();
3670
3671 // Get the size of the types in bits, we'll need this later
3672 Check(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
3673 Check(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
3674 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
3675 "zext source and destination must both be a vector or neither", &I);
3676 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3677 unsigned DestBitSize = DestTy->getScalarSizeInBits();
3678
3679 Check(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
3680
3681 visitInstruction(I);
3682}
3683
3684void Verifier::visitSExtInst(SExtInst &I) {
3685 // Get the source and destination types
3686 Type *SrcTy = I.getOperand(0)->getType();
3687 Type *DestTy = I.getType();
3688
3689 // Get the size of the types in bits, we'll need this later
3690 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3691 unsigned DestBitSize = DestTy->getScalarSizeInBits();
3692
3693 Check(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
3694 Check(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
3695 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
3696 "sext source and destination must both be a vector or neither", &I);
3697 Check(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
3698
3699 visitInstruction(I);
3700}
3701
3702void Verifier::visitFPTruncInst(FPTruncInst &I) {
3703 // Get the source and destination types
3704 Type *SrcTy = I.getOperand(0)->getType();
3705 Type *DestTy = I.getType();
3706 // Get the size of the types in bits, we'll need this later
3707 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3708 unsigned DestBitSize = DestTy->getScalarSizeInBits();
3709
3710 Check(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
3711 Check(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
3712 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
3713 "fptrunc source and destination must both be a vector or neither", &I);
3714 Check(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
3715
3716 visitInstruction(I);
3717}
3718
3719void Verifier::visitFPExtInst(FPExtInst &I) {
3720 // Get the source and destination types
3721 Type *SrcTy = I.getOperand(0)->getType();
3722 Type *DestTy = I.getType();
3723
3724 // Get the size of the types in bits, we'll need this later
3725 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3726 unsigned DestBitSize = DestTy->getScalarSizeInBits();
3727
3728 Check(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
3729 Check(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
3730 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
3731 "fpext source and destination must both be a vector or neither", &I);
3732 Check(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
3733
3734 visitInstruction(I);
3735}
3736
3737void Verifier::visitUIToFPInst(UIToFPInst &I) {
3738 // Get the source and destination types
3739 Type *SrcTy = I.getOperand(0)->getType();
3740 Type *DestTy = I.getType();
3741
3742 bool SrcVec = SrcTy->isVectorTy();
3743 bool DstVec = DestTy->isVectorTy();
3744
3745 Check(SrcVec == DstVec,
3746 "UIToFP source and dest must both be vector or scalar", &I);
3747 Check(SrcTy->isIntOrIntVectorTy(),
3748 "UIToFP source must be integer or integer vector", &I);
3749 Check(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
3750 &I);
3751
3752 if (SrcVec && DstVec)
3753 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3754 cast<VectorType>(DestTy)->getElementCount(),
3755 "UIToFP source and dest vector length mismatch", &I);
3756
3757 visitInstruction(I);
3758}
3759
3760void Verifier::visitSIToFPInst(SIToFPInst &I) {
3761 // Get the source and destination types
3762 Type *SrcTy = I.getOperand(0)->getType();
3763 Type *DestTy = I.getType();
3764
3765 bool SrcVec = SrcTy->isVectorTy();
3766 bool DstVec = DestTy->isVectorTy();
3767
3768 Check(SrcVec == DstVec,
3769 "SIToFP source and dest must both be vector or scalar", &I);
3770 Check(SrcTy->isIntOrIntVectorTy(),
3771 "SIToFP source must be integer or integer vector", &I);
3772 Check(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
3773 &I);
3774
3775 if (SrcVec && DstVec)
3776 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3777 cast<VectorType>(DestTy)->getElementCount(),
3778 "SIToFP source and dest vector length mismatch", &I);
3779
3780 visitInstruction(I);
3781}
3782
3783void Verifier::visitFPToUIInst(FPToUIInst &I) {
3784 // Get the source and destination types
3785 Type *SrcTy = I.getOperand(0)->getType();
3786 Type *DestTy = I.getType();
3787
3788 bool SrcVec = SrcTy->isVectorTy();
3789 bool DstVec = DestTy->isVectorTy();
3790
3791 Check(SrcVec == DstVec,
3792 "FPToUI source and dest must both be vector or scalar", &I);
3793 Check(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector", &I);
3794 Check(DestTy->isIntOrIntVectorTy(),
3795 "FPToUI result must be integer or integer vector", &I);
3796
3797 if (SrcVec && DstVec)
3798 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3799 cast<VectorType>(DestTy)->getElementCount(),
3800 "FPToUI source and dest vector length mismatch", &I);
3801
3802 visitInstruction(I);
3803}
3804
3805void Verifier::visitFPToSIInst(FPToSIInst &I) {
3806 // Get the source and destination types
3807 Type *SrcTy = I.getOperand(0)->getType();
3808 Type *DestTy = I.getType();
3809
3810 bool SrcVec = SrcTy->isVectorTy();
3811 bool DstVec = DestTy->isVectorTy();
3812
3813 Check(SrcVec == DstVec,
3814 "FPToSI source and dest must both be vector or scalar", &I);
3815 Check(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector", &I);
3816 Check(DestTy->isIntOrIntVectorTy(),
3817 "FPToSI result must be integer or integer vector", &I);
3818
3819 if (SrcVec && DstVec)
3820 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3821 cast<VectorType>(DestTy)->getElementCount(),
3822 "FPToSI source and dest vector length mismatch", &I);
3823
3824 visitInstruction(I);
3825}
3826
3827void Verifier::checkPtrToAddr(Type *SrcTy, Type *DestTy, const Value &V) {
3828 Check(SrcTy->isPtrOrPtrVectorTy(), "PtrToAddr source must be pointer", V);
3829 Check(DestTy->isIntOrIntVectorTy(), "PtrToAddr result must be integral", V);
3830 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToAddr type mismatch",
3831 V);
3832
3833 if (SrcTy->isVectorTy()) {
3834 auto *VSrc = cast<VectorType>(SrcTy);
3835 auto *VDest = cast<VectorType>(DestTy);
3836 Check(VSrc->getElementCount() == VDest->getElementCount(),
3837 "PtrToAddr vector length mismatch", V);
3838 }
3839
3840 Type *AddrTy = DL.getAddressType(SrcTy);
3841 Check(AddrTy == DestTy, "PtrToAddr result must be address width", V);
3842}
3843
3844void Verifier::visitPtrToAddrInst(PtrToAddrInst &I) {
3845 checkPtrToAddr(I.getOperand(0)->getType(), I.getType(), I);
3846 visitInstruction(I);
3847}
3848
3849void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
3850 // Get the source and destination types
3851 Type *SrcTy = I.getOperand(0)->getType();
3852 Type *DestTy = I.getType();
3853
3854 Check(SrcTy->isPtrOrPtrVectorTy(), "PtrToInt source must be pointer", &I);
3855
3856 Check(DestTy->isIntOrIntVectorTy(), "PtrToInt result must be integral", &I);
3857 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
3858 &I);
3859
3860 if (SrcTy->isVectorTy()) {
3861 auto *VSrc = cast<VectorType>(SrcTy);
3862 auto *VDest = cast<VectorType>(DestTy);
3863 Check(VSrc->getElementCount() == VDest->getElementCount(),
3864 "PtrToInt Vector length mismatch", &I);
3865 }
3866
3867 visitInstruction(I);
3868}
3869
3870void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
3871 // Get the source and destination types
3872 Type *SrcTy = I.getOperand(0)->getType();
3873 Type *DestTy = I.getType();
3874
3875 Check(SrcTy->isIntOrIntVectorTy(), "IntToPtr source must be an integral", &I);
3876 Check(DestTy->isPtrOrPtrVectorTy(), "IntToPtr result must be a pointer", &I);
3877
3878 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
3879 &I);
3880 if (SrcTy->isVectorTy()) {
3881 auto *VSrc = cast<VectorType>(SrcTy);
3882 auto *VDest = cast<VectorType>(DestTy);
3883 Check(VSrc->getElementCount() == VDest->getElementCount(),
3884 "IntToPtr Vector length mismatch", &I);
3885 }
3886 visitInstruction(I);
3887}
3888
3889void Verifier::visitBitCastInst(BitCastInst &I) {
3890 Check(
3891 CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
3892 "Invalid bitcast", &I);
3893 visitInstruction(I);
3894}
3895
3896void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
3897 Type *SrcTy = I.getOperand(0)->getType();
3898 Type *DestTy = I.getType();
3899
3900 Check(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
3901 &I);
3902 Check(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
3903 &I);
3905 "AddrSpaceCast must be between different address spaces", &I);
3906 if (auto *SrcVTy = dyn_cast<VectorType>(SrcTy))
3907 Check(SrcVTy->getElementCount() ==
3908 cast<VectorType>(DestTy)->getElementCount(),
3909 "AddrSpaceCast vector pointer number of elements mismatch", &I);
3910 visitInstruction(I);
3911}
3912
3913/// visitPHINode - Ensure that a PHI node is well formed.
3914///
3915void Verifier::visitPHINode(PHINode &PN) {
3916 // Ensure that the PHI nodes are all grouped together at the top of the block.
3917 // This can be tested by checking whether the instruction before this is
3918 // either nonexistent (because this is begin()) or is a PHI node. If not,
3919 // then there is some other instruction before a PHI.
3920 Check(&PN == &PN.getParent()->front() ||
3922 "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
3923
3924 // Check that a PHI doesn't yield a Token.
3925 Check(!PN.getType()->isTokenLikeTy(), "PHI nodes cannot have token type!");
3926
3927 // Check that all of the values of the PHI node have the same type as the
3928 // result.
3929 for (Value *IncValue : PN.incoming_values()) {
3930 Check(PN.getType() == IncValue->getType(),
3931 "PHI node operands are not the same type as the result!", &PN);
3932 }
3933
3934 // All other PHI node constraints are checked in the visitBasicBlock method.
3935
3936 visitInstruction(PN);
3937}
3938
3939void Verifier::visitCallBase(CallBase &Call) {
3941 "Called function must be a pointer!", Call);
3942 FunctionType *FTy = Call.getFunctionType();
3943
3944 // Verify that the correct number of arguments are being passed
3945 if (FTy->isVarArg())
3946 Check(Call.arg_size() >= FTy->getNumParams(),
3947 "Called function requires more parameters than were provided!", Call);
3948 else
3949 Check(Call.arg_size() == FTy->getNumParams(),
3950 "Incorrect number of arguments passed to called function!", Call);
3951
3952 // Verify that all arguments to the call match the function type.
3953 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3954 Check(Call.getArgOperand(i)->getType() == FTy->getParamType(i),
3955 "Call parameter type does not match function signature!",
3956 Call.getArgOperand(i), FTy->getParamType(i), Call);
3957
3958 AttributeList Attrs = Call.getAttributes();
3959
3960 Check(verifyAttributeCount(Attrs, Call.arg_size()),
3961 "Attribute after last parameter!", Call);
3962
3963 Function *Callee =
3965 bool IsIntrinsic = Callee && Callee->isIntrinsic();
3966 if (IsIntrinsic)
3967 Check(Callee->getFunctionType() == FTy,
3968 "Intrinsic called with incompatible signature", Call);
3969
3970 // Verify if the calling convention of the callee is callable.
3972 "calling convention does not permit calls", Call);
3973
3974 // Disallow passing/returning values with alignment higher than we can
3975 // represent.
3976 // FIXME: Consider making DataLayout cap the alignment, so this isn't
3977 // necessary.
3978 auto VerifyTypeAlign = [&](Type *Ty, const Twine &Message) {
3979 if (!Ty->isSized())
3980 return;
3981 Align ABIAlign = DL.getABITypeAlign(Ty);
3982 Check(ABIAlign.value() <= Value::MaximumAlignment,
3983 "Incorrect alignment of " + Message + " to called function!", Call);
3984 };
3985
3986 if (!IsIntrinsic) {
3987 VerifyTypeAlign(FTy->getReturnType(), "return type");
3988 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3989 Type *Ty = FTy->getParamType(i);
3990 VerifyTypeAlign(Ty, "argument passed");
3991 }
3992 }
3993
3994 if (Attrs.hasFnAttr(Attribute::Speculatable)) {
3995 // Don't allow speculatable on call sites, unless the underlying function
3996 // declaration is also speculatable.
3997 Check(Callee && Callee->isSpeculatable(),
3998 "speculatable attribute may not apply to call sites", Call);
3999 }
4000
4001 if (Attrs.hasFnAttr(Attribute::Preallocated)) {
4002 Check(Call.getIntrinsicID() == Intrinsic::call_preallocated_arg,
4003 "preallocated as a call site attribute can only be on "
4004 "llvm.call.preallocated.arg");
4005 }
4006
4007 Check(!Attrs.hasFnAttr(Attribute::DenormalFPEnv),
4008 "denormal_fpenv attribute may not apply to call sites", Call);
4009
4010 // Verify call attributes.
4011 verifyFunctionAttrs(FTy, Attrs, &Call, IsIntrinsic, Call.isInlineAsm());
4012
4013 // Conservatively check the inalloca argument.
4014 // We have a bug if we can find that there is an underlying alloca without
4015 // inalloca.
4016 if (Call.hasInAllocaArgument()) {
4017 Value *InAllocaArg = Call.getArgOperand(FTy->getNumParams() - 1);
4018 if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
4019 Check(AI->isUsedWithInAlloca(),
4020 "inalloca argument for call has mismatched alloca", AI, Call);
4021 }
4022
4023 // For each argument of the callsite, if it has the swifterror argument,
4024 // make sure the underlying alloca/parameter it comes from has a swifterror as
4025 // well.
4026 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
4027 if (Call.paramHasAttr(i, Attribute::SwiftError)) {
4028 Value *SwiftErrorArg = Call.getArgOperand(i);
4029 if (auto AI = dyn_cast<AllocaInst>(SwiftErrorArg->stripInBoundsOffsets())) {
4030 Check(AI->isSwiftError(),
4031 "swifterror argument for call has mismatched alloca", AI, Call);
4032 continue;
4033 }
4034 auto ArgI = dyn_cast<Argument>(SwiftErrorArg);
4035 Check(ArgI, "swifterror argument should come from an alloca or parameter",
4036 SwiftErrorArg, Call);
4037 Check(ArgI->hasSwiftErrorAttr(),
4038 "swifterror argument for call has mismatched parameter", ArgI,
4039 Call);
4040 }
4041
4042 if (Attrs.hasParamAttr(i, Attribute::ImmArg)) {
4043 // Don't allow immarg on call sites, unless the underlying declaration
4044 // also has the matching immarg.
4045 Check(Callee && Callee->hasParamAttribute(i, Attribute::ImmArg),
4046 "immarg may not apply only to call sites", Call.getArgOperand(i),
4047 Call);
4048 }
4049
4050 if (Call.paramHasAttr(i, Attribute::ImmArg)) {
4051 Value *ArgVal = Call.getArgOperand(i);
4052 Check((isa<ConstantInt>(ArgVal) || isa<ConstantFP>(ArgVal)) &&
4053 !isa<VectorType>(ArgVal->getType()),
4054 "immarg operand has non-immediate parameter", ArgVal, Call);
4055
4056 // If the imm-arg is an integer and also has a range attached,
4057 // check if the given value is within the range.
4058 if (Call.paramHasAttr(i, Attribute::Range)) {
4059 if (auto *CI = dyn_cast<ConstantInt>(ArgVal)) {
4060 const ConstantRange &CR =
4061 Call.getParamAttr(i, Attribute::Range).getValueAsConstantRange();
4062 Check(CR.contains(CI->getValue()),
4063 "immarg value " + Twine(CI->getValue().getSExtValue()) +
4064 " out of range [" + Twine(CR.getLower().getSExtValue()) +
4065 ", " + Twine(CR.getUpper().getSExtValue()) + ")",
4066 Call);
4067 }
4068 }
4069 }
4070
4071 if (Call.paramHasAttr(i, Attribute::Preallocated)) {
4072 Value *ArgVal = Call.getArgOperand(i);
4073 bool hasOB =
4075 bool isMustTail = Call.isMustTailCall();
4076 Check(hasOB != isMustTail,
4077 "preallocated operand either requires a preallocated bundle or "
4078 "the call to be musttail (but not both)",
4079 ArgVal, Call);
4080 }
4081 }
4082
4083 if (FTy->isVarArg()) {
4084 // FIXME? is 'nest' even legal here?
4085 bool SawNest = false;
4086 bool SawReturned = false;
4087
4088 for (unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) {
4089 if (Attrs.hasParamAttr(Idx, Attribute::Nest))
4090 SawNest = true;
4091 if (Attrs.hasParamAttr(Idx, Attribute::Returned))
4092 SawReturned = true;
4093 }
4094
4095 // Check attributes on the varargs part.
4096 for (unsigned Idx = FTy->getNumParams(); Idx < Call.arg_size(); ++Idx) {
4097 Type *Ty = Call.getArgOperand(Idx)->getType();
4098 AttributeSet ArgAttrs = Attrs.getParamAttrs(Idx);
4099 verifyParameterAttrs(ArgAttrs, Ty, &Call);
4100
4101 if (ArgAttrs.hasAttribute(Attribute::Nest)) {
4102 Check(!SawNest, "More than one parameter has attribute nest!", Call);
4103 SawNest = true;
4104 }
4105
4106 if (ArgAttrs.hasAttribute(Attribute::Returned)) {
4107 Check(!SawReturned, "More than one parameter has attribute returned!",
4108 Call);
4109 Check(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
4110 "Incompatible argument and return types for 'returned' "
4111 "attribute",
4112 Call);
4113 SawReturned = true;
4114 }
4115
4116 // Statepoint intrinsic is vararg but the wrapped function may be not.
4117 // Allow sret here and check the wrapped function in verifyStatepoint.
4118 if (Call.getIntrinsicID() != Intrinsic::experimental_gc_statepoint)
4119 Check(!ArgAttrs.hasAttribute(Attribute::StructRet),
4120 "Attribute 'sret' cannot be used for vararg call arguments!",
4121 Call);
4122
4123 if (ArgAttrs.hasAttribute(Attribute::InAlloca))
4124 Check(Idx == Call.arg_size() - 1,
4125 "inalloca isn't on the last argument!", Call);
4126 }
4127 }
4128
4129 // Verify that there's no metadata unless it's a direct call to an intrinsic.
4130 if (!IsIntrinsic) {
4131 for (Type *ParamTy : FTy->params()) {
4132 Check(!ParamTy->isMetadataTy(),
4133 "Function has metadata parameter but isn't an intrinsic", Call);
4134 Check(!ParamTy->isTokenLikeTy(),
4135 "Function has token parameter but isn't an intrinsic", Call);
4136 }
4137 }
4138
4139 // Verify that indirect calls don't return tokens.
4140 if (!Call.getCalledFunction()) {
4141 Check(!FTy->getReturnType()->isTokenLikeTy(),
4142 "Return type cannot be token for indirect call!");
4143 Check(!FTy->getReturnType()->isX86_AMXTy(),
4144 "Return type cannot be x86_amx for indirect call!");
4145 }
4146
4148 visitIntrinsicCall(ID, Call);
4149
4150 // Verify that a callsite has at most one "deopt", at most one "funclet", at
4151 // most one "gc-transition", at most one "cfguardtarget", at most one
4152 // "preallocated" operand bundle, and at most one "ptrauth" operand bundle.
4153 bool FoundDeoptBundle = false, FoundFuncletBundle = false,
4154 FoundGCTransitionBundle = false, FoundCFGuardTargetBundle = false,
4155 FoundPreallocatedBundle = false, FoundGCLiveBundle = false,
4156 FoundPtrauthBundle = false, FoundKCFIBundle = false,
4157 FoundAttachedCallBundle = false;
4158 for (unsigned i = 0, e = Call.getNumOperandBundles(); i < e; ++i) {
4159 OperandBundleUse BU = Call.getOperandBundleAt(i);
4160 uint32_t Tag = BU.getTagID();
4161 if (Tag == LLVMContext::OB_deopt) {
4162 Check(!FoundDeoptBundle, "Multiple deopt operand bundles", Call);
4163 FoundDeoptBundle = true;
4164 } else if (Tag == LLVMContext::OB_gc_transition) {
4165 Check(!FoundGCTransitionBundle, "Multiple gc-transition operand bundles",
4166 Call);
4167 FoundGCTransitionBundle = true;
4168 } else if (Tag == LLVMContext::OB_funclet) {
4169 Check(!FoundFuncletBundle, "Multiple funclet operand bundles", Call);
4170 FoundFuncletBundle = true;
4171 Check(BU.Inputs.size() == 1,
4172 "Expected exactly one funclet bundle operand", Call);
4173 Check(isa<FuncletPadInst>(BU.Inputs.front()),
4174 "Funclet bundle operands should correspond to a FuncletPadInst",
4175 Call);
4176 } else if (Tag == LLVMContext::OB_cfguardtarget) {
4177 Check(!FoundCFGuardTargetBundle, "Multiple CFGuardTarget operand bundles",
4178 Call);
4179 FoundCFGuardTargetBundle = true;
4180 Check(BU.Inputs.size() == 1,
4181 "Expected exactly one cfguardtarget bundle operand", Call);
4182 } else if (Tag == LLVMContext::OB_ptrauth) {
4183 Check(!FoundPtrauthBundle, "Multiple ptrauth operand bundles", Call);
4184 FoundPtrauthBundle = true;
4185 Check(BU.Inputs.size() == 2,
4186 "Expected exactly two ptrauth bundle operands", Call);
4187 Check(isa<ConstantInt>(BU.Inputs[0]) &&
4188 BU.Inputs[0]->getType()->isIntegerTy(32),
4189 "Ptrauth bundle key operand must be an i32 constant", Call);
4190 Check(BU.Inputs[1]->getType()->isIntegerTy(64),
4191 "Ptrauth bundle discriminator operand must be an i64", Call);
4192 } else if (Tag == LLVMContext::OB_kcfi) {
4193 Check(!FoundKCFIBundle, "Multiple kcfi operand bundles", Call);
4194 FoundKCFIBundle = true;
4195 Check(BU.Inputs.size() == 1, "Expected exactly one kcfi bundle operand",
4196 Call);
4197 Check(isa<ConstantInt>(BU.Inputs[0]) &&
4198 BU.Inputs[0]->getType()->isIntegerTy(32),
4199 "Kcfi bundle operand must be an i32 constant", Call);
4200 } else if (Tag == LLVMContext::OB_preallocated) {
4201 Check(!FoundPreallocatedBundle, "Multiple preallocated operand bundles",
4202 Call);
4203 FoundPreallocatedBundle = true;
4204 Check(BU.Inputs.size() == 1,
4205 "Expected exactly one preallocated bundle operand", Call);
4206 auto Input = dyn_cast<IntrinsicInst>(BU.Inputs.front());
4207 Check(Input &&
4208 Input->getIntrinsicID() == Intrinsic::call_preallocated_setup,
4209 "\"preallocated\" argument must be a token from "
4210 "llvm.call.preallocated.setup",
4211 Call);
4212 } else if (Tag == LLVMContext::OB_gc_live) {
4213 Check(!FoundGCLiveBundle, "Multiple gc-live operand bundles", Call);
4214 FoundGCLiveBundle = true;
4216 Check(!FoundAttachedCallBundle,
4217 "Multiple \"clang.arc.attachedcall\" operand bundles", Call);
4218 FoundAttachedCallBundle = true;
4219 verifyAttachedCallBundle(Call, BU);
4220 }
4221 }
4222
4223 // Verify that callee and callsite agree on whether to use pointer auth.
4224 Check(!(Call.getCalledFunction() && FoundPtrauthBundle),
4225 "Direct call cannot have a ptrauth bundle", Call);
4226
4227 // Verify that each inlinable callsite of a debug-info-bearing function in a
4228 // debug-info-bearing function has a debug location attached to it. Failure to
4229 // do so causes assertion failures when the inliner sets up inline scope info
4230 // (Interposable functions are not inlinable, neither are functions without
4231 // definitions.)
4237 "inlinable function call in a function with "
4238 "debug info must have a !dbg location",
4239 Call);
4240
4241 if (Call.isInlineAsm())
4242 verifyInlineAsmCall(Call);
4243
4244 ConvergenceVerifyHelper.visit(Call);
4245
4246 visitInstruction(Call);
4247}
4248
4249void Verifier::verifyTailCCMustTailAttrs(const AttrBuilder &Attrs,
4250 StringRef Context) {
4251 Check(!Attrs.contains(Attribute::InAlloca),
4252 Twine("inalloca attribute not allowed in ") + Context);
4253 Check(!Attrs.contains(Attribute::InReg),
4254 Twine("inreg attribute not allowed in ") + Context);
4255 Check(!Attrs.contains(Attribute::SwiftError),
4256 Twine("swifterror attribute not allowed in ") + Context);
4257 Check(!Attrs.contains(Attribute::Preallocated),
4258 Twine("preallocated attribute not allowed in ") + Context);
4259 Check(!Attrs.contains(Attribute::ByRef),
4260 Twine("byref attribute not allowed in ") + Context);
4261}
4262
4263static AttrBuilder getParameterABIAttributes(LLVMContext& C, unsigned I, AttributeList Attrs) {
4264 static const Attribute::AttrKind ABIAttrs[] = {
4265 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
4266 Attribute::InReg, Attribute::StackAlignment, Attribute::SwiftSelf,
4267 Attribute::SwiftAsync, Attribute::SwiftError, Attribute::Preallocated,
4268 Attribute::ByRef};
4269 AttrBuilder Copy(C);
4270 for (auto AK : ABIAttrs) {
4271 Attribute Attr = Attrs.getParamAttrs(I).getAttribute(AK);
4272 if (Attr.isValid())
4273 Copy.addAttribute(Attr);
4274 }
4275
4276 // `align` is ABI-affecting only in combination with `byval` or `byref`.
4277 if (Attrs.hasParamAttr(I, Attribute::Alignment) &&
4278 (Attrs.hasParamAttr(I, Attribute::ByVal) ||
4279 Attrs.hasParamAttr(I, Attribute::ByRef)))
4280 Copy.addAlignmentAttr(Attrs.getParamAlignment(I));
4281 return Copy;
4282}
4283
4284void Verifier::verifyMustTailCall(CallInst &CI) {
4285 Check(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
4286
4287 Function *F = CI.getParent()->getParent();
4288 FunctionType *CallerTy = F->getFunctionType();
4289 FunctionType *CalleeTy = CI.getFunctionType();
4290 Check(CallerTy->isVarArg() == CalleeTy->isVarArg(),
4291 "cannot guarantee tail call due to mismatched varargs", &CI);
4292 Check(CallerTy->getReturnType() == CalleeTy->getReturnType(),
4293 "cannot guarantee tail call due to mismatched return types", &CI);
4294
4295 // - The calling conventions of the caller and callee must match.
4296 Check(F->getCallingConv() == CI.getCallingConv(),
4297 "cannot guarantee tail call due to mismatched calling conv", &CI);
4298
4299 // - The call must immediately precede a :ref:`ret <i_ret>` instruction.
4300 // - The ret instruction must return the value produced by the call or void.
4302
4303 // Check the return.
4304 ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
4305 Check(Ret, "musttail call must precede a ret", &CI);
4306 Check(!Ret->getReturnValue() || Ret->getReturnValue() == &CI ||
4308 "musttail call result must be returned", Ret);
4309
4310 AttributeList CallerAttrs = F->getAttributes();
4311 AttributeList CalleeAttrs = CI.getAttributes();
4312 if (CI.getCallingConv() == CallingConv::SwiftTail ||
4313 CI.getCallingConv() == CallingConv::Tail) {
4314 StringRef CCName =
4315 CI.getCallingConv() == CallingConv::Tail ? "tailcc" : "swifttailcc";
4316
4317 // - Only sret, byval, swiftself, and swiftasync ABI-impacting attributes
4318 // are allowed in swifttailcc call
4319 for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
4320 AttrBuilder ABIAttrs = getParameterABIAttributes(F->getContext(), I, CallerAttrs);
4321 SmallString<32> Context{CCName, StringRef(" musttail caller")};
4322 verifyTailCCMustTailAttrs(ABIAttrs, Context);
4323 }
4324 for (unsigned I = 0, E = CalleeTy->getNumParams(); I != E; ++I) {
4325 AttrBuilder ABIAttrs = getParameterABIAttributes(F->getContext(), I, CalleeAttrs);
4326 SmallString<32> Context{CCName, StringRef(" musttail callee")};
4327 verifyTailCCMustTailAttrs(ABIAttrs, Context);
4328 }
4329 // - Varargs functions are not allowed
4330 Check(!CallerTy->isVarArg(), Twine("cannot guarantee ") + CCName +
4331 " tail call for varargs function");
4332 return;
4333 }
4334
4335 // - The caller and callee prototypes must match.
4336 if (!CI.getIntrinsicID()) {
4337 Check(CallerTy->getNumParams() == CalleeTy->getNumParams(),
4338 "cannot guarantee tail call due to mismatched parameter counts", &CI);
4339 for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
4340 Check(CallerTy->getParamType(I) == CalleeTy->getParamType(I),
4341 "cannot guarantee tail call due to mismatched parameter types",
4342 &CI);
4343 }
4344 }
4345
4346 // - All ABI-impacting function attributes, such as sret, byval, inreg,
4347 // returned, preallocated, and inalloca, must match.
4348 for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
4349 AttrBuilder CallerABIAttrs = getParameterABIAttributes(F->getContext(), I, CallerAttrs);
4350 AttrBuilder CalleeABIAttrs = getParameterABIAttributes(F->getContext(), I, CalleeAttrs);
4351 Check(CallerABIAttrs == CalleeABIAttrs,
4352 "cannot guarantee tail call due to mismatched ABI impacting "
4353 "function attributes",
4354 &CI, CI.getOperand(I));
4355 }
4356}
4357
4358void Verifier::visitCallInst(CallInst &CI) {
4359 visitCallBase(CI);
4360
4361 if (CI.isMustTailCall())
4362 verifyMustTailCall(CI);
4363}
4364
4365void Verifier::visitInvokeInst(InvokeInst &II) {
4366 visitCallBase(II);
4367
4368 // Verify that the first non-PHI instruction of the unwind destination is an
4369 // exception handling instruction.
4370 Check(
4371 II.getUnwindDest()->isEHPad(),
4372 "The unwind destination does not have an exception handling instruction!",
4373 &II);
4374
4375 visitTerminator(II);
4376}
4377
4378/// visitUnaryOperator - Check the argument to the unary operator.
4379///
4380void Verifier::visitUnaryOperator(UnaryOperator &U) {
4381 Check(U.getType() == U.getOperand(0)->getType(),
4382 "Unary operators must have same type for"
4383 "operands and result!",
4384 &U);
4385
4386 switch (U.getOpcode()) {
4387 // Check that floating-point arithmetic operators are only used with
4388 // floating-point operands.
4389 case Instruction::FNeg:
4390 Check(U.getType()->isFPOrFPVectorTy(),
4391 "FNeg operator only works with float types!", &U);
4392 break;
4393 default:
4394 llvm_unreachable("Unknown UnaryOperator opcode!");
4395 }
4396
4397 visitInstruction(U);
4398}
4399
4400/// visitBinaryOperator - Check that both arguments to the binary operator are
4401/// of the same type!
4402///
4403void Verifier::visitBinaryOperator(BinaryOperator &B) {
4404 Check(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
4405 "Both operands to a binary operator are not of the same type!", &B);
4406
4407 switch (B.getOpcode()) {
4408 // Check that integer arithmetic operators are only used with
4409 // integral operands.
4410 case Instruction::Add:
4411 case Instruction::Sub:
4412 case Instruction::Mul:
4413 case Instruction::SDiv:
4414 case Instruction::UDiv:
4415 case Instruction::SRem:
4416 case Instruction::URem:
4417 Check(B.getType()->isIntOrIntVectorTy(),
4418 "Integer arithmetic operators only work with integral types!", &B);
4419 Check(B.getType() == B.getOperand(0)->getType(),
4420 "Integer arithmetic operators must have same type "
4421 "for operands and result!",
4422 &B);
4423 break;
4424 // Check that floating-point arithmetic operators are only used with
4425 // floating-point operands.
4426 case Instruction::FAdd:
4427 case Instruction::FSub:
4428 case Instruction::FMul:
4429 case Instruction::FDiv:
4430 case Instruction::FRem:
4431 Check(B.getType()->isFPOrFPVectorTy(),
4432 "Floating-point arithmetic operators only work with "
4433 "floating-point types!",
4434 &B);
4435 Check(B.getType() == B.getOperand(0)->getType(),
4436 "Floating-point arithmetic operators must have same type "
4437 "for operands and result!",
4438 &B);
4439 break;
4440 // Check that logical operators are only used with integral operands.
4441 case Instruction::And:
4442 case Instruction::Or:
4443 case Instruction::Xor:
4444 Check(B.getType()->isIntOrIntVectorTy(),
4445 "Logical operators only work with integral types!", &B);
4446 Check(B.getType() == B.getOperand(0)->getType(),
4447 "Logical operators must have same type for operands and result!", &B);
4448 break;
4449 case Instruction::Shl:
4450 case Instruction::LShr:
4451 case Instruction::AShr:
4452 Check(B.getType()->isIntOrIntVectorTy(),
4453 "Shifts only work with integral types!", &B);
4454 Check(B.getType() == B.getOperand(0)->getType(),
4455 "Shift return type must be same as operands!", &B);
4456 break;
4457 default:
4458 llvm_unreachable("Unknown BinaryOperator opcode!");
4459 }
4460
4461 visitInstruction(B);
4462}
4463
4464void Verifier::visitICmpInst(ICmpInst &IC) {
4465 // Check that the operands are the same type
4466 Type *Op0Ty = IC.getOperand(0)->getType();
4467 Type *Op1Ty = IC.getOperand(1)->getType();
4468 Check(Op0Ty == Op1Ty,
4469 "Both operands to ICmp instruction are not of the same type!", &IC);
4470 // Check that the operands are the right type
4471 Check(Op0Ty->isIntOrIntVectorTy() || Op0Ty->isPtrOrPtrVectorTy(),
4472 "Invalid operand types for ICmp instruction", &IC);
4473 // Check that the predicate is valid.
4474 Check(IC.isIntPredicate(), "Invalid predicate in ICmp instruction!", &IC);
4475
4476 visitInstruction(IC);
4477}
4478
4479void Verifier::visitFCmpInst(FCmpInst &FC) {
4480 // Check that the operands are the same type
4481 Type *Op0Ty = FC.getOperand(0)->getType();
4482 Type *Op1Ty = FC.getOperand(1)->getType();
4483 Check(Op0Ty == Op1Ty,
4484 "Both operands to FCmp instruction are not of the same type!", &FC);
4485 // Check that the operands are the right type
4486 Check(Op0Ty->isFPOrFPVectorTy(), "Invalid operand types for FCmp instruction",
4487 &FC);
4488 // Check that the predicate is valid.
4489 Check(FC.isFPPredicate(), "Invalid predicate in FCmp instruction!", &FC);
4490
4491 visitInstruction(FC);
4492}
4493
4494void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
4496 "Invalid extractelement operands!", &EI);
4497 visitInstruction(EI);
4498}
4499
4500void Verifier::visitInsertElementInst(InsertElementInst &IE) {
4501 Check(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
4502 IE.getOperand(2)),
4503 "Invalid insertelement operands!", &IE);
4504 visitInstruction(IE);
4505}
4506
4507void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
4509 SV.getShuffleMask()),
4510 "Invalid shufflevector operands!", &SV);
4511 visitInstruction(SV);
4512}
4513
4514void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
4516 GEP.getModule()->getModuleFlag("require-logical-pointer")))
4517 Check(!MD->getZExtValue(),
4518 "Non-logical getelementptr disallowed for this module.");
4519
4520 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
4521
4522 Check(isa<PointerType>(TargetTy),
4523 "GEP base pointer is not a vector or a vector of pointers", &GEP);
4524 Check(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP);
4525
4526 if (auto *STy = dyn_cast<StructType>(GEP.getSourceElementType())) {
4527 Check(!STy->isScalableTy(),
4528 "getelementptr cannot target structure that contains scalable vector"
4529 "type",
4530 &GEP);
4531 }
4532
4533 SmallVector<Value *, 16> Idxs(GEP.indices());
4534 Check(
4535 all_of(Idxs, [](Value *V) { return V->getType()->isIntOrIntVectorTy(); }),
4536 "GEP indexes must be integers", &GEP);
4537 Type *ElTy =
4538 GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs);
4539 Check(ElTy, "Invalid indices for GEP pointer type!", &GEP);
4540
4541 PointerType *PtrTy = dyn_cast<PointerType>(GEP.getType()->getScalarType());
4542
4543 Check(PtrTy && GEP.getResultElementType() == ElTy,
4544 "GEP is not of right type for indices!", &GEP, ElTy);
4545
4546 if (auto *GEPVTy = dyn_cast<VectorType>(GEP.getType())) {
4547 // Additional checks for vector GEPs.
4548 ElementCount GEPWidth = GEPVTy->getElementCount();
4549 if (GEP.getPointerOperandType()->isVectorTy())
4550 Check(
4551 GEPWidth ==
4552 cast<VectorType>(GEP.getPointerOperandType())->getElementCount(),
4553 "Vector GEP result width doesn't match operand's", &GEP);
4554 for (Value *Idx : Idxs) {
4555 Type *IndexTy = Idx->getType();
4556 if (auto *IndexVTy = dyn_cast<VectorType>(IndexTy)) {
4557 ElementCount IndexWidth = IndexVTy->getElementCount();
4558 Check(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP);
4559 }
4560 Check(IndexTy->isIntOrIntVectorTy(),
4561 "All GEP indices should be of integer type");
4562 }
4563 }
4564
4565 // Check that GEP does not index into a vector with non-byte-addressable
4566 // elements.
4568 GTI != GTE; ++GTI) {
4569 if (GTI.isVector()) {
4570 Type *ElemTy = GTI.getIndexedType();
4571 Check(DL.typeSizeEqualsStoreSize(ElemTy),
4572 "GEP into vector with non-byte-addressable element type", &GEP);
4573 }
4574 }
4575
4576 Check(GEP.getAddressSpace() == PtrTy->getAddressSpace(),
4577 "GEP address space doesn't match type", &GEP);
4578
4579 visitInstruction(GEP);
4580}
4581
4582static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
4583 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
4584}
4585
4586/// Verify !range and !absolute_symbol metadata. These have the same
4587/// restrictions, except !absolute_symbol allows the full set.
4588void Verifier::verifyRangeLikeMetadata(const Value &I, const MDNode *Range,
4589 Type *Ty, RangeLikeMetadataKind Kind) {
4590 unsigned NumOperands = Range->getNumOperands();
4591 Check(NumOperands % 2 == 0, "Unfinished range!", Range);
4592 unsigned NumRanges = NumOperands / 2;
4593 Check(NumRanges >= 1, "It should have at least one range!", Range);
4594
4595 ConstantRange LastRange(1, true); // Dummy initial value
4596 for (unsigned i = 0; i < NumRanges; ++i) {
4597 ConstantInt *Low =
4598 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
4599 Check(Low, "The lower limit must be an integer!", Low);
4600 ConstantInt *High =
4601 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
4602 Check(High, "The upper limit must be an integer!", High);
4603
4604 Check(High->getType() == Low->getType(), "Range pair types must match!",
4605 &I);
4606
4607 if (Kind == RangeLikeMetadataKind::NoaliasAddrspace) {
4608 Check(High->getType()->isIntegerTy(32),
4609 "noalias.addrspace type must be i32!", &I);
4610 } else {
4611 Check(High->getType() == Ty->getScalarType(),
4612 "Range types must match instruction type!", &I);
4613 }
4614
4615 APInt HighV = High->getValue();
4616 APInt LowV = Low->getValue();
4617
4618 // ConstantRange asserts if the ranges are the same except for the min/max
4619 // value. Leave the cases it tolerates for the empty range error below.
4620 Check(LowV != HighV || LowV.isMaxValue() || LowV.isMinValue(),
4621 "The upper and lower limits cannot be the same value", &I);
4622
4623 ConstantRange CurRange(LowV, HighV);
4624 Check(!CurRange.isEmptySet() &&
4625 (Kind == RangeLikeMetadataKind::AbsoluteSymbol ||
4626 !CurRange.isFullSet()),
4627 "Range must not be empty!", Range);
4628 if (i != 0) {
4629 Check(CurRange.intersectWith(LastRange).isEmptySet(),
4630 "Intervals are overlapping", Range);
4631 Check(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
4632 Range);
4633 Check(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
4634 Range);
4635 }
4636 LastRange = ConstantRange(LowV, HighV);
4637 }
4638 if (NumRanges > 2) {
4639 APInt FirstLow =
4640 mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
4641 APInt FirstHigh =
4642 mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
4643 ConstantRange FirstRange(FirstLow, FirstHigh);
4644 Check(FirstRange.intersectWith(LastRange).isEmptySet(),
4645 "Intervals are overlapping", Range);
4646 Check(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
4647 Range);
4648 }
4649}
4650
4651void Verifier::visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty) {
4652 assert(Range && Range == I.getMetadata(LLVMContext::MD_range) &&
4653 "precondition violation");
4654 verifyRangeLikeMetadata(I, Range, Ty, RangeLikeMetadataKind::Range);
4655}
4656
4657void Verifier::visitNoFPClassMetadata(Instruction &I, MDNode *NoFPClass,
4658 Type *Ty) {
4659 Check(AttributeFuncs::isNoFPClassCompatibleType(Ty),
4660 "nofpclass only applies to floating-point typed loads", I);
4661
4662 Check(NoFPClass->getNumOperands() == 1,
4663 "nofpclass must have exactly one entry", NoFPClass);
4664 ConstantInt *MaskVal =
4666 Check(MaskVal && MaskVal->getType()->isIntegerTy(32),
4667 "nofpclass entry must be a constant i32", NoFPClass);
4668 uint32_t Val = MaskVal->getZExtValue();
4669 Check(Val != 0, "'nofpclass' must have at least one test bit set", NoFPClass,
4670 I);
4671
4672 Check((Val & ~static_cast<unsigned>(fcAllFlags)) == 0,
4673 "Invalid value for 'nofpclass' test mask", NoFPClass, I);
4674}
4675
4676void Verifier::visitNoaliasAddrspaceMetadata(Instruction &I, MDNode *Range,
4677 Type *Ty) {
4678 assert(Range && Range == I.getMetadata(LLVMContext::MD_noalias_addrspace) &&
4679 "precondition violation");
4680 verifyRangeLikeMetadata(I, Range, Ty,
4681 RangeLikeMetadataKind::NoaliasAddrspace);
4682}
4683
4684void Verifier::checkAtomicMemAccessSize(Type *Ty, const Instruction *I) {
4685 unsigned Size = DL.getTypeSizeInBits(Ty).getFixedValue();
4686 Check(Size >= 8, "atomic memory access' size must be byte-sized", Ty, I);
4687 Check(!(Size & (Size - 1)),
4688 "atomic memory access' operand must have a power-of-two size", Ty, I);
4689}
4690
4691void Verifier::visitLoadInst(LoadInst &LI) {
4693 Check(PTy, "Load operand must be a pointer.", &LI);
4694 Type *ElTy = LI.getType();
4695 if (MaybeAlign A = LI.getAlign()) {
4696 Check(A->value() <= Value::MaximumAlignment,
4697 "huge alignment values are unsupported", &LI);
4698 }
4699 Check(ElTy->isSized(), "loading unsized types is not allowed", &LI);
4700 if (LI.isAtomic()) {
4701 Check(LI.getOrdering() != AtomicOrdering::Release &&
4702 LI.getOrdering() != AtomicOrdering::AcquireRelease,
4703 "Load cannot have Release ordering", &LI);
4704 Check(ElTy->getScalarType()->isIntOrPtrTy() ||
4705 ElTy->getScalarType()->isByteTy() ||
4707 "atomic load operand must have integer, byte, pointer, floating "
4708 "point, or vector type!",
4709 ElTy, &LI);
4710
4711 checkAtomicMemAccessSize(ElTy, &LI);
4712 } else {
4714 "Non-atomic load cannot have SynchronizationScope specified", &LI);
4715 }
4716
4717 visitInstruction(LI);
4718}
4719
4720void Verifier::visitStoreInst(StoreInst &SI) {
4721 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
4722 Check(PTy, "Store operand must be a pointer.", &SI);
4723 Type *ElTy = SI.getOperand(0)->getType();
4724 if (MaybeAlign A = SI.getAlign()) {
4725 Check(A->value() <= Value::MaximumAlignment,
4726 "huge alignment values are unsupported", &SI);
4727 }
4728 Check(ElTy->isSized(), "storing unsized types is not allowed", &SI);
4729 if (SI.isAtomic()) {
4730 Check(SI.getOrdering() != AtomicOrdering::Acquire &&
4731 SI.getOrdering() != AtomicOrdering::AcquireRelease,
4732 "Store cannot have Acquire ordering", &SI);
4733 Check(ElTy->getScalarType()->isIntOrPtrTy() ||
4734 ElTy->getScalarType()->isByteTy() ||
4736 "atomic store operand must have integer, byte, pointer, floating "
4737 "point, or vector type!",
4738 ElTy, &SI);
4739 checkAtomicMemAccessSize(ElTy, &SI);
4740 } else {
4741 Check(SI.getSyncScopeID() == SyncScope::System,
4742 "Non-atomic store cannot have SynchronizationScope specified", &SI);
4743 }
4744 visitInstruction(SI);
4745}
4746
4747/// Check that SwiftErrorVal is used as a swifterror argument in CS.
4748void Verifier::verifySwiftErrorCall(CallBase &Call,
4749 const Value *SwiftErrorVal) {
4750 for (const auto &I : llvm::enumerate(Call.args())) {
4751 if (I.value() == SwiftErrorVal) {
4752 Check(Call.paramHasAttr(I.index(), Attribute::SwiftError),
4753 "swifterror value when used in a callsite should be marked "
4754 "with swifterror attribute",
4755 SwiftErrorVal, Call);
4756 }
4757 }
4758}
4759
4760void Verifier::verifySwiftErrorValue(const Value *SwiftErrorVal) {
4761 // Check that swifterror value is only used by loads, stores, or as
4762 // a swifterror argument.
4763 for (const User *U : SwiftErrorVal->users()) {
4765 isa<InvokeInst>(U),
4766 "swifterror value can only be loaded and stored from, or "
4767 "as a swifterror argument!",
4768 SwiftErrorVal, U);
4769 // If it is used by a store, check it is the second operand.
4770 if (auto StoreI = dyn_cast<StoreInst>(U))
4771 Check(StoreI->getOperand(1) == SwiftErrorVal,
4772 "swifterror value should be the second operand when used "
4773 "by stores",
4774 SwiftErrorVal, U);
4775 if (auto *Call = dyn_cast<CallBase>(U))
4776 verifySwiftErrorCall(*const_cast<CallBase *>(Call), SwiftErrorVal);
4777 }
4778}
4779
4780void Verifier::visitAllocaInst(AllocaInst &AI) {
4782 AI.getModule()->getModuleFlag("require-logical-pointer")))
4783 Check(!MD->getZExtValue(),
4784 "Non-logical alloca disallowed for this module.");
4785
4786 Type *Ty = AI.getAllocatedType();
4787 SmallPtrSet<Type*, 4> Visited;
4788 Check(Ty->isSized(&Visited), "Cannot allocate unsized type", &AI);
4789 // Check if it's a target extension type that disallows being used on the
4790 // stack.
4792 "Alloca has illegal target extension type", &AI);
4794 "Alloca array size must have integer type", &AI);
4795 if (MaybeAlign A = AI.getAlign()) {
4796 Check(A->value() <= Value::MaximumAlignment,
4797 "huge alignment values are unsupported", &AI);
4798 }
4799
4800 if (AI.isSwiftError()) {
4801 Check(Ty->isPointerTy(), "swifterror alloca must have pointer type", &AI);
4803 "swifterror alloca must not be array allocation", &AI);
4804 verifySwiftErrorValue(&AI);
4805 }
4806
4807 if (TT.isAMDGPU()) {
4809 "alloca on amdgpu must be in addrspace(5)", &AI);
4810 }
4811
4812 visitInstruction(AI);
4813}
4814
4815void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
4816 Type *ElTy = CXI.getOperand(1)->getType();
4817 Check(ElTy->isIntOrPtrTy(),
4818 "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
4819 checkAtomicMemAccessSize(ElTy, &CXI);
4820 visitInstruction(CXI);
4821}
4822
4823void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
4824 Check(RMWI.getOrdering() != AtomicOrdering::Unordered,
4825 "atomicrmw instructions cannot be unordered.", &RMWI);
4826 auto Op = RMWI.getOperation();
4827 Type *ElTy = RMWI.getOperand(1)->getType();
4828 Type *ScalarTy = ElTy;
4829 if (RMWI.isElementwise()) {
4830 auto *VecTy = dyn_cast<FixedVectorType>(ElTy);
4831 Check(VecTy, "atomicrmw elementwise operand must have fixed vector type!",
4832 &RMWI, ElTy);
4833 if (VecTy)
4834 ScalarTy = VecTy->getElementType();
4835 }
4836
4837 if (Op == AtomicRMWInst::Xchg) {
4838 Check(ScalarTy->isIntegerTy() || ScalarTy->isFloatingPointTy() ||
4839 ScalarTy->isPointerTy(),
4840 "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
4841 " operand must have integer or floating point type!",
4842 &RMWI, ElTy);
4843 } else if (AtomicRMWInst::isFPOperation(Op)) {
4845 "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
4846 " operand must have floating-point or fixed vector of "
4847 "floating-point "
4848 "type!",
4849 &RMWI, ElTy);
4850 } else {
4851 Check(ScalarTy->isIntegerTy(),
4852 "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
4853 " operand must have integer type!",
4854 &RMWI, ElTy);
4855 }
4856 checkAtomicMemAccessSize(ElTy, &RMWI);
4858 "Invalid binary operation!", &RMWI);
4859 visitInstruction(RMWI);
4860}
4861
4862void Verifier::visitFenceInst(FenceInst &FI) {
4863 const AtomicOrdering Ordering = FI.getOrdering();
4864 Check(Ordering == AtomicOrdering::Acquire ||
4865 Ordering == AtomicOrdering::Release ||
4866 Ordering == AtomicOrdering::AcquireRelease ||
4867 Ordering == AtomicOrdering::SequentiallyConsistent,
4868 "fence instructions may only have acquire, release, acq_rel, or "
4869 "seq_cst ordering.",
4870 &FI);
4871 visitInstruction(FI);
4872}
4873
4874void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
4876 EVI.getIndices()) == EVI.getType(),
4877 "Invalid ExtractValueInst operands!", &EVI);
4878
4879 visitInstruction(EVI);
4880}
4881
4882void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
4884 IVI.getIndices()) ==
4885 IVI.getOperand(1)->getType(),
4886 "Invalid InsertValueInst operands!", &IVI);
4887
4888 visitInstruction(IVI);
4889}
4890
4891static Value *getParentPad(Value *EHPad) {
4892 if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
4893 return FPI->getParentPad();
4894
4895 return cast<CatchSwitchInst>(EHPad)->getParentPad();
4896}
4897
4898void Verifier::visitEHPadPredecessors(Instruction &I) {
4899 assert(I.isEHPad());
4900
4901 BasicBlock *BB = I.getParent();
4902 Function *F = BB->getParent();
4903
4904 Check(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I);
4905
4906 if (auto *LPI = dyn_cast<LandingPadInst>(&I)) {
4907 // The landingpad instruction defines its parent as a landing pad block. The
4908 // landing pad block may be branched to only by the unwind edge of an
4909 // invoke.
4910 for (BasicBlock *PredBB : predecessors(BB)) {
4911 const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator());
4912 Check(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
4913 "Block containing LandingPadInst must be jumped to "
4914 "only by the unwind edge of an invoke.",
4915 LPI);
4916 }
4917 return;
4918 }
4919 if (auto *CPI = dyn_cast<CatchPadInst>(&I)) {
4920 if (!pred_empty(BB))
4921 Check(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(),
4922 "Block containg CatchPadInst must be jumped to "
4923 "only by its catchswitch.",
4924 CPI);
4925 Check(BB != CPI->getCatchSwitch()->getUnwindDest(),
4926 "Catchswitch cannot unwind to one of its catchpads",
4927 CPI->getCatchSwitch(), CPI);
4928 return;
4929 }
4930
4931 // Verify that each pred has a legal terminator with a legal to/from EH
4932 // pad relationship.
4933 Instruction *ToPad = &I;
4934 Value *ToPadParent = getParentPad(ToPad);
4935 for (BasicBlock *PredBB : predecessors(BB)) {
4936 Instruction *TI = PredBB->getTerminator();
4937 Value *FromPad;
4938 if (auto *II = dyn_cast<InvokeInst>(TI)) {
4939 Check(II->getUnwindDest() == BB && II->getNormalDest() != BB,
4940 "EH pad must be jumped to via an unwind edge", ToPad, II);
4941 auto *CalledFn =
4942 dyn_cast<Function>(II->getCalledOperand()->stripPointerCasts());
4943 if (CalledFn && CalledFn->isIntrinsic() && II->doesNotThrow() &&
4944 !IntrinsicInst::mayLowerToFunctionCall(CalledFn->getIntrinsicID()))
4945 continue;
4946 if (auto Bundle = II->getOperandBundle(LLVMContext::OB_funclet))
4947 FromPad = Bundle->Inputs[0];
4948 else
4949 FromPad = ConstantTokenNone::get(II->getContext());
4950 } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
4951 FromPad = CRI->getOperand(0);
4952 Check(FromPad != ToPadParent, "A cleanupret must exit its cleanup", CRI);
4953 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
4954 FromPad = CSI;
4955 } else {
4956 Check(false, "EH pad must be jumped to via an unwind edge", ToPad, TI);
4957 }
4958
4959 // The edge may exit from zero or more nested pads.
4960 SmallPtrSet<Value *, 8> Seen;
4961 for (;; FromPad = getParentPad(FromPad)) {
4962 Check(FromPad != ToPad,
4963 "EH pad cannot handle exceptions raised within it", FromPad, TI);
4964 if (FromPad == ToPadParent) {
4965 // This is a legal unwind edge.
4966 break;
4967 }
4968 Check(!isa<ConstantTokenNone>(FromPad),
4969 "A single unwind edge may only enter one EH pad", TI);
4970 Check(Seen.insert(FromPad).second, "EH pad jumps through a cycle of pads",
4971 FromPad);
4972
4973 // This will be diagnosed on the corresponding instruction already. We
4974 // need the extra check here to make sure getParentPad() works.
4975 Check(isa<FuncletPadInst>(FromPad) || isa<CatchSwitchInst>(FromPad),
4976 "Parent pad must be catchpad/cleanuppad/catchswitch", TI);
4977 }
4978 }
4979}
4980
4981void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
4982 // The landingpad instruction is ill-formed if it doesn't have any clauses and
4983 // isn't a cleanup.
4984 Check(LPI.getNumClauses() > 0 || LPI.isCleanup(),
4985 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
4986
4987 visitEHPadPredecessors(LPI);
4988
4989 if (!LandingPadResultTy)
4990 LandingPadResultTy = LPI.getType();
4991 else
4992 Check(LandingPadResultTy == LPI.getType(),
4993 "The landingpad instruction should have a consistent result type "
4994 "inside a function.",
4995 &LPI);
4996
4997 Function *F = LPI.getParent()->getParent();
4998 Check(F->hasPersonalityFn(),
4999 "LandingPadInst needs to be in a function with a personality.", &LPI);
5000
5001 // The landingpad instruction must be the first non-PHI instruction in the
5002 // block.
5003 Check(LPI.getParent()->getLandingPadInst() == &LPI,
5004 "LandingPadInst not the first non-PHI instruction in the block.", &LPI);
5005
5006 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
5007 Constant *Clause = LPI.getClause(i);
5008 if (LPI.isCatch(i)) {
5009 Check(isa<PointerType>(Clause->getType()),
5010 "Catch operand does not have pointer type!", &LPI);
5011 } else {
5012 Check(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
5014 "Filter operand is not an array of constants!", &LPI);
5015 }
5016 }
5017
5018 visitInstruction(LPI);
5019}
5020
5021void Verifier::visitResumeInst(ResumeInst &RI) {
5023 "ResumeInst needs to be in a function with a personality.", &RI);
5024
5025 if (!LandingPadResultTy)
5026 LandingPadResultTy = RI.getValue()->getType();
5027 else
5028 Check(LandingPadResultTy == RI.getValue()->getType(),
5029 "The resume instruction should have a consistent result type "
5030 "inside a function.",
5031 &RI);
5032
5033 visitTerminator(RI);
5034}
5035
5036void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
5037 BasicBlock *BB = CPI.getParent();
5038
5039 Function *F = BB->getParent();
5040 Check(F->hasPersonalityFn(),
5041 "CatchPadInst needs to be in a function with a personality.", &CPI);
5042
5044 "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
5045 CPI.getParentPad());
5046
5047 // The catchpad instruction must be the first non-PHI instruction in the
5048 // block.
5049 Check(&*BB->getFirstNonPHIIt() == &CPI,
5050 "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
5051
5053 [](Use &U) {
5054 auto *V = U.get();
5055 return isa<Constant>(V) || isa<AllocaInst>(V);
5056 }),
5057 "Argument operand must be alloca or constant.", &CPI);
5058
5059 visitEHPadPredecessors(CPI);
5060 visitFuncletPadInst(CPI);
5061}
5062
5063void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
5064 Check(isa<CatchPadInst>(CatchReturn.getOperand(0)),
5065 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
5066 CatchReturn.getOperand(0));
5067
5068 visitTerminator(CatchReturn);
5069}
5070
5071void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
5072 BasicBlock *BB = CPI.getParent();
5073
5074 Function *F = BB->getParent();
5075 Check(F->hasPersonalityFn(),
5076 "CleanupPadInst needs to be in a function with a personality.", &CPI);
5077
5078 // The cleanuppad instruction must be the first non-PHI instruction in the
5079 // block.
5080 Check(&*BB->getFirstNonPHIIt() == &CPI,
5081 "CleanupPadInst not the first non-PHI instruction in the block.", &CPI);
5082
5083 auto *ParentPad = CPI.getParentPad();
5084 Check(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
5085 "CleanupPadInst has an invalid parent.", &CPI);
5086
5087 visitEHPadPredecessors(CPI);
5088 visitFuncletPadInst(CPI);
5089}
5090
5091void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
5092 User *FirstUser = nullptr;
5093 Value *FirstUnwindPad = nullptr;
5094 SmallVector<FuncletPadInst *, 8> Worklist({&FPI});
5095 SmallPtrSet<FuncletPadInst *, 8> Seen;
5096
5097 while (!Worklist.empty()) {
5098 FuncletPadInst *CurrentPad = Worklist.pop_back_val();
5099 Check(Seen.insert(CurrentPad).second,
5100 "FuncletPadInst must not be nested within itself", CurrentPad);
5101 Value *UnresolvedAncestorPad = nullptr;
5102 for (User *U : CurrentPad->users()) {
5103 BasicBlock *UnwindDest;
5104 if (auto *CRI = dyn_cast<CleanupReturnInst>(U)) {
5105 UnwindDest = CRI->getUnwindDest();
5106 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(U)) {
5107 // We allow catchswitch unwind to caller to nest
5108 // within an outer pad that unwinds somewhere else,
5109 // because catchswitch doesn't have a nounwind variant.
5110 // See e.g. SimplifyCFGOpt::SimplifyUnreachable.
5111 if (CSI->unwindsToCaller())
5112 continue;
5113 UnwindDest = CSI->getUnwindDest();
5114 } else if (auto *II = dyn_cast<InvokeInst>(U)) {
5115 UnwindDest = II->getUnwindDest();
5116 } else if (isa<CallInst>(U)) {
5117 // Calls which don't unwind may be found inside funclet
5118 // pads that unwind somewhere else. We don't *require*
5119 // such calls to be annotated nounwind.
5120 continue;
5121 } else if (auto *CPI = dyn_cast<CleanupPadInst>(U)) {
5122 // The unwind dest for a cleanup can only be found by
5123 // recursive search. Add it to the worklist, and we'll
5124 // search for its first use that determines where it unwinds.
5125 Worklist.push_back(CPI);
5126 continue;
5127 } else {
5128 Check(isa<CatchReturnInst>(U), "Bogus funclet pad use", U);
5129 continue;
5130 }
5131
5132 Value *UnwindPad;
5133 bool ExitsFPI;
5134 if (UnwindDest) {
5135 UnwindPad = &*UnwindDest->getFirstNonPHIIt();
5136 if (!cast<Instruction>(UnwindPad)->isEHPad())
5137 continue;
5138 Value *UnwindParent = getParentPad(UnwindPad);
5139 // Ignore unwind edges that don't exit CurrentPad.
5140 if (UnwindParent == CurrentPad)
5141 continue;
5142 // Determine whether the original funclet pad is exited,
5143 // and if we are scanning nested pads determine how many
5144 // of them are exited so we can stop searching their
5145 // children.
5146 Value *ExitedPad = CurrentPad;
5147 ExitsFPI = false;
5148 do {
5149 if (ExitedPad == &FPI) {
5150 ExitsFPI = true;
5151 // Now we can resolve any ancestors of CurrentPad up to
5152 // FPI, but not including FPI since we need to make sure
5153 // to check all direct users of FPI for consistency.
5154 UnresolvedAncestorPad = &FPI;
5155 break;
5156 }
5157 Value *ExitedParent = getParentPad(ExitedPad);
5158 if (ExitedParent == UnwindParent) {
5159 // ExitedPad is the ancestor-most pad which this unwind
5160 // edge exits, so we can resolve up to it, meaning that
5161 // ExitedParent is the first ancestor still unresolved.
5162 UnresolvedAncestorPad = ExitedParent;
5163 break;
5164 }
5165 ExitedPad = ExitedParent;
5166 } while (!isa<ConstantTokenNone>(ExitedPad));
5167 } else {
5168 // Unwinding to caller exits all pads.
5169 UnwindPad = ConstantTokenNone::get(FPI.getContext());
5170 ExitsFPI = true;
5171 UnresolvedAncestorPad = &FPI;
5172 }
5173
5174 if (ExitsFPI) {
5175 // This unwind edge exits FPI. Make sure it agrees with other
5176 // such edges.
5177 if (FirstUser) {
5178 Check(UnwindPad == FirstUnwindPad,
5179 "Unwind edges out of a funclet "
5180 "pad must have the same unwind "
5181 "dest",
5182 &FPI, U, FirstUser);
5183 } else {
5184 FirstUser = U;
5185 FirstUnwindPad = UnwindPad;
5186 // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds
5187 if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) &&
5188 getParentPad(UnwindPad) == getParentPad(&FPI))
5189 SiblingFuncletInfo[&FPI] = cast<Instruction>(U);
5190 }
5191 }
5192 // Make sure we visit all uses of FPI, but for nested pads stop as
5193 // soon as we know where they unwind to.
5194 if (CurrentPad != &FPI)
5195 break;
5196 }
5197 if (UnresolvedAncestorPad) {
5198 if (CurrentPad == UnresolvedAncestorPad) {
5199 // When CurrentPad is FPI itself, we don't mark it as resolved even if
5200 // we've found an unwind edge that exits it, because we need to verify
5201 // all direct uses of FPI.
5202 assert(CurrentPad == &FPI);
5203 continue;
5204 }
5205 // Pop off the worklist any nested pads that we've found an unwind
5206 // destination for. The pads on the worklist are the uncles,
5207 // great-uncles, etc. of CurrentPad. We've found an unwind destination
5208 // for all ancestors of CurrentPad up to but not including
5209 // UnresolvedAncestorPad.
5210 Value *ResolvedPad = CurrentPad;
5211 while (!Worklist.empty()) {
5212 Value *UnclePad = Worklist.back();
5213 Value *AncestorPad = getParentPad(UnclePad);
5214 // Walk ResolvedPad up the ancestor list until we either find the
5215 // uncle's parent or the last resolved ancestor.
5216 while (ResolvedPad != AncestorPad) {
5217 Value *ResolvedParent = getParentPad(ResolvedPad);
5218 if (ResolvedParent == UnresolvedAncestorPad) {
5219 break;
5220 }
5221 ResolvedPad = ResolvedParent;
5222 }
5223 // If the resolved ancestor search didn't find the uncle's parent,
5224 // then the uncle is not yet resolved.
5225 if (ResolvedPad != AncestorPad)
5226 break;
5227 // This uncle is resolved, so pop it from the worklist.
5228 Worklist.pop_back();
5229 }
5230 }
5231 }
5232
5233 if (FirstUnwindPad) {
5234 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.getParentPad())) {
5235 BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
5236 Value *SwitchUnwindPad;
5237 if (SwitchUnwindDest)
5238 SwitchUnwindPad = &*SwitchUnwindDest->getFirstNonPHIIt();
5239 else
5240 SwitchUnwindPad = ConstantTokenNone::get(FPI.getContext());
5241 Check(SwitchUnwindPad == FirstUnwindPad,
5242 "Unwind edges out of a catch must have the same unwind dest as "
5243 "the parent catchswitch",
5244 &FPI, FirstUser, CatchSwitch);
5245 }
5246 }
5247
5248 visitInstruction(FPI);
5249}
5250
5251void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
5252 BasicBlock *BB = CatchSwitch.getParent();
5253
5254 Function *F = BB->getParent();
5255 Check(F->hasPersonalityFn(),
5256 "CatchSwitchInst needs to be in a function with a personality.",
5257 &CatchSwitch);
5258
5259 // The catchswitch instruction must be the first non-PHI instruction in the
5260 // block.
5261 Check(&*BB->getFirstNonPHIIt() == &CatchSwitch,
5262 "CatchSwitchInst not the first non-PHI instruction in the block.",
5263 &CatchSwitch);
5264
5265 auto *ParentPad = CatchSwitch.getParentPad();
5266 Check(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
5267 "CatchSwitchInst has an invalid parent.", ParentPad);
5268
5269 if (BasicBlock *UnwindDest = CatchSwitch.getUnwindDest()) {
5270 BasicBlock::iterator I = UnwindDest->getFirstNonPHIIt();
5271 Check(I->isEHPad() && !isa<LandingPadInst>(I),
5272 "CatchSwitchInst must unwind to an EH block which is not a "
5273 "landingpad.",
5274 &CatchSwitch);
5275
5276 // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds
5277 if (getParentPad(&*I) == ParentPad)
5278 SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
5279 }
5280
5281 Check(CatchSwitch.getNumHandlers() != 0,
5282 "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
5283
5284 for (BasicBlock *Handler : CatchSwitch.handlers()) {
5285 Check(isa<CatchPadInst>(Handler->getFirstNonPHIIt()),
5286 "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
5287 }
5288
5289 visitEHPadPredecessors(CatchSwitch);
5290 visitTerminator(CatchSwitch);
5291}
5292
5293void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
5295 "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
5296 CRI.getOperand(0));
5297
5298 if (BasicBlock *UnwindDest = CRI.getUnwindDest()) {
5299 BasicBlock::iterator I = UnwindDest->getFirstNonPHIIt();
5300 Check(I->isEHPad() && !isa<LandingPadInst>(I),
5301 "CleanupReturnInst must unwind to an EH block which is not a "
5302 "landingpad.",
5303 &CRI);
5304 }
5305
5306 visitTerminator(CRI);
5307}
5308
5309void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
5310 Instruction *Op = cast<Instruction>(I.getOperand(i));
5311 // If the we have an invalid invoke, don't try to compute the dominance.
5312 // We already reject it in the invoke specific checks and the dominance
5313 // computation doesn't handle multiple edges.
5314 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
5315 if (II->getNormalDest() == II->getUnwindDest())
5316 return;
5317 }
5318
5319 // Quick check whether the def has already been encountered in the same block.
5320 // PHI nodes are not checked to prevent accepting preceding PHIs, because PHI
5321 // uses are defined to happen on the incoming edge, not at the instruction.
5322 //
5323 // FIXME: If this operand is a MetadataAsValue (wrapping a LocalAsMetadata)
5324 // wrapping an SSA value, assert that we've already encountered it. See
5325 // related FIXME in Mapper::mapLocalAsMetadata in ValueMapper.cpp.
5326 if (!isa<PHINode>(I) && InstsInThisBlock.count(Op))
5327 return;
5328
5329 const Use &U = I.getOperandUse(i);
5330 Check(DT.dominates(Op, U), "Instruction does not dominate all uses!", Op, &I);
5331}
5332
5333void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) {
5334 Check(I.getType()->isPointerTy(),
5335 "dereferenceable, dereferenceable_or_null "
5336 "apply only to pointer types",
5337 &I);
5339 "dereferenceable, dereferenceable_or_null apply only to load"
5340 " and inttoptr instructions, use attributes for calls or invokes",
5341 &I);
5342 Check(MD->getNumOperands() == 1,
5343 "dereferenceable, dereferenceable_or_null "
5344 "take one operand!",
5345 &I);
5346 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
5347 Check(CI && CI->getType()->isIntegerTy(64),
5348 "dereferenceable, "
5349 "dereferenceable_or_null metadata value must be an i64!",
5350 &I);
5351}
5352
5353void Verifier::visitNofreeMetadata(Instruction &I, MDNode *MD) {
5354 Check(I.getType()->isPointerTy(), "nofree applies only to pointer types", &I);
5355 Check((isa<IntToPtrInst>(I)), "nofree applies only to inttoptr instruction",
5356 &I);
5357 Check(MD->getNumOperands() == 0, "nofree metadata must be empty", &I);
5358}
5359
5360void Verifier::visitProfMetadata(Instruction &I, MDNode *MD) {
5361 auto GetBranchingTerminatorNumOperands = [&]() {
5362 unsigned ExpectedNumOperands = 0;
5363 if (CondBrInst *BI = dyn_cast<CondBrInst>(&I))
5364 ExpectedNumOperands = BI->getNumSuccessors();
5365 else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
5366 ExpectedNumOperands = SI->getNumSuccessors();
5367 else if (isa<CallInst>(&I))
5368 ExpectedNumOperands = 1;
5369 else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
5370 ExpectedNumOperands = IBI->getNumDestinations();
5371 else if (isa<SelectInst>(&I))
5372 ExpectedNumOperands = 2;
5373 else if (CallBrInst *CI = dyn_cast<CallBrInst>(&I))
5374 ExpectedNumOperands = CI->getNumSuccessors();
5375 return ExpectedNumOperands;
5376 };
5377 Check(MD->getNumOperands() >= 1,
5378 "!prof annotations should have at least 1 operand", MD);
5379 // Check first operand.
5380 Check(MD->getOperand(0) != nullptr, "first operand should not be null", MD);
5382 "expected string with name of the !prof annotation", MD);
5383 MDString *MDS = cast<MDString>(MD->getOperand(0));
5384 StringRef ProfName = MDS->getString();
5385
5387 Check(GetBranchingTerminatorNumOperands() != 0 || isa<InvokeInst>(I),
5388 "'unknown' !prof should only appear on instructions on which "
5389 "'branch_weights' would",
5390 MD);
5391 verifyUnknownProfileMetadata(MD);
5392 return;
5393 }
5394
5395 Check(MD->getNumOperands() >= 2,
5396 "!prof annotations should have no less than 2 operands", MD);
5397
5398 // Check consistency of !prof branch_weights metadata.
5399 if (ProfName == MDProfLabels::BranchWeights) {
5400 unsigned NumBranchWeights = getNumBranchWeights(*MD);
5401 if (isa<InvokeInst>(&I)) {
5402 Check(NumBranchWeights == 1 || NumBranchWeights == 2,
5403 "Wrong number of InvokeInst branch_weights operands", MD);
5404 } else {
5405 const unsigned ExpectedNumOperands = GetBranchingTerminatorNumOperands();
5406 if (ExpectedNumOperands == 0)
5407 CheckFailed("!prof branch_weights are not allowed for this instruction",
5408 MD);
5409
5410 Check(NumBranchWeights == ExpectedNumOperands, "Wrong number of operands",
5411 MD);
5412 }
5413 for (unsigned i = getBranchWeightOffset(MD); i < MD->getNumOperands();
5414 ++i) {
5415 auto &MDO = MD->getOperand(i);
5416 Check(MDO, "second operand should not be null", MD);
5418 "!prof brunch_weights operand is not a const int");
5419 }
5420 } else if (ProfName == MDProfLabels::ValueProfile) {
5421 Check(isValueProfileMD(MD), "invalid value profiling metadata", MD);
5422 ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
5423 Check(KindInt, "VP !prof missing kind argument", MD);
5424
5425 auto Kind = KindInt->getZExtValue();
5426 Check(Kind >= InstrProfValueKind::IPVK_First &&
5427 Kind <= InstrProfValueKind::IPVK_Last,
5428 "Invalid VP !prof kind", MD);
5429 Check(MD->getNumOperands() % 2 == 1,
5430 "VP !prof should have an even number "
5431 "of arguments after 'VP'",
5432 MD);
5433 if (Kind == InstrProfValueKind::IPVK_IndirectCallTarget ||
5434 Kind == InstrProfValueKind::IPVK_MemOPSize)
5436 "VP !prof indirect call or memop size expected to be applied to "
5437 "CallBase instructions only",
5438 MD);
5439
5440 DenseSet<uint64_t> ProfileValues;
5441 for (unsigned I = 3; I < MD->getNumOperands(); I += 2) {
5442 ConstantInt *ProfileValue =
5444 Check(ProfileValue, "VP !prof value operand is not a const int", MD);
5445 uint64_t ProfileValueInt = ProfileValue->getZExtValue();
5446 auto [ValueIt, Inserted] = ProfileValues.insert(ProfileValueInt);
5447 Check(Inserted, "VP !prof should not have duplicate profile values", MD);
5448 }
5449 } else {
5450 CheckFailed("expected either branch_weights or VP profile name", MD);
5451 }
5452}
5453
5454void Verifier::visitDIAssignIDMetadata(Instruction &I, MDNode *MD) {
5455 assert(I.hasMetadata(LLVMContext::MD_DIAssignID));
5456 // DIAssignID metadata must be attached to either an alloca or some form of
5457 // store/memory-writing instruction.
5458 // FIXME: We allow all intrinsic insts here to avoid trying to enumerate all
5459 // possible store intrinsics.
5460 bool ExpectedInstTy =
5462 CheckDI(ExpectedInstTy, "!DIAssignID attached to unexpected instruction kind",
5463 I, MD);
5464 // Iterate over the MetadataAsValue uses of the DIAssignID - these should
5465 // only be found as DbgAssignIntrinsic operands.
5466 if (auto *AsValue = MetadataAsValue::getIfExists(Context, MD)) {
5467 for (auto *User : AsValue->users()) {
5469 "!DIAssignID should only be used by llvm.dbg.assign intrinsics",
5470 MD, User);
5471 // All of the dbg.assign intrinsics should be in the same function as I.
5472 if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(User))
5473 CheckDI(DAI->getFunction() == I.getFunction(),
5474 "dbg.assign not in same function as inst", DAI, &I);
5475 }
5476 }
5477 for (DbgVariableRecord *DVR :
5478 cast<DIAssignID>(MD)->getAllDbgVariableRecordUsers()) {
5479 CheckDI(DVR->isDbgAssign(),
5480 "!DIAssignID should only be used by Assign DVRs.", MD, DVR);
5481 CheckDI(DVR->getFunction() == I.getFunction(),
5482 "DVRAssign not in same function as inst", DVR, &I);
5483 }
5484}
5485
5486void Verifier::visitMMRAMetadata(Instruction &I, MDNode *MD) {
5488 "!mmra metadata attached to unexpected instruction kind", I, MD);
5489
5490 // MMRA Metadata should either be a tag, e.g. !{!"foo", !"bar"}, or a
5491 // list of tags such as !2 in the following example:
5492 // !0 = !{!"a", !"b"}
5493 // !1 = !{!"c", !"d"}
5494 // !2 = !{!0, !1}
5495 if (MMRAMetadata::isTagMD(MD))
5496 return;
5497
5498 Check(isa<MDTuple>(MD), "!mmra expected to be a metadata tuple", I, MD);
5499 for (const MDOperand &MDOp : MD->operands())
5500 Check(MMRAMetadata::isTagMD(MDOp.get()),
5501 "!mmra metadata tuple operand is not an MMRA tag", I, MDOp.get());
5502}
5503
5504void Verifier::visitCallStackMetadata(MDNode *MD) {
5505 // Call stack metadata should consist of a list of at least 1 constant int
5506 // (representing a hash of the location).
5507 Check(MD->getNumOperands() >= 1,
5508 "call stack metadata should have at least 1 operand", MD);
5509
5510 for (const auto &Op : MD->operands())
5512 "call stack metadata operand should be constant integer", Op);
5513}
5514
5515void Verifier::visitMemProfMetadata(Instruction &I, MDNode *MD) {
5516 Check(isa<CallBase>(I), "!memprof metadata should only exist on calls", &I);
5517 Check(MD->getNumOperands() >= 1,
5518 "!memprof annotations should have at least 1 metadata operand "
5519 "(MemInfoBlock)",
5520 MD);
5521
5522 // Check each MIB
5523 for (auto &MIBOp : MD->operands()) {
5524 MDNode *MIB = dyn_cast<MDNode>(MIBOp);
5525 // The first operand of an MIB should be the call stack metadata.
5526 // There rest of the operands should be MDString tags, and there should be
5527 // at least one.
5528 Check(MIB->getNumOperands() >= 2,
5529 "Each !memprof MemInfoBlock should have at least 2 operands", MIB);
5530
5531 // Check call stack metadata (first operand).
5532 Check(MIB->getOperand(0) != nullptr,
5533 "!memprof MemInfoBlock first operand should not be null", MIB);
5534 Check(isa<MDNode>(MIB->getOperand(0)),
5535 "!memprof MemInfoBlock first operand should be an MDNode", MIB);
5536 MDNode *StackMD = dyn_cast<MDNode>(MIB->getOperand(0));
5537 visitCallStackMetadata(StackMD);
5538
5539 // The second MIB operand should be MDString.
5541 "!memprof MemInfoBlock second operand should be an MDString", MIB);
5542
5543 // Any remaining should be MDNode that are pairs of integers
5544 for (unsigned I = 2; I < MIB->getNumOperands(); ++I) {
5545 MDNode *OpNode = dyn_cast<MDNode>(MIB->getOperand(I));
5546 Check(OpNode, "Not all !memprof MemInfoBlock operands 2 to N are MDNode",
5547 MIB);
5548 Check(OpNode->getNumOperands() == 2,
5549 "Not all !memprof MemInfoBlock operands 2 to N are MDNode with 2 "
5550 "operands",
5551 MIB);
5552 // Check that all of Op's operands are ConstantInt.
5553 Check(llvm::all_of(OpNode->operands(),
5554 [](const MDOperand &Op) {
5555 return mdconst::hasa<ConstantInt>(Op);
5556 }),
5557 "Not all !memprof MemInfoBlock operands 2 to N are MDNode with "
5558 "ConstantInt operands",
5559 MIB);
5560 }
5561 }
5562}
5563
5564void Verifier::visitCallsiteMetadata(Instruction &I, MDNode *MD) {
5565 Check(isa<CallBase>(I), "!callsite metadata should only exist on calls", &I);
5566 // Verify the partial callstack annotated from memprof profiles. This callsite
5567 // is a part of a profiled allocation callstack.
5568 visitCallStackMetadata(MD);
5569}
5570
5571static inline bool isConstantIntMetadataOperand(const Metadata *MD) {
5572 if (auto *VAL = dyn_cast<ValueAsMetadata>(MD))
5573 return isa<ConstantInt>(VAL->getValue());
5574 return false;
5575}
5576
5577void Verifier::visitCalleeTypeMetadata(Instruction &I, MDNode *MD) {
5578 Check(isa<CallBase>(I), "!callee_type metadata should only exist on calls",
5579 &I);
5580 for (Metadata *Op : MD->operands()) {
5582 "The callee_type metadata must be a list of type metadata nodes", Op);
5583 auto *TypeMD = cast<MDNode>(Op);
5584 Check(TypeMD->getNumOperands() == 2,
5585 "Well-formed generalized type metadata must contain exactly two "
5586 "operands",
5587 Op);
5588 Check(isConstantIntMetadataOperand(TypeMD->getOperand(0)) &&
5589 mdconst::extract<ConstantInt>(TypeMD->getOperand(0))->isZero(),
5590 "The first operand of type metadata for functions must be zero", Op);
5591 Check(TypeMD->hasGeneralizedMDString(),
5592 "Only generalized type metadata can be part of the callee_type "
5593 "metadata list",
5594 Op);
5595 }
5596}
5597
5598void Verifier::visitAnnotationMetadata(MDNode *Annotation) {
5599 Check(isa<MDTuple>(Annotation), "annotation must be a tuple");
5600 Check(Annotation->getNumOperands() >= 1,
5601 "annotation must have at least one operand");
5602 for (const MDOperand &Op : Annotation->operands()) {
5603 bool TupleOfStrings =
5604 isa<MDTuple>(Op.get()) &&
5605 all_of(cast<MDTuple>(Op)->operands(), [](auto &Annotation) {
5606 return isa<MDString>(Annotation.get());
5607 });
5608 Check(isa<MDString>(Op.get()) || TupleOfStrings,
5609 "operands must be a string or a tuple of strings");
5610 }
5611}
5612
5613void Verifier::visitAliasScopeMetadata(const MDNode *MD) {
5614 unsigned NumOps = MD->getNumOperands();
5615 Check(NumOps >= 2 && NumOps <= 3, "scope must have two or three operands",
5616 MD);
5617 Check(MD->getOperand(0).get() == MD || isa<MDString>(MD->getOperand(0)),
5618 "first scope operand must be self-referential or string", MD);
5619 if (NumOps == 3)
5621 "third scope operand must be string (if used)", MD);
5622
5623 MDNode *Domain = dyn_cast<MDNode>(MD->getOperand(1));
5624 Check(Domain != nullptr, "second scope operand must be MDNode", MD);
5625
5626 unsigned NumDomainOps = Domain->getNumOperands();
5627 Check(NumDomainOps >= 1 && NumDomainOps <= 2,
5628 "domain must have one or two operands", Domain);
5629 Check(Domain->getOperand(0).get() == Domain ||
5630 isa<MDString>(Domain->getOperand(0)),
5631 "first domain operand must be self-referential or string", Domain);
5632 if (NumDomainOps == 2)
5633 Check(isa<MDString>(Domain->getOperand(1)),
5634 "second domain operand must be string (if used)", Domain);
5635}
5636
5637void Verifier::visitAliasScopeListMetadata(const MDNode *MD) {
5638 for (const MDOperand &Op : MD->operands()) {
5639 const MDNode *OpMD = dyn_cast<MDNode>(Op);
5640 Check(OpMD != nullptr, "scope list must consist of MDNodes", MD);
5641 visitAliasScopeMetadata(OpMD);
5642 }
5643}
5644
5645void Verifier::visitAccessGroupMetadata(const MDNode *MD) {
5646 auto IsValidAccessScope = [](const MDNode *MD) {
5647 return MD->getNumOperands() == 0 && MD->isDistinct();
5648 };
5649
5650 // It must be either an access scope itself...
5651 if (IsValidAccessScope(MD))
5652 return;
5653
5654 // ...or a list of access scopes.
5655 for (const MDOperand &Op : MD->operands()) {
5656 const MDNode *OpMD = dyn_cast<MDNode>(Op);
5657 Check(OpMD != nullptr, "Access scope list must consist of MDNodes", MD);
5658 Check(IsValidAccessScope(OpMD),
5659 "Access scope list contains invalid access scope", MD);
5660 }
5661}
5662
5663void Verifier::visitCapturesMetadata(Instruction &I, const MDNode *Captures) {
5664 static const char *ValidArgs[] = {"address_is_null", "address",
5665 "read_provenance", "provenance"};
5666
5667 auto *SI = dyn_cast<StoreInst>(&I);
5668 Check(SI, "!captures metadata can only be applied to store instructions", &I);
5669 Check(SI->getValueOperand()->getType()->isPointerTy(),
5670 "!captures metadata can only be applied to store with value operand of "
5671 "pointer type",
5672 &I);
5673 Check(Captures->getNumOperands() != 0, "!captures metadata cannot be empty",
5674 &I);
5675
5676 for (Metadata *Op : Captures->operands()) {
5677 auto *Str = dyn_cast<MDString>(Op);
5678 Check(Str, "!captures metadata must be a list of strings", &I);
5679 Check(is_contained(ValidArgs, Str->getString()),
5680 "invalid entry in !captures metadata", &I, Str);
5681 }
5682}
5683
5684void Verifier::visitAllocTokenMetadata(Instruction &I, MDNode *MD) {
5685 Check(isa<CallBase>(I), "!alloc_token should only exist on calls", &I);
5686 Check(MD->getNumOperands() == 2, "!alloc_token must have 2 operands", MD);
5687 Check(isa<MDString>(MD->getOperand(0)), "expected string", MD);
5689 "expected integer constant", MD);
5690}
5691
5692void Verifier::visitInlineHistoryMetadata(Instruction &I, MDNode *MD) {
5693 Check(isa<CallBase>(I), "!inline_history should only exist on calls", &I);
5694 for (Metadata *Op : MD->operands()) {
5695 // Can be null when a function is erased.
5696 if (!Op)
5697 continue;
5700 ->getValue()
5701 ->stripPointerCastsAndAliases()),
5702 "!inline_history operands must be functions or null", MD);
5703 }
5704}
5705
5706void Verifier::visitMemCacheHintMetadata(Instruction &I, MDNode *MD) {
5707 Check(I.mayReadOrWriteMemory(),
5708 "!mem.cache_hint is only valid on memory operations", &I);
5709
5710 Check(MD->getNumOperands() % 2 == 0,
5711 "!mem.cache_hint must have even number of operands "
5712 "(operand_no, hint_node pairs)",
5713 MD);
5714
5715 const auto *CB = dyn_cast<CallBase>(&I);
5716 if (CB)
5717 Check(CB->getIntrinsicID() != Intrinsic::not_intrinsic,
5718 "!mem.cache_hint is not supported on non-intrinsic calls", &I);
5719
5720 unsigned NumOperands = CB ? CB->arg_size() : I.getNumOperands();
5721
5722 SmallDenseSet<unsigned, 4> SeenOperandNos;
5723 std::optional<uint64_t> LastOperandNo;
5724
5725 // Top-level metadata alternates: i32 operand_no, MDNode hint_node.
5726 for (unsigned J = 0; J + 1 < MD->getNumOperands(); J += 2) {
5727 auto *OpNoCI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(J));
5728 Check(OpNoCI,
5729 "!mem.cache_hint must alternate between i32 operand numbers and "
5730 "metadata hint nodes",
5731 MD);
5732
5733 Check(OpNoCI->getValue().isNonNegative(),
5734 "!mem.cache_hint operand number must be non-negative", MD);
5735
5736 uint64_t OperandNo = OpNoCI->getZExtValue();
5737 Check(OperandNo < NumOperands,
5738 "!mem.cache_hint operand number is out of range", &I);
5739
5740 Value *Operand =
5741 CB ? CB->getArgOperand(OperandNo) : I.getOperand(OperandNo);
5742 Check(Operand->getType()->isPtrOrPtrVectorTy(),
5743 "!mem.cache_hint operand number must refer to a pointer operand", &I);
5744
5745 bool Inserted = SeenOperandNos.insert(OperandNo).second;
5746 Check(Inserted, "!mem.cache_hint contains duplicate operand number", MD);
5747
5748 Check(!Inserted || !LastOperandNo || OperandNo > *LastOperandNo,
5749 "!mem.cache_hint operand numbers must be in increasing order", MD);
5750 LastOperandNo = OperandNo;
5751
5752 const auto *Node = dyn_cast<MDNode>(MD->getOperand(J + 1));
5753 Check(Node,
5754 "!mem.cache_hint must alternate between i32 operand numbers and "
5755 "metadata hint nodes",
5756 MD);
5757
5758 Check(Node->getNumOperands() % 2 == 0,
5759 "!mem.cache_hint hint node must have even number of operands "
5760 "(key-value pairs)",
5761 Node);
5762
5763 StringSet<> SeenKeys;
5764 for (unsigned K = 0; K + 1 < Node->getNumOperands(); K += 2) {
5765 const auto *Key = dyn_cast<MDString>(Node->getOperand(K));
5766 Check(Key, "!mem.cache_hint key must be a string", Node);
5767
5768 StringRef KeyStr = Key->getString();
5769 Check(SeenKeys.insert(KeyStr).second,
5770 "!mem.cache_hint hint node contains duplicate key", Node);
5771
5772 const Metadata *Value = Node->getOperand(K + 1).get();
5775 "!mem.cache_hint value must be a string or integer", Node);
5776 }
5777 }
5778}
5779
5780/// verifyInstruction - Verify that an instruction is well formed.
5781///
5782void Verifier::visitInstruction(Instruction &I) {
5783 BasicBlock *BB = I.getParent();
5784 Check(BB, "Instruction not embedded in basic block!", &I);
5785
5786 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
5787 for (User *U : I.users()) {
5788 Check(U != (User *)&I || !DT.isReachableFromEntry(BB),
5789 "Only PHI nodes may reference their own value!", &I);
5790 }
5791 }
5792
5793 // Check that void typed values don't have names
5794 Check(!I.getType()->isVoidTy() || !I.hasName(),
5795 "Instruction has a name, but provides a void value!", &I);
5796
5797 // Check that the return value of the instruction is either void or a legal
5798 // value type.
5799 Check(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
5800 "Instruction returns a non-scalar type!", &I);
5801
5802 // Check that the instruction doesn't produce metadata. Calls are already
5803 // checked against the callee type.
5804 Check(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
5805 "Invalid use of metadata!", &I);
5806
5807 // Check that all uses of the instruction, if they are instructions
5808 // themselves, actually have parent basic blocks. If the use is not an
5809 // instruction, it is an error!
5810 for (Use &U : I.uses()) {
5811 if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
5812 Check(Used->getParent() != nullptr,
5813 "Instruction referencing"
5814 " instruction not embedded in a basic block!",
5815 &I, Used);
5816 else {
5817 CheckFailed("Use of instruction is not an instruction!", U);
5818 return;
5819 }
5820 }
5821
5822 // Get a pointer to the call base of the instruction if it is some form of
5823 // call.
5824 const CallBase *CBI = dyn_cast<CallBase>(&I);
5825
5826 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
5827 Check(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
5828
5829 // Check to make sure that only first-class-values are operands to
5830 // instructions.
5831 if (!I.getOperand(i)->getType()->isFirstClassType()) {
5832 Check(false, "Instruction operands must be first-class values!", &I);
5833 }
5834
5835 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
5836 // This code checks whether the function is used as the operand of a
5837 // clang_arc_attachedcall operand bundle.
5838 auto IsAttachedCallOperand = [](Function *F, const CallBase *CBI,
5839 int Idx) {
5840 return CBI && CBI->isOperandBundleOfType(
5842 };
5843
5844 // Check to make sure that the "address of" an intrinsic function is never
5845 // taken. Ignore cases where the address of the intrinsic function is used
5846 // as the argument of operand bundle "clang.arc.attachedcall" as those
5847 // cases are handled in verifyAttachedCallBundle.
5848 Check((!F->isIntrinsic() ||
5849 (CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i)) ||
5850 IsAttachedCallOperand(F, CBI, i)),
5851 "Cannot take the address of an intrinsic!", &I);
5852 Check(!F->isIntrinsic() || isa<CallInst>(I) || isa<CallBrInst>(I) ||
5853 F->getIntrinsicID() == Intrinsic::donothing ||
5854 F->getIntrinsicID() == Intrinsic::seh_try_begin ||
5855 F->getIntrinsicID() == Intrinsic::seh_try_end ||
5856 F->getIntrinsicID() == Intrinsic::seh_scope_begin ||
5857 F->getIntrinsicID() == Intrinsic::seh_scope_end ||
5858 F->getIntrinsicID() == Intrinsic::coro_resume ||
5859 F->getIntrinsicID() == Intrinsic::coro_destroy ||
5860 F->getIntrinsicID() == Intrinsic::coro_await_suspend_void ||
5861 F->getIntrinsicID() == Intrinsic::coro_await_suspend_bool ||
5862 F->getIntrinsicID() == Intrinsic::coro_await_suspend_handle ||
5863 F->getIntrinsicID() ==
5864 Intrinsic::experimental_patchpoint_void ||
5865 F->getIntrinsicID() == Intrinsic::experimental_patchpoint ||
5866 F->getIntrinsicID() == Intrinsic::fake_use ||
5867 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint ||
5868 F->getIntrinsicID() == Intrinsic::wasm_throw ||
5869 F->getIntrinsicID() == Intrinsic::wasm_rethrow ||
5870 IsAttachedCallOperand(F, CBI, i),
5871 "Cannot invoke an intrinsic other than donothing, patchpoint, "
5872 "statepoint, coro_resume, coro_destroy, clang.arc.attachedcall or "
5873 "wasm.(re)throw",
5874 &I);
5875 Check(F->getParent() == &M, "Referencing function in another module!", &I,
5876 &M, F, F->getParent());
5877 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
5878 Check(OpBB->getParent() == BB->getParent(),
5879 "Referring to a basic block in another function!", &I);
5880 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
5881 Check(OpArg->getParent() == BB->getParent(),
5882 "Referring to an argument in another function!", &I);
5883 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
5884 Check(GV->getParent() == &M, "Referencing global in another module!", &I,
5885 &M, GV, GV->getParent());
5886 } else if (Instruction *OpInst = dyn_cast<Instruction>(I.getOperand(i))) {
5887 Check(OpInst->getFunction() == BB->getParent(),
5888 "Referring to an instruction in another function!", &I);
5889 verifyDominatesUse(I, i);
5890 } else if (isa<InlineAsm>(I.getOperand(i))) {
5891 Check(CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i),
5892 "Cannot take the address of an inline asm!", &I);
5893 } else if (auto *C = dyn_cast<Constant>(I.getOperand(i))) {
5894 visitConstantExprsRecursively(C);
5895 }
5896 }
5897
5898 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
5900 "fpmath requires a floating point result!", &I);
5901 Check(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
5902 if (ConstantFP *CFP0 =
5904 const APFloat &Accuracy = CFP0->getValueAPF();
5905 Check(&Accuracy.getSemantics() == &APFloat::IEEEsingle(),
5906 "fpmath accuracy must have float type", &I);
5907 Check(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
5908 "fpmath accuracy not a positive number!", &I);
5909 } else {
5910 Check(false, "invalid fpmath accuracy!", &I);
5911 }
5912 }
5913
5914 if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
5916 "Ranges are only for loads, calls and invokes!", &I);
5917 visitRangeMetadata(I, Range, I.getType());
5918 }
5919
5920 if (MDNode *MD = I.getMetadata(LLVMContext::MD_nofpclass)) {
5921 Check(isa<LoadInst>(I), "nofpclass is only for loads", &I);
5922 visitNoFPClassMetadata(I, MD, I.getType());
5923 }
5924
5925 if (MDNode *Range = I.getMetadata(LLVMContext::MD_noalias_addrspace)) {
5928 "noalias.addrspace are only for memory operations!", &I);
5929 visitNoaliasAddrspaceMetadata(I, Range, I.getType());
5930 }
5931
5932 if (I.hasMetadata(LLVMContext::MD_invariant_group)) {
5934 "invariant.group metadata is only for loads and stores", &I);
5935 }
5936
5937 if (MDNode *MD = I.getMetadata(LLVMContext::MD_nonnull)) {
5938 Check(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
5939 &I);
5941 "nonnull applies only to load instructions, use attributes"
5942 " for calls or invokes",
5943 &I);
5944 Check(MD->getNumOperands() == 0, "nonnull metadata must be empty", &I);
5945 }
5946
5947 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable))
5948 visitDereferenceableMetadata(I, MD);
5949
5950 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
5951 visitDereferenceableMetadata(I, MD);
5952
5953 if (MDNode *MD = I.getMetadata(LLVMContext::MD_nofree))
5954 visitNofreeMetadata(I, MD);
5955
5956 if (MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa))
5957 TBAAVerifyHelper.visitTBAAMetadata(&I, TBAA);
5958
5959 if (MDNode *MD = I.getMetadata(LLVMContext::MD_noalias))
5960 visitAliasScopeListMetadata(MD);
5961 if (MDNode *MD = I.getMetadata(LLVMContext::MD_alias_scope))
5962 visitAliasScopeListMetadata(MD);
5963
5964 if (MDNode *MD = I.getMetadata(LLVMContext::MD_access_group))
5965 visitAccessGroupMetadata(MD);
5966
5967 if (MDNode *AlignMD = I.getMetadata(LLVMContext::MD_align)) {
5968 Check(I.getType()->isPointerTy(), "align applies only to pointer types",
5969 &I);
5971 "align applies only to load instructions, "
5972 "use attributes for calls or invokes",
5973 &I);
5974 Check(AlignMD->getNumOperands() == 1, "align takes one operand!", &I);
5975 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0));
5976 Check(CI && CI->getType()->isIntegerTy(64),
5977 "align metadata value must be an i64!", &I);
5978 uint64_t Align = CI->getZExtValue();
5979 Check(isPowerOf2_64(Align), "align metadata value must be a power of 2!",
5980 &I);
5981 Check(Align <= Value::MaximumAlignment,
5982 "alignment is larger that implementation defined limit", &I);
5983 }
5984
5985 if (MDNode *MD = I.getMetadata(LLVMContext::MD_prof))
5986 visitProfMetadata(I, MD);
5987
5988 if (MDNode *MD = I.getMetadata(LLVMContext::MD_memprof))
5989 visitMemProfMetadata(I, MD);
5990
5991 if (MDNode *MD = I.getMetadata(LLVMContext::MD_callsite))
5992 visitCallsiteMetadata(I, MD);
5993
5994 if (MDNode *MD = I.getMetadata(LLVMContext::MD_callee_type))
5995 visitCalleeTypeMetadata(I, MD);
5996
5997 if (MDNode *MD = I.getMetadata(LLVMContext::MD_DIAssignID))
5998 visitDIAssignIDMetadata(I, MD);
5999
6000 if (MDNode *MMRA = I.getMetadata(LLVMContext::MD_mmra))
6001 visitMMRAMetadata(I, MMRA);
6002
6003 if (MDNode *Annotation = I.getMetadata(LLVMContext::MD_annotation))
6004 visitAnnotationMetadata(Annotation);
6005
6006 if (MDNode *Captures = I.getMetadata(LLVMContext::MD_captures))
6007 visitCapturesMetadata(I, Captures);
6008
6009 if (MDNode *MD = I.getMetadata(LLVMContext::MD_alloc_token))
6010 visitAllocTokenMetadata(I, MD);
6011
6012 if (MDNode *MD = I.getMetadata(LLVMContext::MD_inline_history))
6013 visitInlineHistoryMetadata(I, MD);
6014
6015 if (MDNode *MD = I.getMetadata(LLVMContext::MD_mem_cache_hint))
6016 visitMemCacheHintMetadata(I, MD);
6017
6018 if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
6019 CheckDI(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N);
6020 visitMDNode(*N, AreDebugLocsAllowed::Yes);
6021
6022 if (auto *DL = dyn_cast<DILocation>(N)) {
6023 if (DL->getAtomGroup()) {
6024 CheckDI(DL->getScope()->getSubprogram()->getKeyInstructionsEnabled(),
6025 "DbgLoc uses atomGroup but DISubprogram doesn't have Key "
6026 "Instructions enabled",
6027 DL, DL->getScope()->getSubprogram());
6028 }
6029 }
6030 }
6031
6033 I.getAllMetadata(MDs);
6034 for (auto Attachment : MDs) {
6035 unsigned Kind = Attachment.first;
6036 auto AllowLocs =
6037 (Kind == LLVMContext::MD_dbg || Kind == LLVMContext::MD_loop)
6038 ? AreDebugLocsAllowed::Yes
6039 : AreDebugLocsAllowed::No;
6040 visitMDNode(*Attachment.second, AllowLocs);
6041 }
6042
6043 InstsInThisBlock.insert(&I);
6044}
6045
6046/// Allow intrinsics to be verified in different ways.
6047void Verifier::visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call) {
6049 Check(IF->isDeclaration(), "Intrinsic functions should never be defined!",
6050 IF);
6051
6052 // Verify that the intrinsic prototype lines up with what the .td files
6053 // describe.
6054 FunctionType *IFTy = IF->getFunctionType();
6055
6056 // Walk the descriptors to extract overloaded types.
6057 std::string ErrMsg;
6058 raw_string_ostream ErrOS(ErrMsg);
6059 SmallVector<Type *, 4> OverloadTys;
6060 bool IsValid = Intrinsic::isSignatureValid(ID, IFTy, OverloadTys, ErrOS);
6061 Check(IsValid, ErrMsg, IF);
6062
6063 // Now that we have the intrinsic ID and the actual argument types (and we
6064 // know they are legal for the intrinsic!) get the intrinsic name through the
6065 // usual means. This allows us to verify the mangling of argument types into
6066 // the name.
6067 const std::string ExpectedName =
6068 Intrinsic::getName(ID, OverloadTys, IF->getParent(), IFTy);
6069 Check(ExpectedName == IF->getName(),
6070 "Intrinsic name not mangled correctly for type arguments! "
6071 "Should be: " +
6072 ExpectedName,
6073 IF);
6074
6075 // If the intrinsic takes MDNode arguments, verify that they are either global
6076 // or are local to *this* function.
6077 for (Value *V : Call.args()) {
6078 if (auto *MD = dyn_cast<MetadataAsValue>(V))
6079 visitMetadataAsValue(*MD, Call.getCaller());
6080 if (auto *Const = dyn_cast<Constant>(V))
6081 Check(!Const->getType()->isX86_AMXTy(),
6082 "const x86_amx is not allowed in argument!");
6083 }
6084
6085 switch (ID) {
6086 default:
6087 break;
6088 case Intrinsic::assume: {
6089 if (Call.hasOperandBundles()) {
6091 Check(Cond && Cond->isOne(),
6092 "assume with operand bundles must have i1 true condition", Call);
6093 }
6094 for (auto OBU : Call.operand_bundles()) {
6095 // Separate storage assumptions are special insofar as they're the only
6096 // operand bundles allowed on assumes that aren't parameter attributes.
6097
6098 auto GetTypeAt = [&](unsigned Index) {
6099 return OBU.Inputs[Index]->getType();
6100 };
6101
6102 switch (getBundleAttrFromOBU(OBU)) {
6103 case BundleAttr::None:
6104 CheckFailed("tags must be valid attribute names", Call);
6105 break;
6106 case BundleAttr::Align:
6107 Check(OBU.Inputs.size() >= 2 && OBU.Inputs.size() <= 3,
6108 "alignment assumptions should have 2 or 3 arguments", Call);
6109 Check(GetTypeAt(0)->isPointerTy(), "first argument should be a pointer",
6110 Call);
6111 Check(GetTypeAt(1)->isIntegerTy() &&
6112 GetTypeAt(1)->getIntegerBitWidth() <= 64,
6113 "second argument should be an integer with a maximum width of 64 "
6114 "bits",
6115 Call);
6116 Check(OBU.Inputs.size() < 3 ||
6117 GetTypeAt(2)->isIntegerTy() &&
6118 GetTypeAt(2)->getIntegerBitWidth() <= 64,
6119 "third argument should be an integer with a maximum width of 64 "
6120 "bits if present",
6121 Call);
6122 break;
6123 case BundleAttr::Cold:
6124 Check(OBU.Inputs.size() == 0,
6125 "cold assumptions should have no arguments", Call);
6126 break;
6127 case BundleAttr::Dereferenceable:
6128 case BundleAttr::DereferenceableOrNull:
6129 Check(OBU.Inputs.size() == 2,
6130 "dereferenceable assumptions should have 2 arguments", Call);
6131 Check(GetTypeAt(0)->isPointerTy(), "first argument should be a pointer",
6132 Call);
6133 Check(GetTypeAt(1)->isIntegerTy() &&
6134 GetTypeAt(1)->getIntegerBitWidth() <= 64,
6135 "second argument should be an integer with a maximum width of 64 "
6136 "bits",
6137 Call);
6138 break;
6139 case BundleAttr::Ignore:
6140 break;
6141 case BundleAttr::NonNull:
6142 Check(OBU.Inputs.size() == 1,
6143 "nonnull assumptions should have 1 argument", Call);
6144 Check(GetTypeAt(0)->isPointerTy(), "first argument should be a pointer",
6145 Call);
6146 break;
6147 case BundleAttr::NoUndef:
6148 Check(OBU.Inputs.size() == 1,
6149 "noundef assumptions should have 1 argument", Call);
6150 break;
6151 case BundleAttr::SeparateStorage:
6152 Check(OBU.Inputs.size() == 2,
6153 "separate_storage assumptions should have 2 arguments", Call);
6154 Check(GetTypeAt(0)->isPointerTy() && GetTypeAt(1)->isPointerTy(),
6155 "arguments to separate_storage assumptions should be pointers",
6156 Call);
6157 break;
6158 }
6159 }
6160 break;
6161 }
6162 case Intrinsic::ucmp:
6163 case Intrinsic::scmp: {
6164 Type *SrcTy = Call.getOperand(0)->getType();
6165 Type *DestTy = Call.getType();
6166
6167 Check(DestTy->getScalarSizeInBits() >= 2,
6168 "result type must be at least 2 bits wide", Call);
6169
6170 bool IsDestTypeVector = DestTy->isVectorTy();
6171 Check(SrcTy->isVectorTy() == IsDestTypeVector,
6172 "ucmp/scmp argument and result types must both be either vector or "
6173 "scalar types",
6174 Call);
6175 if (IsDestTypeVector) {
6176 auto SrcVecLen = cast<VectorType>(SrcTy)->getElementCount();
6177 auto DestVecLen = cast<VectorType>(DestTy)->getElementCount();
6178 Check(SrcVecLen == DestVecLen,
6179 "return type and arguments must have the same number of "
6180 "elements",
6181 Call);
6182 }
6183 break;
6184 }
6185 case Intrinsic::coro_begin:
6186 case Intrinsic::coro_begin_custom_abi:
6188 "id argument of llvm.coro.begin must refer to coro.id");
6189 break;
6190 case Intrinsic::coro_id: {
6192 "align argument only accepts constants");
6193 auto *Promise = Call.getArgOperand(1);
6194 Check(isa<ConstantPointerNull>(Promise) || isa<AllocaInst>(Promise),
6195 "promise argument must refer to an alloca");
6196
6197 auto *CoroAddr = Call.getArgOperand(2)->stripPointerCasts();
6198 bool BeforeCoroEarly = isa<ConstantPointerNull>(CoroAddr);
6199 Check(BeforeCoroEarly || isa<Function>(CoroAddr),
6200 "coro argument must refer to a function");
6201
6202 auto *InfoArg = Call.getArgOperand(3);
6203 bool BeforeCoroSplit = isa<ConstantPointerNull>(InfoArg);
6204 if (BeforeCoroSplit)
6205 break;
6206
6207 Check(!BeforeCoroEarly, "cannot run CoroSplit before CoroEarly");
6208 auto *GV = dyn_cast<GlobalVariable>(InfoArg);
6209 Check(GV && GV->isConstant() && GV->hasDefinitiveInitializer(),
6210 "info argument of llvm.coro.id must refer to an initialized "
6211 "constant");
6212 Constant *Init = GV->getInitializer();
6214 "info argument of llvm.coro.id must refer to either a struct or "
6215 "an array");
6216 break;
6217 }
6218 case Intrinsic::is_fpclass: {
6219 const ConstantInt *TestMask = cast<ConstantInt>(Call.getOperand(1));
6220 Check((TestMask->getZExtValue() & ~static_cast<unsigned>(fcAllFlags)) == 0,
6221 "unsupported bits for llvm.is.fpclass test mask");
6222 break;
6223 }
6224 case Intrinsic::fptrunc_round: {
6225 // Check the rounding mode
6226 Metadata *MD = nullptr;
6228 if (MAV)
6229 MD = MAV->getMetadata();
6230
6231 Check(MD != nullptr, "missing rounding mode argument", Call);
6232
6233 Check(isa<MDString>(MD),
6234 ("invalid value for llvm.fptrunc.round metadata operand"
6235 " (the operand should be a string)"),
6236 MD);
6237
6238 std::optional<RoundingMode> RoundMode =
6239 convertStrToRoundingMode(cast<MDString>(MD)->getString());
6240 Check(RoundMode && *RoundMode != RoundingMode::Dynamic,
6241 "unsupported rounding mode argument", Call);
6242 break;
6243 }
6244 case Intrinsic::convert_to_arbitrary_fp: {
6245 // Check that vector element counts are consistent.
6246 Type *ValueTy = Call.getArgOperand(0)->getType();
6247 Type *IntTy = Call.getType();
6248
6249 if (auto *ValueVecTy = dyn_cast<VectorType>(ValueTy)) {
6250 auto *IntVecTy = dyn_cast<VectorType>(IntTy);
6251 Check(IntVecTy,
6252 "if floating-point operand is a vector, integer operand must also "
6253 "be a vector",
6254 Call);
6255 Check(ValueVecTy->getElementCount() == IntVecTy->getElementCount(),
6256 "floating-point and integer vector operands must have the same "
6257 "element count",
6258 Call);
6259 }
6260
6261 // Check interpretation metadata (argoperand 1).
6262 auto *InterpMAV = dyn_cast<MetadataAsValue>(Call.getArgOperand(1));
6263 Check(InterpMAV, "missing interpretation metadata operand", Call);
6264 auto *InterpStr = dyn_cast<MDString>(InterpMAV->getMetadata());
6265 Check(InterpStr, "interpretation metadata operand must be a string", Call);
6266 StringRef Interp = InterpStr->getString();
6267
6268 Check(!Interp.empty(), "interpretation metadata string must not be empty",
6269 Call);
6270
6271 // Valid interpretation strings: mini-float format names.
6273 "unsupported interpretation metadata string", Call);
6274
6275 // Check rounding mode metadata (argoperand 2).
6276 auto *RoundingMAV = dyn_cast<MetadataAsValue>(Call.getArgOperand(2));
6277 Check(RoundingMAV, "missing rounding mode metadata operand", Call);
6278 auto *RoundingStr = dyn_cast<MDString>(RoundingMAV->getMetadata());
6279 Check(RoundingStr, "rounding mode metadata operand must be a string", Call);
6280
6281 std::optional<RoundingMode> RM =
6282 convertStrToRoundingMode(RoundingStr->getString());
6283 Check(RM && *RM != RoundingMode::Dynamic,
6284 "unsupported rounding mode argument", Call);
6285 break;
6286 }
6287 case Intrinsic::convert_from_arbitrary_fp: {
6288 // Check that vector element counts are consistent.
6289 Type *IntTy = Call.getArgOperand(0)->getType();
6290 Type *ValueTy = Call.getType();
6291
6292 if (auto *ValueVecTy = dyn_cast<VectorType>(ValueTy)) {
6293 auto *IntVecTy = dyn_cast<VectorType>(IntTy);
6294 Check(IntVecTy,
6295 "if floating-point operand is a vector, integer operand must also "
6296 "be a vector",
6297 Call);
6298 Check(ValueVecTy->getElementCount() == IntVecTy->getElementCount(),
6299 "floating-point and integer vector operands must have the same "
6300 "element count",
6301 Call);
6302 }
6303
6304 // Check interpretation metadata (argoperand 1).
6305 auto *InterpMAV = dyn_cast<MetadataAsValue>(Call.getArgOperand(1));
6306 Check(InterpMAV, "missing interpretation metadata operand", Call);
6307 auto *InterpStr = dyn_cast<MDString>(InterpMAV->getMetadata());
6308 Check(InterpStr, "interpretation metadata operand must be a string", Call);
6309 StringRef Interp = InterpStr->getString();
6310
6311 Check(!Interp.empty(), "interpretation metadata string must not be empty",
6312 Call);
6313
6314 // Valid interpretation strings: mini-float format names.
6316 "unsupported interpretation metadata string", Call);
6317 break;
6318 }
6319#define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6320#include "llvm/IR/VPIntrinsics.def"
6321#undef BEGIN_REGISTER_VP_INTRINSIC
6322 visitVPIntrinsic(cast<VPIntrinsic>(Call));
6323 break;
6324#define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC) \
6325 case Intrinsic::INTRINSIC:
6326#include "llvm/IR/ConstrainedOps.def"
6327#undef INSTRUCTION
6328 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(Call));
6329 break;
6330 case Intrinsic::dbg_declare: // llvm.dbg.declare
6331 case Intrinsic::dbg_value: // llvm.dbg.value
6332 case Intrinsic::dbg_assign: // llvm.dbg.assign
6333 case Intrinsic::dbg_label: // llvm.dbg.label
6334 // We no longer interpret debug intrinsics (the old variable-location
6335 // design). They're meaningless as far as LLVM is concerned we could make
6336 // it an error for them to appear, but it's possible we'll have users
6337 // converting back to intrinsics for the forseeable future (such as DXIL),
6338 // so tolerate their existance.
6339 break;
6340 case Intrinsic::memcpy:
6341 case Intrinsic::memcpy_inline:
6342 case Intrinsic::memmove:
6343 case Intrinsic::memset:
6344 case Intrinsic::memset_inline:
6345 break;
6346 case Intrinsic::experimental_memset_pattern: {
6347 const auto Memset = cast<MemSetPatternInst>(&Call);
6348 Check(Memset->getValue()->getType()->isSized(),
6349 "unsized types cannot be used as memset patterns", Call);
6350 break;
6351 }
6352 case Intrinsic::memcpy_element_unordered_atomic:
6353 case Intrinsic::memmove_element_unordered_atomic:
6354 case Intrinsic::memset_element_unordered_atomic: {
6355 const auto *AMI = cast<AnyMemIntrinsic>(&Call);
6356
6357 ConstantInt *ElementSizeCI =
6358 cast<ConstantInt>(AMI->getRawElementSizeInBytes());
6359 const APInt &ElementSizeVal = ElementSizeCI->getValue();
6360 Check(ElementSizeVal.isPowerOf2(),
6361 "element size of the element-wise atomic memory intrinsic "
6362 "must be a power of 2",
6363 Call);
6364
6365 auto IsValidAlignment = [&](MaybeAlign Alignment) {
6366 return Alignment && ElementSizeVal.ule(Alignment->value());
6367 };
6368 Check(IsValidAlignment(AMI->getDestAlign()),
6369 "incorrect alignment of the destination argument", Call);
6370 if (const auto *AMT = dyn_cast<AnyMemTransferInst>(AMI)) {
6371 Check(IsValidAlignment(AMT->getSourceAlign()),
6372 "incorrect alignment of the source argument", Call);
6373 }
6374 break;
6375 }
6376 case Intrinsic::call_preallocated_setup: {
6377 auto *NumArgs = cast<ConstantInt>(Call.getArgOperand(0));
6378 bool FoundCall = false;
6379 for (User *U : Call.users()) {
6380 auto *UseCall = dyn_cast<CallBase>(U);
6381 Check(UseCall != nullptr,
6382 "Uses of llvm.call.preallocated.setup must be calls");
6383 Intrinsic::ID IID = UseCall->getIntrinsicID();
6384 if (IID == Intrinsic::call_preallocated_arg) {
6385 auto *AllocArgIndex = dyn_cast<ConstantInt>(UseCall->getArgOperand(1));
6386 Check(AllocArgIndex != nullptr,
6387 "llvm.call.preallocated.alloc arg index must be a constant");
6388 auto AllocArgIndexInt = AllocArgIndex->getValue();
6389 Check(AllocArgIndexInt.sge(0) &&
6390 AllocArgIndexInt.slt(NumArgs->getValue()),
6391 "llvm.call.preallocated.alloc arg index must be between 0 and "
6392 "corresponding "
6393 "llvm.call.preallocated.setup's argument count");
6394 } else if (IID == Intrinsic::call_preallocated_teardown) {
6395 // nothing to do
6396 } else {
6397 Check(!FoundCall, "Can have at most one call corresponding to a "
6398 "llvm.call.preallocated.setup");
6399 FoundCall = true;
6400 size_t NumPreallocatedArgs = 0;
6401 for (unsigned i = 0; i < UseCall->arg_size(); i++) {
6402 if (UseCall->paramHasAttr(i, Attribute::Preallocated)) {
6403 ++NumPreallocatedArgs;
6404 }
6405 }
6406 Check(NumPreallocatedArgs != 0,
6407 "cannot use preallocated intrinsics on a call without "
6408 "preallocated arguments");
6409 Check(NumArgs->equalsInt(NumPreallocatedArgs),
6410 "llvm.call.preallocated.setup arg size must be equal to number "
6411 "of preallocated arguments "
6412 "at call site",
6413 Call, *UseCall);
6414 // getOperandBundle() cannot be called if more than one of the operand
6415 // bundle exists. There is already a check elsewhere for this, so skip
6416 // here if we see more than one.
6417 if (UseCall->countOperandBundlesOfType(LLVMContext::OB_preallocated) >
6418 1) {
6419 return;
6420 }
6421 auto PreallocatedBundle =
6422 UseCall->getOperandBundle(LLVMContext::OB_preallocated);
6423 Check(PreallocatedBundle,
6424 "Use of llvm.call.preallocated.setup outside intrinsics "
6425 "must be in \"preallocated\" operand bundle");
6426 Check(PreallocatedBundle->Inputs.front().get() == &Call,
6427 "preallocated bundle must have token from corresponding "
6428 "llvm.call.preallocated.setup");
6429 }
6430 }
6431 break;
6432 }
6433 case Intrinsic::call_preallocated_arg: {
6434 auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0));
6435 Check(Token &&
6436 Token->getIntrinsicID() == Intrinsic::call_preallocated_setup,
6437 "llvm.call.preallocated.arg token argument must be a "
6438 "llvm.call.preallocated.setup");
6439 Check(Call.hasFnAttr(Attribute::Preallocated),
6440 "llvm.call.preallocated.arg must be called with a \"preallocated\" "
6441 "call site attribute");
6442 break;
6443 }
6444 case Intrinsic::call_preallocated_teardown: {
6445 auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0));
6446 Check(Token &&
6447 Token->getIntrinsicID() == Intrinsic::call_preallocated_setup,
6448 "llvm.call.preallocated.teardown token argument must be a "
6449 "llvm.call.preallocated.setup");
6450 break;
6451 }
6452 case Intrinsic::gcroot:
6453 case Intrinsic::gcwrite:
6454 case Intrinsic::gcread:
6455 if (ID == Intrinsic::gcroot) {
6456 AllocaInst *AI =
6458 Check(AI, "llvm.gcroot parameter #1 must be an alloca.", Call);
6460 "llvm.gcroot parameter #2 must be a constant.", Call);
6461 if (!AI->getAllocatedType()->isPointerTy()) {
6463 "llvm.gcroot parameter #1 must either be a pointer alloca, "
6464 "or argument #2 must be a non-null constant.",
6465 Call);
6466 }
6467 }
6468
6469 Check(Call.getParent()->getParent()->hasGC(),
6470 "Enclosing function does not use GC.", Call);
6471 break;
6472 case Intrinsic::init_trampoline:
6474 "llvm.init_trampoline parameter #2 must resolve to a function.",
6475 Call);
6476 break;
6477 case Intrinsic::prefetch:
6478 Check(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2,
6479 "rw argument to llvm.prefetch must be 0-1", Call);
6480 Check(cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 4,
6481 "locality argument to llvm.prefetch must be 0-3", Call);
6482 Check(cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue() < 2,
6483 "cache type argument to llvm.prefetch must be 0-1", Call);
6484 break;
6485 case Intrinsic::reloc_none: {
6487 cast<MetadataAsValue>(Call.getArgOperand(0))->getMetadata()),
6488 "llvm.reloc.none argument must be a metadata string", &Call);
6489 break;
6490 }
6491 case Intrinsic::stackprotector:
6493 "llvm.stackprotector parameter #2 must resolve to an alloca.", Call);
6494 break;
6495 case Intrinsic::localescape: {
6496 BasicBlock *BB = Call.getParent();
6497 Check(BB->isEntryBlock(), "llvm.localescape used outside of entry block",
6498 Call);
6499 Check(!SawFrameEscape, "multiple calls to llvm.localescape in one function",
6500 Call);
6501 for (Value *Arg : Call.args()) {
6502 if (isa<ConstantPointerNull>(Arg))
6503 continue; // Null values are allowed as placeholders.
6504 auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
6505 Check(AI && AI->isStaticAlloca(),
6506 "llvm.localescape only accepts static allocas", Call);
6507 }
6508 FrameEscapeInfo[BB->getParent()].first = Call.arg_size();
6509 SawFrameEscape = true;
6510 break;
6511 }
6512 case Intrinsic::localrecover: {
6514 Function *Fn = dyn_cast<Function>(FnArg);
6515 Check(Fn && !Fn->isDeclaration(),
6516 "llvm.localrecover first "
6517 "argument must be function defined in this module",
6518 Call);
6519 auto *IdxArg = cast<ConstantInt>(Call.getArgOperand(2));
6520 auto &Entry = FrameEscapeInfo[Fn];
6521 Entry.second = unsigned(
6522 std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
6523 break;
6524 }
6525
6526 case Intrinsic::experimental_gc_statepoint:
6527 if (auto *CI = dyn_cast<CallInst>(&Call))
6528 Check(!CI->isInlineAsm(),
6529 "gc.statepoint support for inline assembly unimplemented", CI);
6530 Check(Call.getParent()->getParent()->hasGC(),
6531 "Enclosing function does not use GC.", Call);
6532
6533 verifyStatepoint(Call);
6534 break;
6535 case Intrinsic::experimental_gc_result: {
6536 Check(Call.getParent()->getParent()->hasGC(),
6537 "Enclosing function does not use GC.", Call);
6538
6539 auto *Statepoint = Call.getArgOperand(0);
6540 if (isa<UndefValue>(Statepoint))
6541 break;
6542
6543 // Are we tied to a statepoint properly?
6544 const auto *StatepointCall = dyn_cast<CallBase>(Statepoint);
6545 Check(StatepointCall && StatepointCall->getIntrinsicID() ==
6546 Intrinsic::experimental_gc_statepoint,
6547 "gc.result operand #1 must be from a statepoint", Call,
6548 Call.getArgOperand(0));
6549
6550 // Check that result type matches wrapped callee.
6551 auto *TargetFuncType =
6552 cast<FunctionType>(StatepointCall->getParamElementType(2));
6553 Check(Call.getType() == TargetFuncType->getReturnType(),
6554 "gc.result result type does not match wrapped callee", Call);
6555 break;
6556 }
6557 case Intrinsic::experimental_gc_relocate: {
6558 Check(Call.arg_size() == 3, "wrong number of arguments", Call);
6559
6561 "gc.relocate must return a pointer or a vector of pointers", Call);
6562
6563 // Check that this relocate is correctly tied to the statepoint
6564
6565 // This is case for relocate on the unwinding path of an invoke statepoint
6566 if (LandingPadInst *LandingPad =
6568
6569 const BasicBlock *InvokeBB =
6570 LandingPad->getParent()->getUniquePredecessor();
6571
6572 // Landingpad relocates should have only one predecessor with invoke
6573 // statepoint terminator
6574 Check(InvokeBB, "safepoints should have unique landingpads",
6575 LandingPad->getParent());
6576 Check(InvokeBB->getTerminator(), "safepoint block should be well formed",
6577 InvokeBB);
6579 "gc relocate should be linked to a statepoint", InvokeBB);
6580 } else {
6581 // In all other cases relocate should be tied to the statepoint directly.
6582 // This covers relocates on a normal return path of invoke statepoint and
6583 // relocates of a call statepoint.
6584 auto *Token = Call.getArgOperand(0);
6586 "gc relocate is incorrectly tied to the statepoint", Call, Token);
6587 }
6588
6589 // Verify rest of the relocate arguments.
6590 const Value &StatepointCall = *cast<GCRelocateInst>(Call).getStatepoint();
6591
6592 // Both the base and derived must be piped through the safepoint.
6595 "gc.relocate operand #2 must be integer offset", Call);
6596
6597 Value *Derived = Call.getArgOperand(2);
6598 Check(isa<ConstantInt>(Derived),
6599 "gc.relocate operand #3 must be integer offset", Call);
6600
6601 const uint64_t BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
6602 const uint64_t DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
6603
6604 // Check the bounds
6605 if (isa<UndefValue>(StatepointCall))
6606 break;
6607 if (auto Opt = cast<GCStatepointInst>(StatepointCall)
6608 .getOperandBundle(LLVMContext::OB_gc_live)) {
6609 Check(BaseIndex < Opt->Inputs.size(),
6610 "gc.relocate: statepoint base index out of bounds", Call);
6611 Check(DerivedIndex < Opt->Inputs.size(),
6612 "gc.relocate: statepoint derived index out of bounds", Call);
6613 }
6614
6615 // Relocated value must be either a pointer type or vector-of-pointer type,
6616 // but gc_relocate does not need to return the same pointer type as the
6617 // relocated pointer. It can be casted to the correct type later if it's
6618 // desired. However, they must have the same address space and 'vectorness'
6619 GCRelocateInst &Relocate = cast<GCRelocateInst>(Call);
6620 auto *ResultType = Call.getType();
6621 auto *DerivedType = Relocate.getDerivedPtr()->getType();
6622 auto *BaseType = Relocate.getBasePtr()->getType();
6623
6624 Check(BaseType->isPtrOrPtrVectorTy(),
6625 "gc.relocate: relocated value must be a pointer", Call);
6626 Check(DerivedType->isPtrOrPtrVectorTy(),
6627 "gc.relocate: relocated value must be a pointer", Call);
6628
6629 Check(ResultType->isVectorTy() == DerivedType->isVectorTy(),
6630 "gc.relocate: vector relocates to vector and pointer to pointer",
6631 Call);
6632 Check(
6633 ResultType->getPointerAddressSpace() ==
6634 DerivedType->getPointerAddressSpace(),
6635 "gc.relocate: relocating a pointer shouldn't change its address space",
6636 Call);
6637
6638 auto GC = llvm::getGCStrategy(Relocate.getFunction()->getGC());
6639 Check(GC, "gc.relocate: calling function must have GCStrategy",
6640 Call.getFunction());
6641 if (GC) {
6642 auto isGCPtr = [&GC](Type *PTy) {
6643 return GC->isGCManagedPointer(PTy->getScalarType()).value_or(true);
6644 };
6645 Check(isGCPtr(ResultType), "gc.relocate: must return gc pointer", Call);
6646 Check(isGCPtr(BaseType),
6647 "gc.relocate: relocated value must be a gc pointer", Call);
6648 Check(isGCPtr(DerivedType),
6649 "gc.relocate: relocated value must be a gc pointer", Call);
6650 }
6651 break;
6652 }
6653 case Intrinsic::experimental_patchpoint: {
6654 if (Call.getCallingConv() == CallingConv::AnyReg) {
6656 "patchpoint: invalid return type used with anyregcc", Call);
6657 }
6658 break;
6659 }
6660 case Intrinsic::eh_exceptioncode:
6661 case Intrinsic::eh_exceptionpointer: {
6663 "eh.exceptionpointer argument must be a catchpad", Call);
6664 break;
6665 }
6666 case Intrinsic::get_active_lane_mask: {
6668 "get_active_lane_mask: must return a "
6669 "vector",
6670 Call);
6671 auto *ElemTy = Call.getType()->getScalarType();
6672 Check(ElemTy->isIntegerTy(1),
6673 "get_active_lane_mask: element type is not "
6674 "i1",
6675 Call);
6676 break;
6677 }
6678 case Intrinsic::experimental_get_vector_length: {
6679 ConstantInt *VF = cast<ConstantInt>(Call.getArgOperand(1));
6680 Check(!VF->isNegative() && !VF->isZero(),
6681 "get_vector_length: VF must be positive", Call);
6682 break;
6683 }
6684 case Intrinsic::masked_load: {
6685 Check(Call.getType()->isVectorTy(), "masked_load: must return a vector",
6686 Call);
6687
6689 Value *PassThru = Call.getArgOperand(2);
6690 Check(Mask->getType()->isVectorTy(), "masked_load: mask must be vector",
6691 Call);
6692 Check(PassThru->getType() == Call.getType(),
6693 "masked_load: pass through and return type must match", Call);
6694 Check(cast<VectorType>(Mask->getType())->getElementCount() ==
6695 cast<VectorType>(Call.getType())->getElementCount(),
6696 "masked_load: vector mask must be same length as return", Call);
6697 break;
6698 }
6699 case Intrinsic::masked_store: {
6700 Value *Val = Call.getArgOperand(0);
6702 Check(Mask->getType()->isVectorTy(), "masked_store: mask must be vector",
6703 Call);
6704 Check(cast<VectorType>(Mask->getType())->getElementCount() ==
6705 cast<VectorType>(Val->getType())->getElementCount(),
6706 "masked_store: vector mask must be same length as value", Call);
6707 break;
6708 }
6709 case Intrinsic::experimental_guard: {
6710 Check(isa<CallInst>(Call), "experimental_guard cannot be invoked", Call);
6712 "experimental_guard must have exactly one "
6713 "\"deopt\" operand bundle");
6714 break;
6715 }
6716
6717 case Intrinsic::experimental_deoptimize: {
6718 Check(isa<CallInst>(Call), "experimental_deoptimize cannot be invoked",
6719 Call);
6721 "experimental_deoptimize must have exactly one "
6722 "\"deopt\" operand bundle");
6724 "experimental_deoptimize return type must match caller return type");
6725
6726 if (isa<CallInst>(Call)) {
6728 Check(RI,
6729 "calls to experimental_deoptimize must be followed by a return");
6730
6731 if (!Call.getType()->isVoidTy() && RI)
6732 Check(RI->getReturnValue() == &Call,
6733 "calls to experimental_deoptimize must be followed by a return "
6734 "of the value computed by experimental_deoptimize");
6735 }
6736
6737 break;
6738 }
6739 case Intrinsic::vastart: {
6741 "va_start called in a non-varargs function");
6742 break;
6743 }
6744 case Intrinsic::get_dynamic_area_offset: {
6745 auto *IntTy = dyn_cast<IntegerType>(Call.getType());
6746 Check(IntTy && DL.getPointerSizeInBits(DL.getAllocaAddrSpace()) ==
6747 IntTy->getBitWidth(),
6748 "get_dynamic_area_offset result type must be scalar integer matching "
6749 "alloca address space width",
6750 Call);
6751 break;
6752 }
6753 case Intrinsic::masked_udiv:
6754 case Intrinsic::masked_sdiv:
6755 case Intrinsic::masked_urem:
6756 case Intrinsic::masked_srem:
6757 case Intrinsic::vector_reduce_and:
6758 case Intrinsic::vector_reduce_or:
6759 case Intrinsic::vector_reduce_xor:
6760 case Intrinsic::vector_reduce_add:
6761 case Intrinsic::vector_reduce_mul:
6762 case Intrinsic::vector_reduce_smax:
6763 case Intrinsic::vector_reduce_smin:
6764 case Intrinsic::vector_reduce_umax:
6765 case Intrinsic::vector_reduce_umin: {
6766 Type *ArgTy = Call.getArgOperand(0)->getType();
6767 Check(ArgTy->isIntOrIntVectorTy() && ArgTy->isVectorTy(),
6768 "intrinsic has incorrect argument type!");
6769 break;
6770 }
6771 case Intrinsic::vector_reduce_fmax:
6772 case Intrinsic::vector_reduce_fmin: {
6773 Type *ArgTy = Call.getArgOperand(0)->getType();
6774 Check(ArgTy->isFPOrFPVectorTy() && ArgTy->isVectorTy(),
6775 "intrinsic has incorrect argument type!");
6776 break;
6777 }
6778 case Intrinsic::vector_reduce_fadd:
6779 case Intrinsic::vector_reduce_fmul: {
6780 // Unlike the other reductions, the first argument is a start value. The
6781 // second argument is the vector to be reduced.
6782 Type *ArgTy = Call.getArgOperand(1)->getType();
6783 Check(ArgTy->isFPOrFPVectorTy() && ArgTy->isVectorTy(),
6784 "intrinsic has incorrect argument type!");
6785 break;
6786 }
6787 case Intrinsic::smul_fix:
6788 case Intrinsic::smul_fix_sat:
6789 case Intrinsic::umul_fix:
6790 case Intrinsic::umul_fix_sat:
6791 case Intrinsic::sdiv_fix:
6792 case Intrinsic::sdiv_fix_sat:
6793 case Intrinsic::udiv_fix:
6794 case Intrinsic::udiv_fix_sat: {
6795 Value *Op1 = Call.getArgOperand(0);
6796 auto *Op3 = cast<ConstantInt>(Call.getArgOperand(2));
6797
6798 if (ID == Intrinsic::smul_fix || ID == Intrinsic::smul_fix_sat ||
6799 ID == Intrinsic::sdiv_fix || ID == Intrinsic::sdiv_fix_sat) {
6800 Check(Op3->getZExtValue() < Op1->getType()->getScalarSizeInBits(),
6801 "the scale of s[mul|div]_fix[_sat] must be less than the width of "
6802 "the operands");
6803 } else {
6804 Check(Op3->getZExtValue() <= Op1->getType()->getScalarSizeInBits(),
6805 "the scale of u[mul|div]_fix[_sat] must be less than or equal "
6806 "to the width of the operands");
6807 }
6808 break;
6809 }
6810 case Intrinsic::lrint:
6811 case Intrinsic::llrint:
6812 case Intrinsic::lround:
6813 case Intrinsic::llround: {
6814 Type *ValTy = Call.getArgOperand(0)->getType();
6815 Type *ResultTy = Call.getType();
6816 Check(ValTy->isVectorTy() == ResultTy->isVectorTy(),
6817 ExpectedName + ": argument and result disagree on vector use", &Call);
6818 if (auto *VTy = dyn_cast<VectorType>(ValTy)) {
6819 auto *RTy = dyn_cast<VectorType>(ResultTy);
6820 Check(VTy->getElementCount() == RTy->getElementCount(),
6821 ExpectedName + ": argument must be same length as result", &Call);
6822 }
6823 break;
6824 }
6825 case Intrinsic::bswap: {
6826 Type *Ty = Call.getType();
6827 unsigned Size = Ty->getScalarSizeInBits();
6828 Check(Size % 16 == 0, "bswap must be an even number of bytes", &Call);
6829 break;
6830 }
6831 case Intrinsic::invariant_start: {
6832 ConstantInt *InvariantSize = dyn_cast<ConstantInt>(Call.getArgOperand(0));
6833 Check(InvariantSize &&
6834 (!InvariantSize->isNegative() || InvariantSize->isMinusOne()),
6835 "invariant_start parameter must be -1, 0 or a positive number",
6836 &Call);
6837 break;
6838 }
6839 case Intrinsic::matrix_multiply:
6840 case Intrinsic::matrix_transpose:
6841 case Intrinsic::matrix_column_major_load:
6842 case Intrinsic::matrix_column_major_store: {
6844 ConstantInt *Stride = nullptr;
6845 ConstantInt *NumRows;
6846 ConstantInt *NumColumns;
6847 VectorType *ResultTy;
6848 Type *Op0ElemTy = nullptr;
6849 Type *Op1ElemTy = nullptr;
6850 switch (ID) {
6851 case Intrinsic::matrix_multiply: {
6852 NumRows = cast<ConstantInt>(Call.getArgOperand(2));
6853 ConstantInt *N = cast<ConstantInt>(Call.getArgOperand(3));
6854 NumColumns = cast<ConstantInt>(Call.getArgOperand(4));
6856 ->getNumElements() ==
6857 NumRows->getZExtValue() * N->getZExtValue(),
6858 "First argument of a matrix operation does not match specified "
6859 "shape!");
6861 ->getNumElements() ==
6862 N->getZExtValue() * NumColumns->getZExtValue(),
6863 "Second argument of a matrix operation does not match specified "
6864 "shape!");
6865
6866 ResultTy = cast<VectorType>(Call.getType());
6867 Op0ElemTy =
6868 cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
6869 Op1ElemTy =
6870 cast<VectorType>(Call.getArgOperand(1)->getType())->getElementType();
6871 break;
6872 }
6873 case Intrinsic::matrix_transpose:
6874 NumRows = cast<ConstantInt>(Call.getArgOperand(1));
6875 NumColumns = cast<ConstantInt>(Call.getArgOperand(2));
6876 ResultTy = cast<VectorType>(Call.getType());
6877 Op0ElemTy =
6878 cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
6879 break;
6880 case Intrinsic::matrix_column_major_load: {
6882 NumRows = cast<ConstantInt>(Call.getArgOperand(3));
6883 NumColumns = cast<ConstantInt>(Call.getArgOperand(4));
6884 ResultTy = cast<VectorType>(Call.getType());
6885 break;
6886 }
6887 case Intrinsic::matrix_column_major_store: {
6889 NumRows = cast<ConstantInt>(Call.getArgOperand(4));
6890 NumColumns = cast<ConstantInt>(Call.getArgOperand(5));
6891 ResultTy = cast<VectorType>(Call.getArgOperand(0)->getType());
6892 Op0ElemTy =
6893 cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
6894 break;
6895 }
6896 default:
6897 llvm_unreachable("unexpected intrinsic");
6898 }
6899
6900 Check(ResultTy->getElementType()->isIntegerTy() ||
6901 ResultTy->getElementType()->isFloatingPointTy(),
6902 "Result type must be an integer or floating-point type!", IF);
6903
6904 if (Op0ElemTy)
6905 Check(ResultTy->getElementType() == Op0ElemTy,
6906 "Vector element type mismatch of the result and first operand "
6907 "vector!",
6908 IF);
6909
6910 if (Op1ElemTy)
6911 Check(ResultTy->getElementType() == Op1ElemTy,
6912 "Vector element type mismatch of the result and second operand "
6913 "vector!",
6914 IF);
6915
6917 NumRows->getZExtValue() * NumColumns->getZExtValue(),
6918 "Result of a matrix operation does not fit in the returned vector!");
6919
6920 if (Stride) {
6921 Check(Stride->getBitWidth() <= 64, "Stride bitwidth cannot exceed 64!",
6922 IF);
6923 Check(Stride->getZExtValue() >= NumRows->getZExtValue(),
6924 "Stride must be greater or equal than the number of rows!", IF);
6925 }
6926
6927 break;
6928 }
6929 case Intrinsic::stepvector: {
6931 Check(VecTy && VecTy->getScalarType()->isIntegerTy() &&
6932 VecTy->getScalarSizeInBits() >= 8,
6933 "stepvector only supported for vectors of integers "
6934 "with a bitwidth of at least 8.",
6935 &Call);
6936 break;
6937 }
6938 case Intrinsic::experimental_vector_match: {
6939 Value *Op1 = Call.getArgOperand(0);
6940 Value *Op2 = Call.getArgOperand(1);
6942
6943 VectorType *Op1Ty = dyn_cast<VectorType>(Op1->getType());
6944 VectorType *Op2Ty = dyn_cast<VectorType>(Op2->getType());
6945 VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
6946
6947 Check(Op1Ty && Op2Ty && MaskTy, "Operands must be vectors.", &Call);
6949 "Second operand must be a fixed length vector.", &Call);
6950 Check(Op1Ty->getElementType()->isIntegerTy(),
6951 "First operand must be a vector of integers.", &Call);
6952 Check(Op1Ty->getElementType() == Op2Ty->getElementType(),
6953 "First two operands must have the same element type.", &Call);
6954 Check(Op1Ty->getElementCount() == MaskTy->getElementCount(),
6955 "First operand and mask must have the same number of elements.",
6956 &Call);
6957 Check(MaskTy->getElementType()->isIntegerTy(1),
6958 "Mask must be a vector of i1's.", &Call);
6959 Check(Call.getType() == MaskTy, "Return type must match the mask type.",
6960 &Call);
6961 break;
6962 }
6963 case Intrinsic::vector_insert: {
6964 Value *Vec = Call.getArgOperand(0);
6965 Value *SubVec = Call.getArgOperand(1);
6966 Value *Idx = Call.getArgOperand(2);
6967 unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
6968
6969 VectorType *VecTy = cast<VectorType>(Vec->getType());
6970 VectorType *SubVecTy = cast<VectorType>(SubVec->getType());
6971
6972 ElementCount VecEC = VecTy->getElementCount();
6973 ElementCount SubVecEC = SubVecTy->getElementCount();
6974 Check(VecTy->getElementType() == SubVecTy->getElementType(),
6975 "vector_insert parameters must have the same element "
6976 "type.",
6977 &Call);
6978 Check(IdxN % SubVecEC.getKnownMinValue() == 0,
6979 "vector_insert index must be a constant multiple of "
6980 "the subvector's known minimum vector length.");
6981
6982 // If this insertion is not the 'mixed' case where a fixed vector is
6983 // inserted into a scalable vector, ensure that the insertion of the
6984 // subvector does not overrun the parent vector.
6985 if (VecEC.isScalable() == SubVecEC.isScalable()) {
6986 Check(IdxN < VecEC.getKnownMinValue() &&
6987 IdxN + SubVecEC.getKnownMinValue() <= VecEC.getKnownMinValue(),
6988 "subvector operand of vector_insert would overrun the "
6989 "vector being inserted into.");
6990 }
6991 break;
6992 }
6993 case Intrinsic::vector_extract: {
6994 Value *Vec = Call.getArgOperand(0);
6995 Value *Idx = Call.getArgOperand(1);
6996 unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
6997
6998 VectorType *ResultTy = cast<VectorType>(Call.getType());
6999 VectorType *VecTy = cast<VectorType>(Vec->getType());
7000
7001 ElementCount VecEC = VecTy->getElementCount();
7002 ElementCount ResultEC = ResultTy->getElementCount();
7003
7004 Check(ResultTy->getElementType() == VecTy->getElementType(),
7005 "vector_extract result must have the same element "
7006 "type as the input vector.",
7007 &Call);
7008 Check(IdxN % ResultEC.getKnownMinValue() == 0,
7009 "vector_extract index must be a constant multiple of "
7010 "the result type's known minimum vector length.");
7011
7012 // If this extraction is not the 'mixed' case where a fixed vector is
7013 // extracted from a scalable vector, ensure that the extraction does not
7014 // overrun the parent vector.
7015 if (VecEC.isScalable() == ResultEC.isScalable()) {
7016 Check(IdxN < VecEC.getKnownMinValue() &&
7017 IdxN + ResultEC.getKnownMinValue() <= VecEC.getKnownMinValue(),
7018 "vector_extract would overrun.");
7019 }
7020 break;
7021 }
7022 case Intrinsic::vector_partial_reduce_fadd:
7023 case Intrinsic::vector_partial_reduce_add: {
7026
7027 unsigned VecWidth = VecTy->getElementCount().getKnownMinValue();
7028 unsigned AccWidth = AccTy->getElementCount().getKnownMinValue();
7029
7030 Check((VecWidth % AccWidth) == 0,
7031 "Invalid vector widths for partial "
7032 "reduction. The width of the input vector "
7033 "must be a positive integer multiple of "
7034 "the width of the accumulator vector.");
7035 break;
7036 }
7037 case Intrinsic::experimental_noalias_scope_decl: {
7038 NoAliasScopeDecls.push_back(cast<IntrinsicInst>(&Call));
7039 break;
7040 }
7041 case Intrinsic::preserve_array_access_index:
7042 case Intrinsic::preserve_struct_access_index:
7043 case Intrinsic::aarch64_ldaxr:
7044 case Intrinsic::aarch64_ldxr:
7045 case Intrinsic::arm_ldaex:
7046 case Intrinsic::arm_ldrex: {
7047 Type *ElemTy = Call.getParamElementType(0);
7048 Check(ElemTy, "Intrinsic requires elementtype attribute on first argument.",
7049 &Call);
7050 break;
7051 }
7052 case Intrinsic::aarch64_stlxr:
7053 case Intrinsic::aarch64_stxr:
7054 case Intrinsic::arm_stlex:
7055 case Intrinsic::arm_strex: {
7056 Type *ElemTy = Call.getAttributes().getParamElementType(1);
7057 Check(ElemTy,
7058 "Intrinsic requires elementtype attribute on second argument.",
7059 &Call);
7060 break;
7061 }
7062 case Intrinsic::aarch64_prefetch: {
7063 Check(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2,
7064 "write argument to llvm.aarch64.prefetch must be 0 or 1", Call);
7065 Check(cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 4,
7066 "target argument to llvm.aarch64.prefetch must be 0-3", Call);
7067 Check(cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue() < 2,
7068 "stream argument to llvm.aarch64.prefetch must be 0 or 1", Call);
7069 Check(cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue() < 2,
7070 "isdata argument to llvm.aarch64.prefetch must be 0 or 1", Call);
7071 break;
7072 }
7073 case Intrinsic::aarch64_range_prefetch: {
7074 Check(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2,
7075 "write argument to llvm.aarch64.range.prefetch must be 0 or 1", Call);
7076 Check(cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 2,
7077 "stream argument to llvm.aarch64.range.prefetch must be 0 or 1",
7078 Call);
7079 break;
7080 }
7081 case Intrinsic::callbr_landingpad: {
7082 const auto *CBR = dyn_cast<CallBrInst>(Call.getOperand(0));
7083 Check(CBR, "intrinstic requires callbr operand", &Call);
7084 if (!CBR)
7085 break;
7086
7087 const BasicBlock *LandingPadBB = Call.getParent();
7088 const BasicBlock *PredBB = LandingPadBB->getUniquePredecessor();
7089 if (!PredBB) {
7090 CheckFailed("Intrinsic in block must have 1 unique predecessor", &Call);
7091 break;
7092 }
7093 if (!isa<CallBrInst>(PredBB->getTerminator())) {
7094 CheckFailed("Intrinsic must have corresponding callbr in predecessor",
7095 &Call);
7096 break;
7097 }
7098 Check(llvm::is_contained(CBR->getIndirectDests(), LandingPadBB),
7099 "Intrinsic's corresponding callbr must have intrinsic's parent basic "
7100 "block in indirect destination list",
7101 &Call);
7102 const Instruction &First = *LandingPadBB->begin();
7103 Check(&First == &Call, "No other instructions may proceed intrinsic",
7104 &Call);
7105 break;
7106 }
7107 case Intrinsic::structured_gep: {
7108 // Parser should refuse those 2 cases.
7109 assert(Call.arg_size() >= 1);
7111
7112 Check(Call.paramHasAttr(0, Attribute::ElementType),
7113 "Intrinsic first parameter is missing an ElementType attribute",
7114 &Call);
7115
7116 Type *T = Call.getParamAttr(0, Attribute::ElementType).getValueAsType();
7117 for (unsigned I = 1; I < Call.arg_size(); ++I) {
7119 ConstantInt *CI = dyn_cast<ConstantInt>(Index);
7120 Check(Index->getType()->isIntegerTy(),
7121 "Index operand type must be an integer", &Call);
7122
7123 if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
7124 T = AT->getElementType();
7125 } else if (StructType *ST = dyn_cast<StructType>(T)) {
7126 Check(CI, "Indexing into a struct requires a constant int", &Call);
7127 Check(CI->getZExtValue() < ST->getNumElements(),
7128 "Indexing in a struct should be inbounds", &Call);
7129 T = ST->getElementType(CI->getZExtValue());
7130 } else if (VectorType *VT = dyn_cast<VectorType>(T)) {
7131 T = VT->getElementType();
7132 } else {
7133 CheckFailed("Reached a non-composite type with more indices to process",
7134 &Call);
7135 }
7136 }
7137 break;
7138 }
7139 case Intrinsic::structured_alloca:
7140 Check(Call.hasRetAttr(Attribute::ElementType),
7141 "@llvm.structured.alloca calls require elementtype attribute.",
7142 &Call);
7143 break;
7144 case Intrinsic::amdgcn_cs_chain: {
7145 auto CallerCC = Call.getCaller()->getCallingConv();
7146 switch (CallerCC) {
7147 case CallingConv::AMDGPU_CS:
7148 case CallingConv::AMDGPU_CS_Chain:
7149 case CallingConv::AMDGPU_CS_ChainPreserve:
7150 case CallingConv::AMDGPU_ES:
7151 case CallingConv::AMDGPU_GS:
7152 case CallingConv::AMDGPU_HS:
7153 case CallingConv::AMDGPU_LS:
7154 case CallingConv::AMDGPU_VS:
7155 break;
7156 default:
7157 CheckFailed("Intrinsic cannot be called from functions with this "
7158 "calling convention",
7159 &Call);
7160 break;
7161 }
7162
7163 Check(Call.paramHasAttr(2, Attribute::InReg),
7164 "SGPR arguments must have the `inreg` attribute", &Call);
7165 Check(!Call.paramHasAttr(3, Attribute::InReg),
7166 "VGPR arguments must not have the `inreg` attribute", &Call);
7167
7168 auto *FlagsArg = cast<ConstantInt>(Call.getArgOperand(4));
7169 Check(FlagsArg->getValue().ult(2),
7170 "flags must be 0 or 1 for llvm.amdgcn.cs.chain", &Call);
7171
7172 auto *Next = Call.getNextNode();
7173 bool IsAMDUnreachable = Next && isa<IntrinsicInst>(Next) &&
7174 cast<IntrinsicInst>(Next)->getIntrinsicID() ==
7175 Intrinsic::amdgcn_unreachable;
7176 Check(Next && (isa<UnreachableInst>(Next) || IsAMDUnreachable),
7177 "llvm.amdgcn.cs.chain must be followed by unreachable", &Call);
7178 break;
7179 }
7180 case Intrinsic::amdgcn_init_exec_from_input: {
7181 const Argument *Arg = dyn_cast<Argument>(Call.getOperand(0));
7182 Check(Arg && Arg->hasInRegAttr(),
7183 "only inreg arguments to the parent function are valid as inputs to "
7184 "this intrinsic",
7185 &Call);
7186 break;
7187 }
7188 case Intrinsic::amdgcn_set_inactive_chain_arg: {
7189 auto CallerCC = Call.getCaller()->getCallingConv();
7190 switch (CallerCC) {
7191 case CallingConv::AMDGPU_CS_Chain:
7192 case CallingConv::AMDGPU_CS_ChainPreserve:
7193 break;
7194 default:
7195 CheckFailed("Intrinsic can only be used from functions with the "
7196 "amdgpu_cs_chain or amdgpu_cs_chain_preserve "
7197 "calling conventions",
7198 &Call);
7199 break;
7200 }
7201
7202 unsigned InactiveIdx = 1;
7203 Check(!Call.paramHasAttr(InactiveIdx, Attribute::InReg),
7204 "Value for inactive lanes must not have the `inreg` attribute",
7205 &Call);
7206 Check(isa<Argument>(Call.getArgOperand(InactiveIdx)),
7207 "Value for inactive lanes must be a function argument", &Call);
7208 Check(!cast<Argument>(Call.getArgOperand(InactiveIdx))->hasInRegAttr(),
7209 "Value for inactive lanes must be a VGPR function argument", &Call);
7210 break;
7211 }
7212 case Intrinsic::amdgcn_call_whole_wave: {
7214 Check(F, "Indirect whole wave calls are not allowed", &Call);
7215
7216 CallingConv::ID CC = F->getCallingConv();
7217 Check(CC == CallingConv::AMDGPU_Gfx_WholeWave,
7218 "Callee must have the amdgpu_gfx_whole_wave calling convention",
7219 &Call);
7220
7221 Check(!F->isVarArg(), "Variadic whole wave calls are not allowed", &Call);
7222
7223 Check(Call.arg_size() == F->arg_size(),
7224 "Call argument count must match callee argument count", &Call);
7225
7226 // The first argument of the call is the callee, and the first argument of
7227 // the callee is the active mask. The rest of the arguments must match.
7228 Check(F->arg_begin()->getType()->isIntegerTy(1),
7229 "Callee must have i1 as its first argument", &Call);
7230 for (auto [CallArg, FuncArg] :
7231 drop_begin(zip_equal(Call.args(), F->args()))) {
7232 Check(CallArg->getType() == FuncArg.getType(),
7233 "Argument types must match", &Call);
7234
7235 // Check that inreg attributes match between call site and function
7236 Check(Call.paramHasAttr(FuncArg.getArgNo(), Attribute::InReg) ==
7237 FuncArg.hasInRegAttr(),
7238 "Argument inreg attributes must match", &Call);
7239 }
7240 break;
7241 }
7242 case Intrinsic::amdgcn_s_prefetch_data: {
7243 Check(
7246 "llvm.amdgcn.s.prefetch.data only supports global or constant memory");
7247 break;
7248 }
7249 case Intrinsic::amdgcn_load_to_lds:
7250 case Intrinsic::amdgcn_load_async_to_lds:
7251 case Intrinsic::amdgcn_global_load_lds:
7252 case Intrinsic::amdgcn_global_load_async_lds:
7253 case Intrinsic::amdgcn_raw_buffer_load_lds:
7254 case Intrinsic::amdgcn_raw_buffer_load_async_lds:
7255 case Intrinsic::amdgcn_raw_ptr_buffer_load_lds:
7256 case Intrinsic::amdgcn_raw_ptr_buffer_load_async_lds:
7257 case Intrinsic::amdgcn_struct_buffer_load_lds:
7258 case Intrinsic::amdgcn_struct_buffer_load_async_lds:
7259 case Intrinsic::amdgcn_struct_ptr_buffer_load_lds:
7260 case Intrinsic::amdgcn_struct_ptr_buffer_load_async_lds: {
7261 // The data byte size immarg is operand 2 for every load-to-LDS intrinsic.
7262 uint64_t Size = cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue();
7263 Check(Size == 1 || Size == 2 || Size == 4 || Size == 12 || Size == 16,
7264 "invalid data size for load-to-LDS intrinsic; must be 1, 2, 4, 12, "
7265 "or 16",
7266 &Call);
7267 break;
7268 }
7269 case Intrinsic::amdgcn_mfma_scale_f32_16x16x128_f8f6f4:
7270 case Intrinsic::amdgcn_mfma_scale_f32_32x32x64_f8f6f4: {
7271 Value *Src0 = Call.getArgOperand(0);
7272 Value *Src1 = Call.getArgOperand(1);
7273
7274 uint64_t CBSZ = cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue();
7275 uint64_t BLGP = cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue();
7276 Check(CBSZ <= 4, "invalid value for cbsz format", Call,
7277 Call.getArgOperand(3));
7278 Check(BLGP <= 4, "invalid value for blgp format", Call,
7279 Call.getArgOperand(4));
7280
7281 // AMDGPU::MFMAScaleFormats values
7282 auto getFormatNumRegs = [](unsigned FormatVal) {
7283 switch (FormatVal) {
7284 case 0:
7285 case 1:
7286 return 8u;
7287 case 2:
7288 case 3:
7289 return 6u;
7290 case 4:
7291 return 4u;
7292 default:
7293 llvm_unreachable("invalid format value");
7294 }
7295 };
7296
7297 auto isValidSrcASrcBVector = [](FixedVectorType *Ty) {
7298 if (!Ty || !Ty->getElementType()->isIntegerTy(32))
7299 return false;
7300 unsigned NumElts = Ty->getNumElements();
7301 return NumElts == 4 || NumElts == 6 || NumElts == 8;
7302 };
7303
7304 auto *Src0Ty = dyn_cast<FixedVectorType>(Src0->getType());
7305 auto *Src1Ty = dyn_cast<FixedVectorType>(Src1->getType());
7306 Check(isValidSrcASrcBVector(Src0Ty),
7307 "operand 0 must be 4, 6 or 8 element i32 vector", &Call, Src0);
7308 Check(isValidSrcASrcBVector(Src1Ty),
7309 "operand 1 must be 4, 6 or 8 element i32 vector", &Call, Src1);
7310
7311 // Permit excess registers for the format.
7312 Check(Src0Ty->getNumElements() >= getFormatNumRegs(CBSZ),
7313 "invalid vector type for format", &Call, Src0, Call.getArgOperand(3));
7314 Check(Src1Ty->getNumElements() >= getFormatNumRegs(BLGP),
7315 "invalid vector type for format", &Call, Src1, Call.getArgOperand(5));
7316 break;
7317 }
7318 case Intrinsic::amdgcn_wmma_f32_16x16x128_f8f6f4:
7319 case Intrinsic::amdgcn_wmma_scale_f32_16x16x128_f8f6f4:
7320 case Intrinsic::amdgcn_wmma_scale16_f32_16x16x128_f8f6f4: {
7321 Value *Src0 = Call.getArgOperand(1);
7322 Value *Src1 = Call.getArgOperand(3);
7323
7324 unsigned FmtA = cast<ConstantInt>(Call.getArgOperand(0))->getZExtValue();
7325 unsigned FmtB = cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue();
7326 Check(FmtA <= 4, "invalid value for matrix format", Call,
7327 Call.getArgOperand(0));
7328 Check(FmtB <= 4, "invalid value for matrix format", Call,
7329 Call.getArgOperand(2));
7330
7331 // AMDGPU::MatrixFMT values
7332 auto getFormatNumRegs = [](unsigned FormatVal) {
7333 switch (FormatVal) {
7334 case 0:
7335 case 1:
7336 return 16u;
7337 case 2:
7338 case 3:
7339 return 12u;
7340 case 4:
7341 return 8u;
7342 default:
7343 llvm_unreachable("invalid format value");
7344 }
7345 };
7346
7347 auto isValidSrcASrcBVector = [](FixedVectorType *Ty) {
7348 if (!Ty || !Ty->getElementType()->isIntegerTy(32))
7349 return false;
7350 unsigned NumElts = Ty->getNumElements();
7351 return NumElts == 16 || NumElts == 12 || NumElts == 8;
7352 };
7353
7354 auto *Src0Ty = dyn_cast<FixedVectorType>(Src0->getType());
7355 auto *Src1Ty = dyn_cast<FixedVectorType>(Src1->getType());
7356 Check(isValidSrcASrcBVector(Src0Ty),
7357 "operand 1 must be 8, 12 or 16 element i32 vector", &Call, Src0);
7358 Check(isValidSrcASrcBVector(Src1Ty),
7359 "operand 3 must be 8, 12 or 16 element i32 vector", &Call, Src1);
7360
7361 // Permit excess registers for the format.
7362 Check(Src0Ty->getNumElements() >= getFormatNumRegs(FmtA),
7363 "invalid vector type for format", &Call, Src0, Call.getArgOperand(0));
7364 Check(Src1Ty->getNumElements() >= getFormatNumRegs(FmtB),
7365 "invalid vector type for format", &Call, Src1, Call.getArgOperand(2));
7366 break;
7367 }
7368 case Intrinsic::amdgcn_cooperative_atomic_load_32x4B:
7369 case Intrinsic::amdgcn_cooperative_atomic_load_16x8B:
7370 case Intrinsic::amdgcn_cooperative_atomic_load_8x16B:
7371 case Intrinsic::amdgcn_cooperative_atomic_store_32x4B:
7372 case Intrinsic::amdgcn_cooperative_atomic_store_16x8B:
7373 case Intrinsic::amdgcn_cooperative_atomic_store_8x16B: {
7374 // Check we only use this intrinsic on the FLAT or GLOBAL address spaces.
7375 Value *PtrArg = Call.getArgOperand(0);
7376 const unsigned AS = PtrArg->getType()->getPointerAddressSpace();
7378 "cooperative atomic intrinsics require a generic or global pointer",
7379 &Call, PtrArg);
7380
7381 // Last argument must be a MD string
7383 MDNode *MD = cast<MDNode>(Op->getMetadata());
7384 Check((MD->getNumOperands() == 1) && isa<MDString>(MD->getOperand(0)),
7385 "cooperative atomic intrinsics require that the last argument is a "
7386 "metadata string",
7387 &Call, Op);
7388 break;
7389 }
7390 case Intrinsic::amdgcn_av_load_b128:
7391 case Intrinsic::amdgcn_av_store_b128: {
7392 // Last argument must be a MD string
7394 auto *MD = dyn_cast<MDNode>(Op->getMetadata());
7395 Check(MD && (MD->getNumOperands() == 1) && isa<MDString>(MD->getOperand(0)),
7396 "the last argument to av load/store intrinsics must be a "
7397 "metadata string",
7398 &Call, Op);
7399 break;
7400 }
7401 case Intrinsic::nvvm_setmaxnreg_inc_sync_aligned_u32:
7402 case Intrinsic::nvvm_setmaxnreg_dec_sync_aligned_u32: {
7403 Value *V = Call.getArgOperand(0);
7404 unsigned RegCount = cast<ConstantInt>(V)->getZExtValue();
7405 Check(RegCount % 8 == 0,
7406 "reg_count argument to nvvm.setmaxnreg must be in multiples of 8");
7407 break;
7408 }
7409 case Intrinsic::experimental_convergence_entry:
7410 case Intrinsic::experimental_convergence_anchor:
7411 break;
7412 case Intrinsic::experimental_convergence_loop:
7413 break;
7414 case Intrinsic::ptrmask: {
7415 Type *Ty0 = Call.getArgOperand(0)->getType();
7416 Type *Ty1 = Call.getArgOperand(1)->getType();
7418 "llvm.ptrmask intrinsic first argument must be pointer or vector "
7419 "of pointers",
7420 &Call);
7421 Check(
7422 Ty0->isVectorTy() == Ty1->isVectorTy(),
7423 "llvm.ptrmask intrinsic arguments must be both scalars or both vectors",
7424 &Call);
7425 if (Ty0->isVectorTy())
7426 Check(cast<VectorType>(Ty0)->getElementCount() ==
7427 cast<VectorType>(Ty1)->getElementCount(),
7428 "llvm.ptrmask intrinsic arguments must have the same number of "
7429 "elements",
7430 &Call);
7431 Check(DL.getIndexTypeSizeInBits(Ty0) == Ty1->getScalarSizeInBits(),
7432 "llvm.ptrmask intrinsic second argument bitwidth must match "
7433 "pointer index type size of first argument",
7434 &Call);
7435 break;
7436 }
7437 case Intrinsic::thread_pointer: {
7439 DL.getDefaultGlobalsAddressSpace(),
7440 "llvm.thread.pointer intrinsic return type must be for the globals "
7441 "address space",
7442 &Call);
7443 break;
7444 }
7445 case Intrinsic::threadlocal_address: {
7446 const Value &Arg0 = *Call.getArgOperand(0);
7447 Check(isa<GlobalValue>(Arg0),
7448 "llvm.threadlocal.address first argument must be a GlobalValue");
7449 Check(cast<GlobalValue>(Arg0).isThreadLocal(),
7450 "llvm.threadlocal.address operand isThreadLocal() must be true");
7451 break;
7452 }
7453 case Intrinsic::lifetime_start:
7454 case Intrinsic::lifetime_end: {
7455 Value *Ptr = Call.getArgOperand(0);
7456 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Ptr);
7457 Check(isa<AllocaInst>(Ptr) || isa<PoisonValue>(Ptr) ||
7458 (II && II->getIntrinsicID() == Intrinsic::structured_alloca),
7459 "llvm.lifetime.start/end can only be used on alloca or poison",
7460 &Call);
7461 break;
7462 }
7463 case Intrinsic::sponentry: {
7464 const unsigned StackAS = DL.getAllocaAddrSpace();
7465 const Type *RetTy = Call.getFunctionType()->getReturnType();
7466 Check(RetTy->getPointerAddressSpace() == StackAS,
7467 "llvm.sponentry must return a pointer to the stack", &Call);
7468 break;
7469 }
7470 case Intrinsic::write_volatile_register: {
7471 auto *MD = cast<MDNode>(
7472 cast<MetadataAsValue>(Call.getArgOperand(0))->getMetadata());
7473 Check(MD->getNumOperands() == 1 && isa<MDString>(MD->getOperand(0)),
7474 "llvm.write_volatile_register metadata must be a single MDString",
7475 &Call);
7476 break;
7477 }
7478 };
7479
7480 // Verify that there aren't any unmediated control transfers between funclets.
7482 Function *F = Call.getParent()->getParent();
7483 if (F->hasPersonalityFn() &&
7484 isScopedEHPersonality(classifyEHPersonality(F->getPersonalityFn()))) {
7485 // Run EH funclet coloring on-demand and cache results for other intrinsic
7486 // calls in this function
7487 if (BlockEHFuncletColors.empty())
7488 BlockEHFuncletColors = colorEHFunclets(*F);
7489
7490 // Check for catch-/cleanup-pad in first funclet block
7491 bool InEHFunclet = false;
7492 BasicBlock *CallBB = Call.getParent();
7493 const ColorVector &CV = BlockEHFuncletColors.find(CallBB)->second;
7494 assert(CV.size() > 0 && "Uncolored block");
7495 for (BasicBlock *ColorFirstBB : CV)
7496 if (auto It = ColorFirstBB->getFirstNonPHIIt();
7497 It != ColorFirstBB->end())
7499 InEHFunclet = true;
7500
7501 // Check for funclet operand bundle
7502 bool HasToken = false;
7503 for (unsigned I = 0, E = Call.getNumOperandBundles(); I != E; ++I)
7505 HasToken = true;
7506
7507 // This would cause silent code truncation in WinEHPrepare
7508 if (InEHFunclet)
7509 Check(HasToken, "Missing funclet token on intrinsic call", &Call);
7510 }
7511 }
7512}
7513
7514/// Carefully grab the subprogram from a local scope.
7515///
7516/// This carefully grabs the subprogram from a local scope, avoiding the
7517/// built-in assertions that would typically fire.
7519 if (!LocalScope)
7520 return nullptr;
7521
7522 if (auto *SP = dyn_cast<DISubprogram>(LocalScope))
7523 return SP;
7524
7525 if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope))
7526 return getSubprogram(LB->getRawScope());
7527
7528 // Just return null; broken scope chains are checked elsewhere.
7529 assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope");
7530 return nullptr;
7531}
7532
7533void Verifier::visit(DbgLabelRecord &DLR) {
7535 "invalid #dbg_label intrinsic variable", &DLR, DLR.getRawLabel());
7536
7537 // Ignore broken !dbg attachments; they're checked elsewhere.
7538 if (MDNode *N = DLR.getDebugLoc().getAsMDNode())
7539 if (!isa<DILocation>(N))
7540 return;
7541
7542 BasicBlock *BB = DLR.getParent();
7543 Function *F = BB ? BB->getParent() : nullptr;
7544
7545 // The scopes for variables and !dbg attachments must agree.
7546 DILabel *Label = DLR.getLabel();
7547 DILocation *Loc = DLR.getDebugLoc();
7548 CheckDI(Loc, "#dbg_label record requires a !dbg attachment", &DLR, BB, F);
7549
7550 DISubprogram *LabelSP = getSubprogram(Label->getRawScope());
7551 DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
7552 if (!LabelSP || !LocSP)
7553 return;
7554
7555 CheckDI(LabelSP == LocSP,
7556 "mismatched subprogram between #dbg_label label and !dbg attachment",
7557 &DLR, BB, F, Label, Label->getScope()->getSubprogram(), Loc,
7558 Loc->getScope()->getSubprogram());
7559}
7560
7561void Verifier::visit(DbgVariableRecord &DVR) {
7562 BasicBlock *BB = DVR.getParent();
7563 Function *F = BB->getParent();
7564
7565 CheckDI(DVR.getType() == DbgVariableRecord::LocationType::Value ||
7566 DVR.getType() == DbgVariableRecord::LocationType::Declare ||
7567 DVR.getType() == DbgVariableRecord::LocationType::DeclareValue ||
7568 DVR.getType() == DbgVariableRecord::LocationType::Assign,
7569 "invalid #dbg record type", &DVR, DVR.getType(), BB, F);
7570
7571 // The location for a DbgVariableRecord must be either a ValueAsMetadata,
7572 // DIArgList, or an empty MDNode (which is a legacy representation for an
7573 // "undef" location).
7574 auto *MD = DVR.getRawLocation();
7575 CheckDI(MD && (isa<ValueAsMetadata>(MD) || isa<DIArgList>(MD) ||
7576 (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands())),
7577 "invalid #dbg record address/value", &DVR, MD, BB, F);
7578 if (auto *VAM = dyn_cast<ValueAsMetadata>(MD)) {
7579 visitValueAsMetadata(*VAM, F);
7580 if (DVR.isDbgDeclare()) {
7581 // Allow integers here to support inttoptr salvage.
7582 Type *Ty = VAM->getValue()->getType();
7583 CheckDI(Ty->isPointerTy() || Ty->isIntegerTy(),
7584 "location of #dbg_declare must be a pointer or int", &DVR, MD, BB,
7585 F);
7586 }
7587 } else if (auto *AL = dyn_cast<DIArgList>(MD)) {
7588 visitDIArgList(*AL, F);
7589 }
7590
7592 "invalid #dbg record variable", &DVR, DVR.getRawVariable(), BB, F);
7593 visitMDNode(*DVR.getRawVariable(), AreDebugLocsAllowed::No);
7594
7596 "invalid #dbg record expression", &DVR, DVR.getRawExpression(), BB,
7597 F);
7598 visitMDNode(*DVR.getExpression(), AreDebugLocsAllowed::No);
7599
7600 if (DVR.isDbgAssign()) {
7602 "invalid #dbg_assign DIAssignID", &DVR, DVR.getRawAssignID(), BB,
7603 F);
7604 visitMDNode(*cast<DIAssignID>(DVR.getRawAssignID()),
7605 AreDebugLocsAllowed::No);
7606
7607 const auto *RawAddr = DVR.getRawAddress();
7608 // Similarly to the location above, the address for an assign
7609 // DbgVariableRecord must be a ValueAsMetadata or an empty MDNode, which
7610 // represents an undef address.
7611 CheckDI(
7612 isa<ValueAsMetadata>(RawAddr) ||
7613 (isa<MDNode>(RawAddr) && !cast<MDNode>(RawAddr)->getNumOperands()),
7614 "invalid #dbg_assign address", &DVR, DVR.getRawAddress(), BB, F);
7615 if (auto *VAM = dyn_cast<ValueAsMetadata>(RawAddr))
7616 visitValueAsMetadata(*VAM, F);
7617
7619 "invalid #dbg_assign address expression", &DVR,
7620 DVR.getRawAddressExpression(), BB, F);
7621 visitMDNode(*DVR.getAddressExpression(), AreDebugLocsAllowed::No);
7622
7623 // All of the linked instructions should be in the same function as DVR.
7624 for (Instruction *I : at::getAssignmentInsts(&DVR))
7625 CheckDI(DVR.getFunction() == I->getFunction(),
7626 "inst not in same function as #dbg_assign", I, &DVR, BB, F);
7627 }
7628
7629 // This check is redundant with one in visitLocalVariable().
7630 DILocalVariable *Var = DVR.getVariable();
7631 CheckDI(isType(Var->getRawType()), "invalid type ref", Var, Var->getRawType(),
7632 BB, F);
7633
7634 auto *DLNode = DVR.getDebugLoc().getAsMDNode();
7635 CheckDI(isa_and_nonnull<DILocation>(DLNode), "invalid #dbg record DILocation",
7636 &DVR, DLNode, BB, F);
7637 DILocation *Loc = DVR.getDebugLoc();
7638
7639 // The scopes for variables and !dbg attachments must agree.
7640 DISubprogram *VarSP = getSubprogram(Var->getRawScope());
7641 DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
7642 if (!VarSP || !LocSP)
7643 return; // Broken scope chains are checked elsewhere.
7644
7645 CheckDI(VarSP == LocSP,
7646 "mismatched subprogram between #dbg record variable and DILocation",
7647 &DVR, BB, F, Var, Var->getScope()->getSubprogram(), Loc,
7648 Loc->getScope()->getSubprogram(), BB, F);
7649
7650 verifyFnArgs(DVR);
7651}
7652
7653void Verifier::visitVPIntrinsic(VPIntrinsic &VPI) {
7654 if (auto *VPCast = dyn_cast<VPCastIntrinsic>(&VPI)) {
7655 auto *RetTy = cast<VectorType>(VPCast->getType());
7656 auto *ValTy = cast<VectorType>(VPCast->getOperand(0)->getType());
7657 Check(RetTy->getElementCount() == ValTy->getElementCount(),
7658 "VP cast intrinsic first argument and result vector lengths must be "
7659 "equal",
7660 *VPCast);
7661
7662 switch (VPCast->getIntrinsicID()) {
7663 default:
7664 llvm_unreachable("Unknown VP cast intrinsic");
7665 case Intrinsic::vp_trunc:
7666 Check(RetTy->isIntOrIntVectorTy() && ValTy->isIntOrIntVectorTy(),
7667 "llvm.vp.trunc intrinsic first argument and result element type "
7668 "must be integer",
7669 *VPCast);
7670 Check(RetTy->getScalarSizeInBits() < ValTy->getScalarSizeInBits(),
7671 "llvm.vp.trunc intrinsic the bit size of first argument must be "
7672 "larger than the bit size of the return type",
7673 *VPCast);
7674 break;
7675 case Intrinsic::vp_zext:
7676 case Intrinsic::vp_sext:
7677 Check(RetTy->isIntOrIntVectorTy() && ValTy->isIntOrIntVectorTy(),
7678 "llvm.vp.zext or llvm.vp.sext intrinsic first argument and result "
7679 "element type must be integer",
7680 *VPCast);
7681 Check(RetTy->getScalarSizeInBits() > ValTy->getScalarSizeInBits(),
7682 "llvm.vp.zext or llvm.vp.sext intrinsic the bit size of first "
7683 "argument must be smaller than the bit size of the return type",
7684 *VPCast);
7685 break;
7686 case Intrinsic::vp_fptoui:
7687 case Intrinsic::vp_fptosi:
7688 case Intrinsic::vp_lrint:
7689 case Intrinsic::vp_llrint:
7690 Check(
7691 RetTy->isIntOrIntVectorTy() && ValTy->isFPOrFPVectorTy(),
7692 "llvm.vp.fptoui, llvm.vp.fptosi, llvm.vp.lrint or llvm.vp.llrint" "intrinsic first argument element "
7693 "type must be floating-point and result element type must be integer",
7694 *VPCast);
7695 break;
7696 case Intrinsic::vp_uitofp:
7697 case Intrinsic::vp_sitofp:
7698 Check(
7699 RetTy->isFPOrFPVectorTy() && ValTy->isIntOrIntVectorTy(),
7700 "llvm.vp.uitofp or llvm.vp.sitofp intrinsic first argument element "
7701 "type must be integer and result element type must be floating-point",
7702 *VPCast);
7703 break;
7704 case Intrinsic::vp_fptrunc:
7705 Check(RetTy->isFPOrFPVectorTy() && ValTy->isFPOrFPVectorTy(),
7706 "llvm.vp.fptrunc intrinsic first argument and result element type "
7707 "must be floating-point",
7708 *VPCast);
7709 Check(RetTy->getScalarSizeInBits() < ValTy->getScalarSizeInBits(),
7710 "llvm.vp.fptrunc intrinsic the bit size of first argument must be "
7711 "larger than the bit size of the return type",
7712 *VPCast);
7713 break;
7714 case Intrinsic::vp_fpext:
7715 Check(RetTy->isFPOrFPVectorTy() && ValTy->isFPOrFPVectorTy(),
7716 "llvm.vp.fpext intrinsic first argument and result element type "
7717 "must be floating-point",
7718 *VPCast);
7719 Check(RetTy->getScalarSizeInBits() > ValTy->getScalarSizeInBits(),
7720 "llvm.vp.fpext intrinsic the bit size of first argument must be "
7721 "smaller than the bit size of the return type",
7722 *VPCast);
7723 break;
7724 case Intrinsic::vp_ptrtoint:
7725 Check(RetTy->isIntOrIntVectorTy() && ValTy->isPtrOrPtrVectorTy(),
7726 "llvm.vp.ptrtoint intrinsic first argument element type must be "
7727 "pointer and result element type must be integer",
7728 *VPCast);
7729 break;
7730 case Intrinsic::vp_inttoptr:
7731 Check(RetTy->isPtrOrPtrVectorTy() && ValTy->isIntOrIntVectorTy(),
7732 "llvm.vp.inttoptr intrinsic first argument element type must be "
7733 "integer and result element type must be pointer",
7734 *VPCast);
7735 break;
7736 }
7737 }
7738
7739 switch (VPI.getIntrinsicID()) {
7740 case Intrinsic::vp_fcmp: {
7741 auto Pred = cast<VPCmpIntrinsic>(&VPI)->getPredicate();
7743 "invalid predicate for VP FP comparison intrinsic", &VPI);
7744 break;
7745 }
7746 case Intrinsic::vp_icmp: {
7747 auto Pred = cast<VPCmpIntrinsic>(&VPI)->getPredicate();
7749 "invalid predicate for VP integer comparison intrinsic", &VPI);
7750 break;
7751 }
7752 case Intrinsic::vp_is_fpclass: {
7753 auto TestMask = cast<ConstantInt>(VPI.getOperand(1));
7754 Check((TestMask->getZExtValue() & ~static_cast<unsigned>(fcAllFlags)) == 0,
7755 "unsupported bits for llvm.vp.is.fpclass test mask");
7756 break;
7757 }
7758 case Intrinsic::experimental_vp_splice: {
7759 VectorType *VecTy = cast<VectorType>(VPI.getType());
7760 int64_t Idx = cast<ConstantInt>(VPI.getArgOperand(2))->getSExtValue();
7761 int64_t KnownMinNumElements = VecTy->getElementCount().getKnownMinValue();
7762 if (VPI.getParent() && VPI.getParent()->getParent()) {
7763 AttributeList Attrs = VPI.getParent()->getParent()->getAttributes();
7764 if (Attrs.hasFnAttr(Attribute::VScaleRange))
7765 KnownMinNumElements *= Attrs.getFnAttrs().getVScaleRangeMin();
7766 }
7767 Check((Idx < 0 && std::abs(Idx) <= KnownMinNumElements) ||
7768 (Idx >= 0 && Idx < KnownMinNumElements),
7769 "The splice index exceeds the range [-VL, VL-1] where VL is the "
7770 "known minimum number of elements in the vector. For scalable "
7771 "vectors the minimum number of elements is determined from "
7772 "vscale_range.",
7773 &VPI);
7774 break;
7775 }
7776 }
7777}
7778
7779void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) {
7780 unsigned NumOperands = FPI.getNonMetadataArgCount();
7781 bool HasRoundingMD =
7783
7784 // Add the expected number of metadata operands.
7785 NumOperands += (1 + HasRoundingMD);
7786
7787 // Compare intrinsics carry an extra predicate metadata operand.
7789 NumOperands += 1;
7790 Check((FPI.arg_size() == NumOperands),
7791 "invalid arguments for constrained FP intrinsic", &FPI);
7792
7793 switch (FPI.getIntrinsicID()) {
7794 case Intrinsic::experimental_constrained_lrint:
7795 case Intrinsic::experimental_constrained_llrint: {
7796 Type *ValTy = FPI.getArgOperand(0)->getType();
7797 Type *ResultTy = FPI.getType();
7798 Check(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
7799 "Intrinsic does not support vectors", &FPI);
7800 break;
7801 }
7802
7803 case Intrinsic::experimental_constrained_lround:
7804 case Intrinsic::experimental_constrained_llround: {
7805 Type *ValTy = FPI.getArgOperand(0)->getType();
7806 Type *ResultTy = FPI.getType();
7807 Check(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
7808 "Intrinsic does not support vectors", &FPI);
7809 break;
7810 }
7811
7812 case Intrinsic::experimental_constrained_fcmp:
7813 case Intrinsic::experimental_constrained_fcmps: {
7814 auto Pred = cast<ConstrainedFPCmpIntrinsic>(&FPI)->getPredicate();
7816 "invalid predicate for constrained FP comparison intrinsic", &FPI);
7817 break;
7818 }
7819
7820 case Intrinsic::experimental_constrained_fptosi:
7821 case Intrinsic::experimental_constrained_fptoui: {
7822 Value *Operand = FPI.getArgOperand(0);
7823 ElementCount SrcEC;
7824 Check(Operand->getType()->isFPOrFPVectorTy(),
7825 "Intrinsic first argument must be floating point", &FPI);
7826 if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
7827 SrcEC = cast<VectorType>(OperandT)->getElementCount();
7828 }
7829
7830 Operand = &FPI;
7831 Check(SrcEC.isNonZero() == Operand->getType()->isVectorTy(),
7832 "Intrinsic first argument and result disagree on vector use", &FPI);
7833 Check(Operand->getType()->isIntOrIntVectorTy(),
7834 "Intrinsic result must be an integer", &FPI);
7835 if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
7836 Check(SrcEC == cast<VectorType>(OperandT)->getElementCount(),
7837 "Intrinsic first argument and result vector lengths must be equal",
7838 &FPI);
7839 }
7840 break;
7841 }
7842
7843 case Intrinsic::experimental_constrained_sitofp:
7844 case Intrinsic::experimental_constrained_uitofp: {
7845 Value *Operand = FPI.getArgOperand(0);
7846 ElementCount SrcEC;
7847 Check(Operand->getType()->isIntOrIntVectorTy(),
7848 "Intrinsic first argument must be integer", &FPI);
7849 if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
7850 SrcEC = cast<VectorType>(OperandT)->getElementCount();
7851 }
7852
7853 Operand = &FPI;
7854 Check(SrcEC.isNonZero() == Operand->getType()->isVectorTy(),
7855 "Intrinsic first argument and result disagree on vector use", &FPI);
7856 Check(Operand->getType()->isFPOrFPVectorTy(),
7857 "Intrinsic result must be a floating point", &FPI);
7858 if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
7859 Check(SrcEC == cast<VectorType>(OperandT)->getElementCount(),
7860 "Intrinsic first argument and result vector lengths must be equal",
7861 &FPI);
7862 }
7863 break;
7864 }
7865
7866 case Intrinsic::experimental_constrained_fptrunc:
7867 case Intrinsic::experimental_constrained_fpext: {
7868 Value *Operand = FPI.getArgOperand(0);
7869 Type *OperandTy = Operand->getType();
7870 Value *Result = &FPI;
7871 Type *ResultTy = Result->getType();
7872 Check(OperandTy->isFPOrFPVectorTy(),
7873 "Intrinsic first argument must be FP or FP vector", &FPI);
7874 Check(ResultTy->isFPOrFPVectorTy(),
7875 "Intrinsic result must be FP or FP vector", &FPI);
7876 Check(OperandTy->isVectorTy() == ResultTy->isVectorTy(),
7877 "Intrinsic first argument and result disagree on vector use", &FPI);
7878 if (OperandTy->isVectorTy()) {
7879 Check(cast<VectorType>(OperandTy)->getElementCount() ==
7880 cast<VectorType>(ResultTy)->getElementCount(),
7881 "Intrinsic first argument and result vector lengths must be equal",
7882 &FPI);
7883 }
7884 if (FPI.getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) {
7885 Check(OperandTy->getScalarSizeInBits() > ResultTy->getScalarSizeInBits(),
7886 "Intrinsic first argument's type must be larger than result type",
7887 &FPI);
7888 } else {
7889 Check(OperandTy->getScalarSizeInBits() < ResultTy->getScalarSizeInBits(),
7890 "Intrinsic first argument's type must be smaller than result type",
7891 &FPI);
7892 }
7893 break;
7894 }
7895
7896 default:
7897 break;
7898 }
7899
7900 // If a non-metadata argument is passed in a metadata slot then the
7901 // error will be caught earlier when the incorrect argument doesn't
7902 // match the specification in the intrinsic call table. Thus, no
7903 // argument type check is needed here.
7904
7905 Check(FPI.getExceptionBehavior().has_value(),
7906 "invalid exception behavior argument", &FPI);
7907 if (HasRoundingMD) {
7908 Check(FPI.getRoundingMode().has_value(), "invalid rounding mode argument",
7909 &FPI);
7910 }
7911}
7912
7913void Verifier::verifyFragmentExpression(const DbgVariableRecord &DVR) {
7914 DILocalVariable *V = dyn_cast_or_null<DILocalVariable>(DVR.getRawVariable());
7915 DIExpression *E = dyn_cast_or_null<DIExpression>(DVR.getRawExpression());
7916
7917 // We don't know whether this intrinsic verified correctly.
7918 if (!V || !E || !E->isValid())
7919 return;
7920
7921 // Nothing to do if this isn't a DW_OP_LLVM_fragment expression.
7922 auto Fragment = E->getFragmentInfo();
7923 if (!Fragment)
7924 return;
7925
7926 // The frontend helps out GDB by emitting the members of local anonymous
7927 // unions as artificial local variables with shared storage. When SROA splits
7928 // the storage for artificial local variables that are smaller than the entire
7929 // union, the overhang piece will be outside of the allotted space for the
7930 // variable and this check fails.
7931 // FIXME: Remove this check as soon as clang stops doing this; it hides bugs.
7932 if (V->isArtificial())
7933 return;
7934
7935 verifyFragmentExpression(*V, *Fragment, &DVR);
7936}
7937
7938template <typename ValueOrMetadata>
7939void Verifier::verifyFragmentExpression(const DIVariable &V,
7941 ValueOrMetadata *Desc) {
7942 // If there's no size, the type is broken, but that should be checked
7943 // elsewhere.
7944 auto VarSize = V.getSizeInBits();
7945 if (!VarSize)
7946 return;
7947
7948 unsigned FragSize = Fragment.SizeInBits;
7949 unsigned FragOffset = Fragment.OffsetInBits;
7950 CheckDI(FragSize + FragOffset <= *VarSize,
7951 "fragment is larger than or outside of variable", Desc, &V);
7952 CheckDI(FragSize != *VarSize, "fragment covers entire variable", Desc, &V);
7953}
7954
7955void Verifier::verifyFnArgs(const DbgVariableRecord &DVR) {
7956 // This function does not take the scope of noninlined function arguments into
7957 // account. Don't run it if current function is nodebug, because it may
7958 // contain inlined debug intrinsics.
7959 if (!HasDebugInfo)
7960 return;
7961
7962 // For performance reasons only check non-inlined ones.
7963 if (DVR.getDebugLoc()->getInlinedAt())
7964 return;
7965
7966 DILocalVariable *Var = DVR.getVariable();
7967 CheckDI(Var, "#dbg record without variable");
7968
7969 unsigned ArgNo = Var->getArg();
7970 if (!ArgNo)
7971 return;
7972
7973 // Verify there are no duplicate function argument debug info entries.
7974 // These will cause hard-to-debug assertions in the DWARF backend.
7975 if (DebugFnArgs.size() < ArgNo)
7976 DebugFnArgs.resize(ArgNo, nullptr);
7977
7978 auto *Prev = DebugFnArgs[ArgNo - 1];
7979 DebugFnArgs[ArgNo - 1] = Var;
7980 CheckDI(!Prev || (Prev == Var), "conflicting debug info for argument", &DVR,
7981 Prev, Var);
7982}
7983
7984void Verifier::verifyNotEntryValue(const DbgVariableRecord &DVR) {
7985 DIExpression *E = dyn_cast_or_null<DIExpression>(DVR.getRawExpression());
7986
7987 // We don't know whether this intrinsic verified correctly.
7988 if (!E || !E->isValid())
7989 return;
7990
7992 Value *VarValue = DVR.getVariableLocationOp(0);
7993 if (isa<UndefValue>(VarValue) || isa<PoisonValue>(VarValue))
7994 return;
7995 // We allow EntryValues for swift async arguments, as they have an
7996 // ABI-guarantee to be turned into a specific register.
7997 if (auto *ArgLoc = dyn_cast_or_null<Argument>(VarValue);
7998 ArgLoc && ArgLoc->hasAttribute(Attribute::SwiftAsync))
7999 return;
8000 }
8001
8002 CheckDI(!E->isEntryValue(),
8003 "Entry values are only allowed in MIR unless they target a "
8004 "swiftasync Argument",
8005 &DVR);
8006}
8007
8008void Verifier::verifyCompileUnits() {
8009 // When more than one Module is imported into the same context, such as during
8010 // an LTO build before linking the modules, ODR type uniquing may cause types
8011 // to point to a different CU. This check does not make sense in this case.
8012 if (M.getContext().isODRUniquingDebugTypes())
8013 return;
8014 auto *CUs = M.getNamedMetadata("llvm.dbg.cu");
8015 SmallPtrSet<const Metadata *, 2> Listed;
8016 if (CUs)
8017 Listed.insert_range(CUs->operands());
8018 for (const auto *CU : CUVisited)
8019 CheckDI(Listed.count(CU), "DICompileUnit not listed in llvm.dbg.cu", CU);
8020 CUVisited.clear();
8021}
8022
8023void Verifier::verifyDeoptimizeCallingConvs() {
8024 if (DeoptimizeDeclarations.empty())
8025 return;
8026
8027 const Function *First = DeoptimizeDeclarations[0];
8028 for (const auto *F : ArrayRef(DeoptimizeDeclarations).slice(1)) {
8029 Check(First->getCallingConv() == F->getCallingConv(),
8030 "All llvm.experimental.deoptimize declarations must have the same "
8031 "calling convention",
8032 First, F);
8033 }
8034}
8035
8036void Verifier::verifyAttachedCallBundle(const CallBase &Call,
8037 const OperandBundleUse &BU) {
8038 FunctionType *FTy = Call.getFunctionType();
8039
8040 Check((FTy->getReturnType()->isPointerTy() ||
8041 (Call.doesNotReturn() && FTy->getReturnType()->isVoidTy())),
8042 "a call with operand bundle \"clang.arc.attachedcall\" must call a "
8043 "function returning a pointer or a non-returning function that has a "
8044 "void return type",
8045 Call);
8046
8047 Check(BU.Inputs.size() == 1 && isa<Function>(BU.Inputs.front()),
8048 "operand bundle \"clang.arc.attachedcall\" requires one function as "
8049 "an argument",
8050 Call);
8051
8052 auto *Fn = cast<Function>(BU.Inputs.front());
8053 Intrinsic::ID IID = Fn->getIntrinsicID();
8054
8055 if (IID) {
8056 Check((IID == Intrinsic::objc_retainAutoreleasedReturnValue ||
8057 IID == Intrinsic::objc_claimAutoreleasedReturnValue ||
8058 IID == Intrinsic::objc_unsafeClaimAutoreleasedReturnValue),
8059 "invalid function argument", Call);
8060 } else {
8061 StringRef FnName = Fn->getName();
8062 Check((FnName == "objc_retainAutoreleasedReturnValue" ||
8063 FnName == "objc_claimAutoreleasedReturnValue" ||
8064 FnName == "objc_unsafeClaimAutoreleasedReturnValue"),
8065 "invalid function argument", Call);
8066 }
8067}
8068
8069void Verifier::verifyNoAliasScopeDecl() {
8070 if (NoAliasScopeDecls.empty())
8071 return;
8072
8073 // only a single scope must be declared at a time.
8074 for (auto *II : NoAliasScopeDecls) {
8075 assert(II->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl &&
8076 "Not a llvm.experimental.noalias.scope.decl ?");
8077 const auto *ScopeListMV = dyn_cast<MetadataAsValue>(
8079 Check(ScopeListMV != nullptr,
8080 "llvm.experimental.noalias.scope.decl must have a MetadataAsValue "
8081 "argument",
8082 II);
8083
8084 const auto *ScopeListMD = dyn_cast<MDNode>(ScopeListMV->getMetadata());
8085 Check(ScopeListMD != nullptr, "!id.scope.list must point to an MDNode", II);
8086 Check(ScopeListMD->getNumOperands() == 1,
8087 "!id.scope.list must point to a list with a single scope", II);
8088 visitAliasScopeListMetadata(ScopeListMD);
8089 }
8090
8091 // Only check the domination rule when requested. Once all passes have been
8092 // adapted this option can go away.
8094 return;
8095
8096 // Now sort the intrinsics based on the scope MDNode so that declarations of
8097 // the same scopes are next to each other.
8098 auto GetScope = [](IntrinsicInst *II) {
8099 const auto *ScopeListMV = cast<MetadataAsValue>(
8101 return &cast<MDNode>(ScopeListMV->getMetadata())->getOperand(0);
8102 };
8103
8104 // We are sorting on MDNode pointers here. For valid input IR this is ok.
8105 // TODO: Sort on Metadata ID to avoid non-deterministic error messages.
8106 auto Compare = [GetScope](IntrinsicInst *Lhs, IntrinsicInst *Rhs) {
8107 return GetScope(Lhs) < GetScope(Rhs);
8108 };
8109
8110 llvm::sort(NoAliasScopeDecls, Compare);
8111
8112 // Go over the intrinsics and check that for the same scope, they are not
8113 // dominating each other.
8114 auto ItCurrent = NoAliasScopeDecls.begin();
8115 while (ItCurrent != NoAliasScopeDecls.end()) {
8116 auto CurScope = GetScope(*ItCurrent);
8117 auto ItNext = ItCurrent;
8118 do {
8119 ++ItNext;
8120 } while (ItNext != NoAliasScopeDecls.end() &&
8121 GetScope(*ItNext) == CurScope);
8122
8123 // [ItCurrent, ItNext) represents the declarations for the same scope.
8124 // Ensure they are not dominating each other.. but only if it is not too
8125 // expensive.
8126 if (ItNext - ItCurrent < 32)
8127 for (auto *I : llvm::make_range(ItCurrent, ItNext))
8128 for (auto *J : llvm::make_range(ItCurrent, ItNext))
8129 if (I != J)
8130 Check(!DT.dominates(I, J),
8131 "llvm.experimental.noalias.scope.decl dominates another one "
8132 "with the same scope",
8133 I);
8134 ItCurrent = ItNext;
8135 }
8136}
8137
8138//===----------------------------------------------------------------------===//
8139// Implement the public interfaces to this file...
8140//===----------------------------------------------------------------------===//
8141
8143 Function &F = const_cast<Function &>(f);
8144
8145 // Don't use a raw_null_ostream. Printing IR is expensive.
8146 Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/true, *f.getParent());
8147
8148 // Note that this function's return value is inverted from what you would
8149 // expect of a function called "verify".
8150 return !V.verify(F);
8151}
8152
8154 bool *BrokenDebugInfo) {
8155 // Don't use a raw_null_ostream. Printing IR is expensive.
8156 Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/!BrokenDebugInfo, M);
8157
8158 bool Broken = false;
8159 for (const Function &F : M)
8160 Broken |= !V.verify(F);
8161
8162 Broken |= !V.verify();
8163 if (BrokenDebugInfo)
8164 *BrokenDebugInfo = V.hasBrokenDebugInfo();
8165 // Note that this function's return value is inverted from what you would
8166 // expect of a function called "verify".
8167 return Broken;
8168}
8169
8170namespace {
8171
8172struct VerifierLegacyPass : public FunctionPass {
8173 static char ID;
8174
8175 std::unique_ptr<Verifier> V;
8176 bool FatalErrors = true;
8177
8178 VerifierLegacyPass() : FunctionPass(ID) {}
8179 explicit VerifierLegacyPass(bool FatalErrors)
8180 : FunctionPass(ID), FatalErrors(FatalErrors) {}
8181
8182 bool doInitialization(Module &M) override {
8183 V = std::make_unique<Verifier>(
8184 &dbgs(), /*ShouldTreatBrokenDebugInfoAsError=*/false, M);
8185 return false;
8186 }
8187
8188 bool runOnFunction(Function &F) override {
8189 if (!V->verify(F) && FatalErrors) {
8190 errs() << "in function " << F.getName() << '\n';
8191 report_fatal_error("Broken function found, compilation aborted!");
8192 }
8193 return false;
8194 }
8195
8196 bool doFinalization(Module &M) override {
8197 bool HasErrors = false;
8198 for (Function &F : M)
8199 if (F.isDeclaration())
8200 HasErrors |= !V->verify(F);
8201
8202 HasErrors |= !V->verify();
8203 if (FatalErrors && (HasErrors || V->hasBrokenDebugInfo()))
8204 report_fatal_error("Broken module found, compilation aborted!");
8205 return false;
8206 }
8207
8208 void getAnalysisUsage(AnalysisUsage &AU) const override {
8209 AU.setPreservesAll();
8210 }
8211};
8212
8213} // end anonymous namespace
8214
8215/// Helper to issue failure from the TBAA verification
8216template <typename... Tys> void TBAAVerifier::CheckFailed(Tys &&... Args) {
8217 if (Diagnostic)
8218 return Diagnostic->CheckFailed(Args...);
8219}
8220
8221#define CheckTBAA(C, ...) \
8222 do { \
8223 if (!(C)) { \
8224 CheckFailed(__VA_ARGS__); \
8225 return false; \
8226 } \
8227 } while (false)
8228
8229/// Verify that \p BaseNode can be used as the "base type" in the struct-path
8230/// TBAA scheme. This means \p BaseNode is either a scalar node, or a
8231/// struct-type node describing an aggregate data structure (like a struct).
8232TBAAVerifier::TBAABaseNodeSummary
8233TBAAVerifier::verifyTBAABaseNode(const Instruction *I, const MDNode *BaseNode,
8234 bool IsNewFormat) {
8235 if (BaseNode->getNumOperands() < 2) {
8236 CheckFailed("Base nodes must have at least two operands", I, BaseNode);
8237 return {true, ~0u};
8238 }
8239
8240 auto Itr = TBAABaseNodes.find(BaseNode);
8241 if (Itr != TBAABaseNodes.end())
8242 return Itr->second;
8243
8244 auto Result = verifyTBAABaseNodeImpl(I, BaseNode, IsNewFormat);
8245 auto InsertResult = TBAABaseNodes.insert({BaseNode, Result});
8246 (void)InsertResult;
8247 assert(InsertResult.second && "We just checked!");
8248 return Result;
8249}
8250
8251TBAAVerifier::TBAABaseNodeSummary
8252TBAAVerifier::verifyTBAABaseNodeImpl(const Instruction *I,
8253 const MDNode *BaseNode, bool IsNewFormat) {
8254 const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {true, ~0u};
8255
8256 if (BaseNode->getNumOperands() == 2) {
8257 // Scalar nodes can only be accessed at offset 0.
8258 return isValidScalarTBAANode(BaseNode)
8259 ? TBAAVerifier::TBAABaseNodeSummary({false, 0})
8260 : InvalidNode;
8261 }
8262
8263 if (IsNewFormat) {
8264 if (BaseNode->getNumOperands() % 3 != 0) {
8265 CheckFailed("Access tag nodes must have the number of operands that is a "
8266 "multiple of 3!", BaseNode);
8267 return InvalidNode;
8268 }
8269 } else {
8270 if (BaseNode->getNumOperands() % 2 != 1) {
8271 CheckFailed("Struct tag nodes must have an odd number of operands!",
8272 BaseNode);
8273 return InvalidNode;
8274 }
8275 }
8276
8277 // Check the type size field.
8278 if (IsNewFormat) {
8279 auto *TypeSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
8280 BaseNode->getOperand(1));
8281 if (!TypeSizeNode) {
8282 CheckFailed("Type size nodes must be constants!", I, BaseNode);
8283 return InvalidNode;
8284 }
8285 }
8286
8287 // Check the type name field. In the new format it can be anything.
8288 if (!IsNewFormat && !isa<MDString>(BaseNode->getOperand(0))) {
8289 CheckFailed("Struct tag nodes have a string as their first operand",
8290 BaseNode);
8291 return InvalidNode;
8292 }
8293
8294 bool Failed = false;
8295
8296 std::optional<APInt> PrevOffset;
8297 unsigned BitWidth = ~0u;
8298
8299 // We've already checked that BaseNode is not a degenerate root node with one
8300 // operand in \c verifyTBAABaseNode, so this loop should run at least once.
8301 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
8302 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
8303 for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
8304 Idx += NumOpsPerField) {
8305 const MDOperand &FieldTy = BaseNode->getOperand(Idx);
8306 const MDOperand &FieldOffset = BaseNode->getOperand(Idx + 1);
8307 if (!isa<MDNode>(FieldTy)) {
8308 CheckFailed("Incorrect field entry in struct type node!", I, BaseNode);
8309 Failed = true;
8310 continue;
8311 }
8312
8313 auto *OffsetEntryCI =
8315 if (!OffsetEntryCI) {
8316 CheckFailed("Offset entries must be constants!", I, BaseNode);
8317 Failed = true;
8318 continue;
8319 }
8320
8321 if (BitWidth == ~0u)
8322 BitWidth = OffsetEntryCI->getBitWidth();
8323
8324 if (OffsetEntryCI->getBitWidth() != BitWidth) {
8325 CheckFailed(
8326 "Bitwidth between the offsets and struct type entries must match", I,
8327 BaseNode);
8328 Failed = true;
8329 continue;
8330 }
8331
8332 // NB! As far as I can tell, we generate a non-strictly increasing offset
8333 // sequence only from structs that have zero size bit fields. When
8334 // recursing into a contained struct in \c getFieldNodeFromTBAABaseNode we
8335 // pick the field lexically the latest in struct type metadata node. This
8336 // mirrors the actual behavior of the alias analysis implementation.
8337 bool IsAscending =
8338 !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue());
8339
8340 if (!IsAscending) {
8341 CheckFailed("Offsets must be increasing!", I, BaseNode);
8342 Failed = true;
8343 }
8344
8345 PrevOffset = OffsetEntryCI->getValue();
8346
8347 if (IsNewFormat) {
8348 auto *MemberSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
8349 BaseNode->getOperand(Idx + 2));
8350 if (!MemberSizeNode) {
8351 CheckFailed("Member size entries must be constants!", I, BaseNode);
8352 Failed = true;
8353 continue;
8354 }
8355 }
8356 }
8357
8358 return Failed ? InvalidNode
8359 : TBAAVerifier::TBAABaseNodeSummary(false, BitWidth);
8360}
8361
8362static bool IsRootTBAANode(const MDNode *MD) {
8363 return MD->getNumOperands() < 2;
8364}
8365
8366static bool IsScalarTBAANodeImpl(const MDNode *MD,
8368 if (MD->getNumOperands() != 2 && MD->getNumOperands() != 3)
8369 return false;
8370
8371 if (!isa<MDString>(MD->getOperand(0)))
8372 return false;
8373
8374 if (MD->getNumOperands() == 3) {
8376 if (!(Offset && Offset->isZero() && isa<MDString>(MD->getOperand(0))))
8377 return false;
8378 }
8379
8380 auto *Parent = dyn_cast_or_null<MDNode>(MD->getOperand(1));
8381 return Parent && Visited.insert(Parent).second &&
8382 (IsRootTBAANode(Parent) || IsScalarTBAANodeImpl(Parent, Visited));
8383}
8384
8385bool TBAAVerifier::isValidScalarTBAANode(const MDNode *MD) {
8386 auto ResultIt = TBAAScalarNodes.find(MD);
8387 if (ResultIt != TBAAScalarNodes.end())
8388 return ResultIt->second;
8389
8390 SmallPtrSet<const MDNode *, 4> Visited;
8391 bool Result = IsScalarTBAANodeImpl(MD, Visited);
8392 auto InsertResult = TBAAScalarNodes.insert({MD, Result});
8393 (void)InsertResult;
8394 assert(InsertResult.second && "Just checked!");
8395
8396 return Result;
8397}
8398
8399/// Returns the field node at the offset \p Offset in \p BaseNode. Update \p
8400/// Offset in place to be the offset within the field node returned.
8401///
8402/// We assume we've okayed \p BaseNode via \c verifyTBAABaseNode.
8403MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(const Instruction *I,
8404 const MDNode *BaseNode,
8405 APInt &Offset,
8406 bool IsNewFormat) {
8407 assert(BaseNode->getNumOperands() >= 2 && "Invalid base node!");
8408
8409 // Scalar nodes have only one possible "field" -- their parent in the access
8410 // hierarchy. Offset must be zero at this point, but our caller is supposed
8411 // to check that.
8412 if (BaseNode->getNumOperands() == 2)
8413 return cast<MDNode>(BaseNode->getOperand(1));
8414
8415 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
8416 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
8417 for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
8418 Idx += NumOpsPerField) {
8419 auto *OffsetEntryCI =
8420 mdconst::extract<ConstantInt>(BaseNode->getOperand(Idx + 1));
8421 if (OffsetEntryCI->getValue().ugt(Offset)) {
8422 if (Idx == FirstFieldOpNo) {
8423 CheckFailed("Could not find TBAA parent in struct type node", I,
8424 BaseNode, &Offset);
8425 return nullptr;
8426 }
8427
8428 unsigned PrevIdx = Idx - NumOpsPerField;
8429 auto *PrevOffsetEntryCI =
8430 mdconst::extract<ConstantInt>(BaseNode->getOperand(PrevIdx + 1));
8431 Offset -= PrevOffsetEntryCI->getValue();
8432 return cast<MDNode>(BaseNode->getOperand(PrevIdx));
8433 }
8434 }
8435
8436 unsigned LastIdx = BaseNode->getNumOperands() - NumOpsPerField;
8437 auto *LastOffsetEntryCI = mdconst::extract<ConstantInt>(
8438 BaseNode->getOperand(LastIdx + 1));
8439 Offset -= LastOffsetEntryCI->getValue();
8440 return cast<MDNode>(BaseNode->getOperand(LastIdx));
8441}
8442
8444 if (!Type || Type->getNumOperands() < 3)
8445 return false;
8446
8447 // In the new format type nodes shall have a reference to the parent type as
8448 // its first operand.
8449 return isa_and_nonnull<MDNode>(Type->getOperand(0));
8450}
8451
8453 CheckTBAA(MD->getNumOperands() > 0, "TBAA metadata cannot have 0 operands", I,
8454 MD);
8455
8456 if (I)
8460 "This instruction shall not have a TBAA access tag!", I);
8461
8462 bool IsStructPathTBAA =
8463 isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3;
8464
8465 CheckTBAA(IsStructPathTBAA,
8466 "Old-style TBAA is no longer allowed, use struct-path TBAA instead",
8467 I);
8468
8469 MDNode *BaseNode = dyn_cast_or_null<MDNode>(MD->getOperand(0));
8470 MDNode *AccessType = dyn_cast_or_null<MDNode>(MD->getOperand(1));
8471
8472 bool IsNewFormat = isNewFormatTBAATypeNode(AccessType);
8473
8474 if (IsNewFormat) {
8475 CheckTBAA(MD->getNumOperands() == 4 || MD->getNumOperands() == 5,
8476 "Access tag metadata must have either 4 or 5 operands", I, MD);
8477 } else {
8478 CheckTBAA(MD->getNumOperands() < 5,
8479 "Struct tag metadata must have either 3 or 4 operands", I, MD);
8480 }
8481
8482 // Check the access size field.
8483 if (IsNewFormat) {
8484 auto *AccessSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
8485 MD->getOperand(3));
8486 CheckTBAA(AccessSizeNode, "Access size field must be a constant", I, MD);
8487 }
8488
8489 // Check the immutability flag.
8490 unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3;
8491 if (MD->getNumOperands() == ImmutabilityFlagOpNo + 1) {
8492 auto *IsImmutableCI = mdconst::dyn_extract_or_null<ConstantInt>(
8493 MD->getOperand(ImmutabilityFlagOpNo));
8494 CheckTBAA(IsImmutableCI,
8495 "Immutability tag on struct tag metadata must be a constant", I,
8496 MD);
8497 CheckTBAA(
8498 IsImmutableCI->isZero() || IsImmutableCI->isOne(),
8499 "Immutability part of the struct tag metadata must be either 0 or 1", I,
8500 MD);
8501 }
8502
8503 CheckTBAA(BaseNode && AccessType,
8504 "Malformed struct tag metadata: base and access-type "
8505 "should be non-null and point to Metadata nodes",
8506 I, MD, BaseNode, AccessType);
8507
8508 if (!IsNewFormat) {
8509 CheckTBAA(isValidScalarTBAANode(AccessType),
8510 "Access type node must be a valid scalar type", I, MD,
8511 AccessType);
8512 }
8513
8515 CheckTBAA(OffsetCI, "Offset must be constant integer", I, MD);
8516
8517 APInt Offset = OffsetCI->getValue();
8518 bool SeenAccessTypeInPath = false;
8519
8520 SmallPtrSet<MDNode *, 4> StructPath;
8521
8522 for (/* empty */; BaseNode && !IsRootTBAANode(BaseNode);
8523 BaseNode =
8524 getFieldNodeFromTBAABaseNode(I, BaseNode, Offset, IsNewFormat)) {
8525 if (!StructPath.insert(BaseNode).second) {
8526 CheckFailed("Cycle detected in struct path", I, MD);
8527 return false;
8528 }
8529
8530 bool Invalid;
8531 unsigned BaseNodeBitWidth;
8532 std::tie(Invalid, BaseNodeBitWidth) =
8533 verifyTBAABaseNode(I, BaseNode, IsNewFormat);
8534
8535 // If the base node is invalid in itself, then we've already printed all the
8536 // errors we wanted to print.
8537 if (Invalid)
8538 return false;
8539
8540 SeenAccessTypeInPath |= BaseNode == AccessType;
8541
8542 if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType)
8543 CheckTBAA(Offset == 0, "Offset not zero at the point of scalar access", I,
8544 MD, &Offset);
8545
8546 CheckTBAA(BaseNodeBitWidth == Offset.getBitWidth() ||
8547 (BaseNodeBitWidth == 0 && Offset == 0) ||
8548 (IsNewFormat && BaseNodeBitWidth == ~0u),
8549 "Access bit-width not the same as description bit-width", I, MD,
8550 BaseNodeBitWidth, Offset.getBitWidth());
8551
8552 if (IsNewFormat && SeenAccessTypeInPath)
8553 break;
8554 }
8555
8556 CheckTBAA(SeenAccessTypeInPath, "Did not see access type in access path!", I,
8557 MD);
8558 return true;
8559}
8560
8561char VerifierLegacyPass::ID = 0;
8562INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
8563
8565 return new VerifierLegacyPass(FatalErrors);
8566}
8567
8568AnalysisKey VerifierAnalysis::Key;
8575
8580
8582 auto Res = AM.getResult<VerifierAnalysis>(M);
8583 if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken))
8584 report_fatal_error("Broken module found, compilation aborted!");
8585
8586 return PreservedAnalyses::all();
8587}
8588
8590 auto res = AM.getResult<VerifierAnalysis>(F);
8591 if (res.IRBroken && FatalErrors)
8592 report_fatal_error("Broken function found, compilation aborted!");
8593
8594 return PreservedAnalyses::all();
8595}
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"))
#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:288
bool isElementwise() const
Return true if this RMW has elementwise vector semantics.
static bool isFPOperation(BinOp Op)
BinOp getOperation() const
static LLVM_ABI StringRef getOperationName(BinOp Op)
AtomicOrdering getOrdering() const
Returns the ordering constraint of this rmw instruction.
bool contains(Attribute::AttrKind A) const
Return true if the builder has the specified attribute.
LLVM_ABI bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
LLVM_ABI std::string getAsString(bool InAttrGrp=false) const
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:105
LLVM_ABI const ConstantRange & getValueAsConstantRange() const
Return the attribute's value as a ConstantRange.
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:124
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:261
LLVM_ABI Type * getValueAsType() const
Return the attribute's value as a Type.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:461
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:530
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI bool isEntryBlock() const
Return true if this is the entry block of the containing function.
const Instruction & front() const
Definition BasicBlock.h:484
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
This class represents a no-op cast from one type to another.
static LLVM_ABI BlockAddress * lookup(const BasicBlock *BB)
Lookup an existing BlockAddress constant for the given BasicBlock.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
bool isInlineAsm() const
Check if this call is an inline asm statement.
auto operand_bundles() const
bool hasInAllocaArgument() const
Determine if there are is an inalloca argument.
OperandBundleUse getOperandBundleAt(unsigned Index) const
Return the operand bundle at a specific index.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool doesNotAccessMemory(unsigned OpNo) const
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
bool hasRetAttr(Attribute::AttrKind Kind) const
Determine whether the return value has the given attribute.
unsigned getNumOperandBundles() const
Return the number of operand bundles associated with this User.
CallingConv::ID getCallingConv() const
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
Attribute getParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Get the attribute of a given kind from a given arg.
unsigned countOperandBundlesOfType(StringRef Name) const
Return the number of operand bundles with the tag Name attached to this instruction.
bool onlyReadsMemory(unsigned OpNo) const
Value * getCalledOperand() const
Type * getParamElementType(unsigned ArgNo) const
Extract the elementtype type for a parameter.
Value * getArgOperand(unsigned i) const
FunctionType * getFunctionType() const
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
bool doesNotReturn() const
Determine if the call cannot return.
LLVM_ABI bool onlyAccessesArgMemory() const
Determine if the call can access memmory only using pointers based on its arguments.
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
bool hasOperandBundles() const
Return true if this User has any operand bundles.
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
BasicBlock * getIndirectDest(unsigned i) const
unsigned getNumIndirectDests() const
Return the number of callbr indirect dest labels.
bool isMustTailCall() const
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
unsigned getNumHandlers() const
return the number of 'handlers' in this catchswitch instruction, except the default handler
Value * getParentPad() const
BasicBlock * getUnwindDest() const
handler_range handlers()
iteration adapter for range-for loops.
BasicBlock * getUnwindDest() const
bool isFPPredicate() const
Definition InstrTypes.h:845
bool isIntPredicate() const
Definition InstrTypes.h:846
static bool isIntPredicate(Predicate P)
Definition InstrTypes.h:839
Value * getCondition() const
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
Definition Constants.h:231
bool isNegative() const
Definition Constants.h:214
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
Constant * getAddrDiscriminator() const
The address discriminator if any, or the null constant.
Definition Constants.h:1258
Constant * getPointer() const
The pointer that is signed in this ptrauth signed pointer.
Definition Constants.h:1245
ConstantInt * getKey() const
The Key ID, an i32 constant.
Definition Constants.h:1248
Constant * getDeactivationSymbol() const
Definition Constants.h:1267
ConstantInt * getDiscriminator() const
The integer discriminator, an i64 constant, or 0.
Definition Constants.h:1251
static LLVM_ABI bool isOrderedRanges(ArrayRef< ConstantRange > RangesRef)
This class represents a range of values.
const APInt & getLower() const
Return the lower value for this range.
const APInt & getUpper() const
Return the upper value for this range.
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
static LLVM_ABI ConstantTokenNone * get(LLVMContext &Context)
Return the ConstantTokenNone.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:64
LLVM_ABI std::optional< fp::ExceptionBehavior > getExceptionBehavior() const
LLVM_ABI std::optional< RoundingMode > getRoundingMode() const
LLVM_ABI unsigned getNonMetadataArgCount() const
DbgVariableFragmentInfo FragmentInfo
@ FixedPointBinary
Scale factor 2^Factor.
@ FixedPointDecimal
Scale factor 10^Factor.
@ FixedPointRational
Arbitrary rational scale factor.
DIGlobalVariable * getVariable() const
LLVM_ABI DISubprogram * getSubprogram() const
Get the subprogram for this scope.
DILocalScope * getScope() const
Get the local scope for this variable.
Metadata * getRawScope() const
Base class for scope-like contexts.
Subprogram description. Uses SubclassData1.
static LLVM_ABI const DIScope * getRawRetainedNodeScope(const MDNode *N)
Base class for template parameters.
Base class for types.
Base class for variables.
Metadata * getRawType() const
Metadata * getRawScope() const
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Records a position in IR for a source label (DILabel).
Base class for non-instruction debug metadata records that have positions within IR.
LLVM_ABI void print(raw_ostream &O, bool IsForDebug=false) const
DebugLoc getDebugLoc() const
LLVM_ABI const BasicBlock * getParent() const
LLVM_ABI Function * getFunction()
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LLVM_ABI Value * getVariableLocationOp(unsigned OpIdx) const
DIExpression * getExpression() const
DILocalVariable * getVariable() const
Metadata * getRawLocation() const
Returns the metadata operand for the first location description.
@ End
Marks the end of the concrete types.
@ Any
To indicate all LocationTypes in searches.
DIExpression * getAddressExpression() const
LLVM_ABI MDNode * getAsMDNode() const
Return this as a bar MDNode.
Definition DebugLoc.cpp:73
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:252
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:225
bool empty() const
Definition DenseMap.h:173
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:286
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:151
This instruction extracts a single (scalar) element from a VectorType value.
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *Idx)
Return true if an extractelement instruction can be formed with the specified operands.
ArrayRef< unsigned > getIndices() const
static LLVM_ABI Type * getIndexedType(Type *Agg, ArrayRef< unsigned > Idxs)
Returns the type of the element that would be extracted with an extractvalue instruction with the spe...
This instruction compares its operands according to the predicate given to the constructor.
This class represents an extension of floating point types.
static bool isSupportedFloatingPointType(Type *Ty)
Returns true if Ty is a supported floating-point type for phi, select, or call FPMathOperators.
Definition Operator.h:302
This class represents a cast from floating point to signed integer.
This class represents a cast from floating point to unsigned integer.
This class represents a truncation of floating point types.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this fence instruction.
op_range arg_operands()
arg_operands - iteration adapter for range-for loops.
Value * getParentPad() const
Convenience accessors.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
Type * getReturnType() const
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:211
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Definition Function.h:246
DISubprogram * getSubprogram() const
Get the attached subprogram.
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:272
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition Function.h:905
const Function & getFunction() const
Definition Function.h:166
const std::string & getGC() const
Definition Function.cpp:814
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:216
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
Definition Function.h:229
LLVM_ABI Value * getBasePtr() const
LLVM_ABI Value * getDerivedPtr() const
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
static bool isValidLinkage(LinkageTypes L)
Definition GlobalAlias.h:98
const Constant * getAliasee() const
Definition GlobalAlias.h:87
LLVM_ABI const Function * getResolverFunction() const
Definition Globals.cpp:688
static bool isValidLinkage(LinkageTypes L)
Definition GlobalIFunc.h:86
const Constant * getResolver() const
Definition GlobalIFunc.h:73
LLVM_ABI void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
Appends all metadata attached to this value to MDs, sorting by KindID.
bool hasComdat() const
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this GlobalObject.
bool hasExternalLinkage() const
bool isDSOLocal() const
bool isImplicitDSOLocal() const
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:337
bool hasValidDeclarationLinkage() const
LinkageTypes getLinkage() const
bool hasDefaultVisibility() const
bool hasPrivateLinkage() const
bool hasHiddenVisibility() const
bool hasExternalWeakLinkage() const
bool hasDLLImportStorageClass() const
bool hasDLLExportStorageClass() const
bool isDeclarationForLinker() const
unsigned getAddressSpace() const
Module * getParent()
Get the module that this global value is contained inside of...
PointerType * getType() const
Global values are always pointers.
LLVM_ABI bool isInterposable() const
Return true if this global's definition can be substituted with an arbitrary definition at link time ...
Definition Globals.cpp:116
bool hasComdat() const
bool hasCommonLinkage() const
bool hasGlobalUnnamedAddr() const
bool hasAppendingLinkage() const
bool hasAvailableExternallyLinkage() const
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
MaybeAlign getAlign() const
Returns the alignment of the given variable.
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
Definition Globals.cpp:569
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
This instruction compares its operands according to the predicate given to the constructor.
BasicBlock * getDestination(unsigned i)
Return the specified destination.
unsigned getNumDestinations() const
return the number of possible destinations in this indirectbr instruction.
unsigned getNumSuccessors() const
This instruction inserts a single (scalar) element into a VectorType value.
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
ArrayRef< unsigned > getIndices() const
Base class for instruction visitors.
Definition InstVisitor.h:78
void visit(Iterator Start, Iterator End)
Definition InstVisitor.h:87
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI bool isAtomic() const LLVM_READONLY
Return true if this instruction has an AtomicOrdering of unordered or higher.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
This class represents a cast from an integer to a pointer.
static LLVM_ABI bool mayLowerToFunctionCall(Intrinsic::ID IID)
Check if the intrinsic might lower into a regular function call in the course of IR transformations.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
bool isCleanup() const
Return 'true' if this landingpad instruction is a cleanup.
unsigned getNumClauses() const
Get the number of clauses for this landing pad.
bool isCatch(unsigned Idx) const
Return 'true' if the clause and index Idx is a catch clause.
bool isFilter(unsigned Idx) const
Return 'true' if the clause and index Idx is a filter clause.
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this load instruction.
Align getAlign() const
Return the alignment of the access that is being performed.
Metadata node.
Definition Metadata.h:1069
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1433
bool isTemporary() const
Definition Metadata.h:1253
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1431
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1439
bool isDistinct() const
Definition Metadata.h:1252
bool isResolved() const
Check if node is fully resolved.
Definition Metadata.h:1249
LLVMContext & getContext() const
Definition Metadata.h:1233
bool equalsStr(StringRef Str) const
Definition Metadata.h:913
Metadata * get() const
Definition Metadata.h:920
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:632
static LLVM_ABI bool isTagMD(const Metadata *MD)
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
static LLVM_ABI MetadataAsValue * getIfExists(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:118
Metadata * getMetadata() const
Definition Metadata.h:202
Root of the metadata hierarchy.
Definition Metadata.h:64
LLVM_ABI void print(raw_ostream &OS, const Module *M=nullptr, bool IsForDebug=false) const
Print.
unsigned getMetadataID() const
Definition Metadata.h:104
Manage lifetime of a slot tracker for printing IR.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
Definition Module.cpp:358
LLVM_ABI StringRef getName() const
LLVM_ABI void print(raw_ostream &ROS, bool IsForDebug=false) const
LLVM_ABI unsigned getNumOperands() const
iterator_range< op_iterator > operands()
Definition Metadata.h:1845
op_range incoming_values()
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
This class represents a cast from a pointer to an address (non-capturing ptrtoint).
This class represents a cast from a pointer to an integer.
Value * getValue() const
Convenience accessor.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
This class represents a sign extension of integer types.
This class represents a cast from signed integer to floating point.
static LLVM_ABI const char * areInvalidOperands(Value *Cond, Value *True, Value *False)
Return a string if the specified operands are invalid for a select operation, otherwise return null.
This instruction constructs a fixed permutation of two input vectors.
static LLVM_ABI bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
static LLVM_ABI void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void reserve(size_type N)
iterator insert(iterator I, T &&Elt)
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:730
static constexpr size_t npos
Definition StringRef.h:58
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition StringRef.h:490
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
std::pair< typename Base::iterator, bool > insert(StringRef key)
Definition StringSet.h:39
unsigned getNumElements() const
Random access to the elements.
LLVM_ABI Type * getTypeAtIndex(const Value *V) const
Given an index value into the type, return the type of the element.
Definition Type.cpp:784
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Returns true if this struct contains a scalable vector.
Definition Type.cpp:506
Verify that the TBAA Metadatas are valid.
Definition Verifier.h:40
LLVM_ABI bool visitTBAAMetadata(const Instruction *I, const MDNode *MD)
Visit an instruction, or a TBAA node itself as part of a metadata, and return true if it is valid,...
unsigned size() const
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:47
This class represents a truncation of integer types.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isByteTy() const
True if this is an instance of ByteType.
Definition Type.h:242
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
LLVM_ABI bool containsNonGlobalTargetExtType(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this type is or contains a target extension type that disallows being used as a global...
Definition Type.cpp:74
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition Type.h:279
LLVM_ABI bool containsNonLocalTargetExtType(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this type is or contains a target extension type that disallows being used as a local.
Definition Type.cpp:90
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this is a type whose size is a known multiple of vscale.
Definition Type.cpp:61
bool isLabelTy() const
Return true if this is 'label'.
Definition Type.h:230
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:263
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
LLVM_ABI bool isTokenLikeTy() const
Returns true if this is 'token' or a token-like target type.s.
Definition Type.cpp:1140
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
Definition Type.h:311
LLVM_ABI bool canLosslesslyBitCastTo(Type *Ty) const
Return true if this type could be converted with a lossless BitCast to type 'Ty'.
Definition Type.cpp:153
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition Type.h:326
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:285
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:270
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:227
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
bool isMetadataTy() const
Return true if this is 'metadata'.
Definition Type.h:233
This class represents a cast unsigned integer to floating point.
op_range operands()
Definition User.h:267
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
Value * getValue() const
Definition Metadata.h:499
LLVM Value Representation.
Definition Value.h:75
iterator_range< user_iterator > materialized_users()
Definition Value.h:420
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI const Value * stripPointerCastsAndAliases() const
Strip off pointer casts, all-zero GEPs, address space casts, and aliases.
Definition Value.cpp: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
bool empty() const
Definition BasicBlock.h:101
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
@ Offset
Definition DWP.cpp:558
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1738
LLVM_ABI bool canInstructionHaveMMRAs(const Instruction &I)
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
Definition STLExtras.h:840
LLVM_ABI unsigned getBranchWeightOffset(const MDNode *ProfileData)
Return the offset to the first branch weight data.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:165
BundleAttr getBundleAttrFromOBU(OperandBundleUse OBU)
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2553
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
AllocFnKind
Definition Attributes.h:53
testing::Matcher< const detail::ErrorHolder & > Failed()
Definition Error.h:198
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2207
LLVM_ABI DenseMap< BasicBlock *, ColorVector > colorEHFunclets(Function &F)
If an EH funclet personality is in use (see isFuncletEHPersonality), this will recompute which blocks...
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:243
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:284
gep_type_iterator gep_type_end(const User *GEP)
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
Op::Description Desc
bool isScopedEHPersonality(EHPersonality Pers)
Returns true if this personality uses scope-style EH IR instructions: catchswitch,...
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
GenericConvergenceVerifier< SSAContext > ConvergenceVerifier
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:279
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1635
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:380
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:310
VerifierSupport(raw_ostream *OS, const Module &M)
Definition Verifier.cpp:159
bool Broken
Track the brokenness of the module while recursively visiting.
Definition Verifier.cpp:153
void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs)
A check failed (with values to print).
Definition Verifier.cpp:303
bool BrokenDebugInfo
Broken debug info can be "recovered" from by stripping the debug info.
Definition Verifier.cpp:155
LLVMContext & Context
Definition Verifier.cpp:150
bool TreatBrokenDebugInfoAsError
Whether to treat broken debug info as an error.
Definition Verifier.cpp:157
void CheckFailed(const Twine &Message)
A check failed, so printout out the condition and the message.
Definition Verifier.cpp:292
const Module & M
Definition Verifier.cpp:146
const DataLayout & DL
Definition Verifier.cpp:149
void DebugInfoCheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs)
A debug info check failed (with values to print).
Definition Verifier.cpp:319
const Triple & TT
Definition Verifier.cpp:148
ModuleSlotTracker MST
Definition Verifier.cpp:147