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