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