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