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