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