LLVM 17.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// * All other things that are tested by asserts spread about the code...
42//
43//===----------------------------------------------------------------------===//
44
45#include "llvm/IR/Verifier.h"
46#include "llvm/ADT/APFloat.h"
47#include "llvm/ADT/APInt.h"
48#include "llvm/ADT/ArrayRef.h"
49#include "llvm/ADT/DenseMap.h"
50#include "llvm/ADT/MapVector.h"
51#include "llvm/ADT/STLExtras.h"
53#include "llvm/ADT/SmallSet.h"
56#include "llvm/ADT/StringMap.h"
57#include "llvm/ADT/StringRef.h"
58#include "llvm/ADT/Twine.h"
60#include "llvm/IR/Argument.h"
61#include "llvm/IR/Attributes.h"
62#include "llvm/IR/BasicBlock.h"
63#include "llvm/IR/CFG.h"
64#include "llvm/IR/CallingConv.h"
65#include "llvm/IR/Comdat.h"
66#include "llvm/IR/Constant.h"
68#include "llvm/IR/Constants.h"
69#include "llvm/IR/DataLayout.h"
70#include "llvm/IR/DebugInfo.h"
72#include "llvm/IR/DebugLoc.h"
74#include "llvm/IR/Dominators.h"
76#include "llvm/IR/Function.h"
77#include "llvm/IR/GCStrategy.h"
78#include "llvm/IR/GlobalAlias.h"
79#include "llvm/IR/GlobalValue.h"
81#include "llvm/IR/InlineAsm.h"
82#include "llvm/IR/InstVisitor.h"
83#include "llvm/IR/InstrTypes.h"
84#include "llvm/IR/Instruction.h"
87#include "llvm/IR/Intrinsics.h"
88#include "llvm/IR/IntrinsicsAArch64.h"
89#include "llvm/IR/IntrinsicsARM.h"
90#include "llvm/IR/IntrinsicsWebAssembly.h"
91#include "llvm/IR/LLVMContext.h"
92#include "llvm/IR/Metadata.h"
93#include "llvm/IR/Module.h"
95#include "llvm/IR/PassManager.h"
96#include "llvm/IR/Statepoint.h"
97#include "llvm/IR/Type.h"
98#include "llvm/IR/Use.h"
99#include "llvm/IR/User.h"
100#include "llvm/IR/Value.h"
102#include "llvm/Pass.h"
104#include "llvm/Support/Casting.h"
109#include <algorithm>
110#include <cassert>
111#include <cstdint>
112#include <memory>
113#include <optional>
114#include <string>
115#include <utility>
116
117using namespace llvm;
118
120 "verify-noalias-scope-decl-dom", cl::Hidden, cl::init(false),
121 cl::desc("Ensure that llvm.experimental.noalias.scope.decl for identical "
122 "scopes are not dominating"));
123
124namespace llvm {
125
128 const Module &M;
133
134 /// Track the brokenness of the module while recursively visiting.
135 bool Broken = false;
136 /// Broken debug info can be "recovered" from by stripping the debug info.
137 bool BrokenDebugInfo = false;
138 /// Whether to treat broken debug info as an error.
140
142 : OS(OS), M(M), MST(&M), TT(M.getTargetTriple()), DL(M.getDataLayout()),
143 Context(M.getContext()) {}
144
145private:
146 void Write(const Module *M) {
147 *OS << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
148 }
149
150 void Write(const Value *V) {
151 if (V)
152 Write(*V);
153 }
154
155 void Write(const Value &V) {
156 if (isa<Instruction>(V)) {
157 V.print(*OS, MST);
158 *OS << '\n';
159 } else {
160 V.printAsOperand(*OS, true, MST);
161 *OS << '\n';
162 }
163 }
164
165 void Write(const Metadata *MD) {
166 if (!MD)
167 return;
168 MD->print(*OS, MST, &M);
169 *OS << '\n';
170 }
171
172 template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) {
173 Write(MD.get());
174 }
175
176 void Write(const NamedMDNode *NMD) {
177 if (!NMD)
178 return;
179 NMD->print(*OS, MST);
180 *OS << '\n';
181 }
182
183 void Write(Type *T) {
184 if (!T)
185 return;
186 *OS << ' ' << *T;
187 }
188
189 void Write(const Comdat *C) {
190 if (!C)
191 return;
192 *OS << *C;
193 }
194
195 void Write(const APInt *AI) {
196 if (!AI)
197 return;
198 *OS << *AI << '\n';
199 }
200
201 void Write(const unsigned i) { *OS << i << '\n'; }
202
203 // NOLINTNEXTLINE(readability-identifier-naming)
204 void Write(const Attribute *A) {
205 if (!A)
206 return;
207 *OS << A->getAsString() << '\n';
208 }
209
210 // NOLINTNEXTLINE(readability-identifier-naming)
211 void Write(const AttributeSet *AS) {
212 if (!AS)
213 return;
214 *OS << AS->getAsString() << '\n';
215 }
216
217 // NOLINTNEXTLINE(readability-identifier-naming)
218 void Write(const AttributeList *AL) {
219 if (!AL)
220 return;
221 AL->print(*OS);
222 }
223
224 template <typename T> void Write(ArrayRef<T> Vs) {
225 for (const T &V : Vs)
226 Write(V);
227 }
228
229 template <typename T1, typename... Ts>
230 void WriteTs(const T1 &V1, const Ts &... Vs) {
231 Write(V1);
232 WriteTs(Vs...);
233 }
234
235 template <typename... Ts> void WriteTs() {}
236
237public:
238 /// A check failed, so printout out the condition and the message.
239 ///
240 /// This provides a nice place to put a breakpoint if you want to see why
241 /// something is not correct.
242 void CheckFailed(const Twine &Message) {
243 if (OS)
244 *OS << Message << '\n';
245 Broken = true;
246 }
247
248 /// A check failed (with values to print).
249 ///
250 /// This calls the Message-only version so that the above is easier to set a
251 /// breakpoint on.
252 template <typename T1, typename... Ts>
253 void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
254 CheckFailed(Message);
255 if (OS)
256 WriteTs(V1, Vs...);
257 }
258
259 /// A debug info check failed.
260 void DebugInfoCheckFailed(const Twine &Message) {
261 if (OS)
262 *OS << Message << '\n';
264 BrokenDebugInfo = true;
265 }
266
267 /// A debug info check failed (with values to print).
268 template <typename T1, typename... Ts>
269 void DebugInfoCheckFailed(const Twine &Message, const T1 &V1,
270 const Ts &... Vs) {
271 DebugInfoCheckFailed(Message);
272 if (OS)
273 WriteTs(V1, Vs...);
274 }
275};
276
277} // namespace llvm
278
279namespace {
280
281class Verifier : public InstVisitor<Verifier>, VerifierSupport {
282 friend class InstVisitor<Verifier>;
283
284 // ISD::ArgFlagsTy::MemAlign only have 4 bits for alignment, so
285 // the alignment size should not exceed 2^15. Since encode(Align)
286 // would plus the shift value by 1, the alignment size should
287 // not exceed 2^14, otherwise it can NOT be properly lowered
288 // in backend.
289 static constexpr unsigned ParamMaxAlignment = 1 << 14;
290 DominatorTree DT;
291
292 /// When verifying a basic block, keep track of all of the
293 /// instructions we have seen so far.
294 ///
295 /// This allows us to do efficient dominance checks for the case when an
296 /// instruction has an operand that is an instruction in the same block.
297 SmallPtrSet<Instruction *, 16> InstsInThisBlock;
298
299 /// Keep track of the metadata nodes that have been checked already.
301
302 /// Keep track which DISubprogram is attached to which function.
304
305 /// Track all DICompileUnits visited.
307
308 /// The result type for a landingpad.
309 Type *LandingPadResultTy;
310
311 /// Whether we've seen a call to @llvm.localescape in this function
312 /// already.
313 bool SawFrameEscape;
314
315 /// Whether the current function has a DISubprogram attached to it.
316 bool HasDebugInfo = false;
317
318 /// The current source language.
320
321 /// Whether source was present on the first DIFile encountered in each CU.
322 DenseMap<const DICompileUnit *, bool> HasSourceDebugInfo;
323
324 /// Stores the count of how many objects were passed to llvm.localescape for a
325 /// given function and the largest index passed to llvm.localrecover.
327
328 // Maps catchswitches and cleanuppads that unwind to siblings to the
329 // terminators that indicate the unwind, used to detect cycles therein.
331
332 /// Cache which blocks are in which funclet, if an EH funclet personality is
333 /// in use. Otherwise empty.
334 DenseMap<BasicBlock *, ColorVector> BlockEHFuncletColors;
335
336 /// Cache of constants visited in search of ConstantExprs.
337 SmallPtrSet<const Constant *, 32> ConstantExprVisited;
338
339 /// Cache of declarations of the llvm.experimental.deoptimize.<ty> intrinsic.
340 SmallVector<const Function *, 4> DeoptimizeDeclarations;
341
342 /// Cache of attribute lists verified.
343 SmallPtrSet<const void *, 32> AttributeListsVisited;
344
345 // Verify that this GlobalValue is only used in this module.
346 // This map is used to avoid visiting uses twice. We can arrive at a user
347 // twice, if they have multiple operands. In particular for very large
348 // constant expressions, we can arrive at a particular user many times.
349 SmallPtrSet<const Value *, 32> GlobalValueVisited;
350
351 // Keeps track of duplicate function argument debug info.
353
354 TBAAVerifier TBAAVerifyHelper;
355
356 SmallVector<IntrinsicInst *, 4> NoAliasScopeDecls;
357
358 void checkAtomicMemAccessSize(Type *Ty, const Instruction *I);
359
360public:
361 explicit Verifier(raw_ostream *OS, bool ShouldTreatBrokenDebugInfoAsError,
362 const Module &M)
363 : VerifierSupport(OS, M), LandingPadResultTy(nullptr),
364 SawFrameEscape(false), TBAAVerifyHelper(this) {
365 TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
366 }
367
368 bool hasBrokenDebugInfo() const { return BrokenDebugInfo; }
369
370 bool verify(const Function &F) {
371 assert(F.getParent() == &M &&
372 "An instance of this class only works with a specific module!");
373
374 // First ensure the function is well-enough formed to compute dominance
375 // information, and directly compute a dominance tree. We don't rely on the
376 // pass manager to provide this as it isolates us from a potentially
377 // out-of-date dominator tree and makes it significantly more complex to run
378 // this code outside of a pass manager.
379 // FIXME: It's really gross that we have to cast away constness here.
380 if (!F.empty())
381 DT.recalculate(const_cast<Function &>(F));
382
383 for (const BasicBlock &BB : F) {
384 if (!BB.empty() && BB.back().isTerminator())
385 continue;
386
387 if (OS) {
388 *OS << "Basic Block in function '" << F.getName()
389 << "' does not have terminator!\n";
390 BB.printAsOperand(*OS, true, MST);
391 *OS << "\n";
392 }
393 return false;
394 }
395
396 Broken = false;
397 // FIXME: We strip const here because the inst visitor strips const.
398 visit(const_cast<Function &>(F));
399 verifySiblingFuncletUnwinds();
400 InstsInThisBlock.clear();
401 DebugFnArgs.clear();
402 LandingPadResultTy = nullptr;
403 SawFrameEscape = false;
404 SiblingFuncletInfo.clear();
405 verifyNoAliasScopeDecl();
406 NoAliasScopeDecls.clear();
407
408 return !Broken;
409 }
410
411 /// Verify the module that this instance of \c Verifier was initialized with.
412 bool verify() {
413 Broken = false;
414
415 // Collect all declarations of the llvm.experimental.deoptimize intrinsic.
416 for (const Function &F : M)
417 if (F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
418 DeoptimizeDeclarations.push_back(&F);
419
420 // Now that we've visited every function, verify that we never asked to
421 // recover a frame index that wasn't escaped.
422 verifyFrameRecoverIndices();
423 for (const GlobalVariable &GV : M.globals())
424 visitGlobalVariable(GV);
425
426 for (const GlobalAlias &GA : M.aliases())
427 visitGlobalAlias(GA);
428
429 for (const GlobalIFunc &GI : M.ifuncs())
430 visitGlobalIFunc(GI);
431
432 for (const NamedMDNode &NMD : M.named_metadata())
433 visitNamedMDNode(NMD);
434
435 for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
436 visitComdat(SMEC.getValue());
437
438 visitModuleFlags();
439 visitModuleIdents();
440 visitModuleCommandLines();
441
442 verifyCompileUnits();
443
444 verifyDeoptimizeCallingConvs();
445 DISubprogramAttachments.clear();
446 return !Broken;
447 }
448
449private:
450 /// Whether a metadata node is allowed to be, or contain, a DILocation.
451 enum class AreDebugLocsAllowed { No, Yes };
452
453 // Verification methods...
454 void visitGlobalValue(const GlobalValue &GV);
455 void visitGlobalVariable(const GlobalVariable &GV);
456 void visitGlobalAlias(const GlobalAlias &GA);
457 void visitGlobalIFunc(const GlobalIFunc &GI);
458 void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
459 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
460 const GlobalAlias &A, const Constant &C);
461 void visitNamedMDNode(const NamedMDNode &NMD);
462 void visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs);
463 void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
464 void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
465 void visitComdat(const Comdat &C);
466 void visitModuleIdents();
467 void visitModuleCommandLines();
468 void visitModuleFlags();
469 void visitModuleFlag(const MDNode *Op,
471 SmallVectorImpl<const MDNode *> &Requirements);
472 void visitModuleFlagCGProfileEntry(const MDOperand &MDO);
473 void visitFunction(const Function &F);
474 void visitBasicBlock(BasicBlock &BB);
475 void visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty);
476 void visitDereferenceableMetadata(Instruction &I, MDNode *MD);
477 void visitProfMetadata(Instruction &I, MDNode *MD);
478 void visitCallStackMetadata(MDNode *MD);
479 void visitMemProfMetadata(Instruction &I, MDNode *MD);
480 void visitCallsiteMetadata(Instruction &I, MDNode *MD);
481 void visitDIAssignIDMetadata(Instruction &I, MDNode *MD);
482 void visitAnnotationMetadata(MDNode *Annotation);
483 void visitAliasScopeMetadata(const MDNode *MD);
484 void visitAliasScopeListMetadata(const MDNode *MD);
485 void visitAccessGroupMetadata(const MDNode *MD);
486
487 template <class Ty> bool isValidMetadataArray(const MDTuple &N);
488#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
489#include "llvm/IR/Metadata.def"
490 void visitDIScope(const DIScope &N);
491 void visitDIVariable(const DIVariable &N);
492 void visitDILexicalBlockBase(const DILexicalBlockBase &N);
493 void visitDITemplateParameter(const DITemplateParameter &N);
494
495 void visitTemplateParams(const MDNode &N, const Metadata &RawParams);
496
497 // InstVisitor overrides...
499 void visit(Instruction &I);
500
501 void visitTruncInst(TruncInst &I);
502 void visitZExtInst(ZExtInst &I);
503 void visitSExtInst(SExtInst &I);
504 void visitFPTruncInst(FPTruncInst &I);
505 void visitFPExtInst(FPExtInst &I);
506 void visitFPToUIInst(FPToUIInst &I);
507 void visitFPToSIInst(FPToSIInst &I);
508 void visitUIToFPInst(UIToFPInst &I);
509 void visitSIToFPInst(SIToFPInst &I);
510 void visitIntToPtrInst(IntToPtrInst &I);
511 void visitPtrToIntInst(PtrToIntInst &I);
512 void visitBitCastInst(BitCastInst &I);
513 void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
514 void visitPHINode(PHINode &PN);
515 void visitCallBase(CallBase &Call);
516 void visitUnaryOperator(UnaryOperator &U);
517 void visitBinaryOperator(BinaryOperator &B);
518 void visitICmpInst(ICmpInst &IC);
519 void visitFCmpInst(FCmpInst &FC);
520 void visitExtractElementInst(ExtractElementInst &EI);
521 void visitInsertElementInst(InsertElementInst &EI);
522 void visitShuffleVectorInst(ShuffleVectorInst &EI);
523 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
524 void visitCallInst(CallInst &CI);
525 void visitInvokeInst(InvokeInst &II);
526 void visitGetElementPtrInst(GetElementPtrInst &GEP);
527 void visitLoadInst(LoadInst &LI);
528 void visitStoreInst(StoreInst &SI);
529 void verifyDominatesUse(Instruction &I, unsigned i);
530 void visitInstruction(Instruction &I);
531 void visitTerminator(Instruction &I);
532 void visitBranchInst(BranchInst &BI);
533 void visitReturnInst(ReturnInst &RI);
534 void visitSwitchInst(SwitchInst &SI);
535 void visitIndirectBrInst(IndirectBrInst &BI);
536 void visitCallBrInst(CallBrInst &CBI);
537 void visitSelectInst(SelectInst &SI);
538 void visitUserOp1(Instruction &I);
539 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
540 void visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call);
541 void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI);
542 void visitVPIntrinsic(VPIntrinsic &VPI);
543 void visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII);
544 void visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI);
545 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
546 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
547 void visitFenceInst(FenceInst &FI);
548 void visitAllocaInst(AllocaInst &AI);
549 void visitExtractValueInst(ExtractValueInst &EVI);
550 void visitInsertValueInst(InsertValueInst &IVI);
551 void visitEHPadPredecessors(Instruction &I);
552 void visitLandingPadInst(LandingPadInst &LPI);
553 void visitResumeInst(ResumeInst &RI);
554 void visitCatchPadInst(CatchPadInst &CPI);
555 void visitCatchReturnInst(CatchReturnInst &CatchReturn);
556 void visitCleanupPadInst(CleanupPadInst &CPI);
557 void visitFuncletPadInst(FuncletPadInst &FPI);
558 void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
559 void visitCleanupReturnInst(CleanupReturnInst &CRI);
560
561 void verifySwiftErrorCall(CallBase &Call, const Value *SwiftErrorVal);
562 void verifySwiftErrorValue(const Value *SwiftErrorVal);
563 void verifyTailCCMustTailAttrs(const AttrBuilder &Attrs, StringRef Context);
564 void verifyMustTailCall(CallInst &CI);
565 bool verifyAttributeCount(AttributeList Attrs, unsigned Params);
566 void verifyAttributeTypes(AttributeSet Attrs, const Value *V);
567 void verifyParameterAttrs(AttributeSet Attrs, Type *Ty, const Value *V);
568 void checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
569 const Value *V);
570 void verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
571 const Value *V, bool IsIntrinsic, bool IsInlineAsm);
572 void verifyFunctionMetadata(ArrayRef<std::pair<unsigned, MDNode *>> MDs);
573
574 void visitConstantExprsRecursively(const Constant *EntryC);
575 void visitConstantExpr(const ConstantExpr *CE);
576 void verifyInlineAsmCall(const CallBase &Call);
577 void verifyStatepoint(const CallBase &Call);
578 void verifyFrameRecoverIndices();
579 void verifySiblingFuncletUnwinds();
580
581 void verifyFragmentExpression(const DbgVariableIntrinsic &I);
582 template <typename ValueOrMetadata>
583 void verifyFragmentExpression(const DIVariable &V,
585 ValueOrMetadata *Desc);
586 void verifyFnArgs(const DbgVariableIntrinsic &I);
587 void verifyNotEntryValue(const DbgVariableIntrinsic &I);
588
589 /// Module-level debug info verification...
590 void verifyCompileUnits();
591
592 /// Module-level verification that all @llvm.experimental.deoptimize
593 /// declarations share the same calling convention.
594 void verifyDeoptimizeCallingConvs();
595
596 void verifyAttachedCallBundle(const CallBase &Call,
597 const OperandBundleUse &BU);
598
599 /// Verify all-or-nothing property of DIFile source attribute within a CU.
600 void verifySourceDebugInfo(const DICompileUnit &U, const DIFile &F);
601
602 /// Verify the llvm.experimental.noalias.scope.decl declarations
603 void verifyNoAliasScopeDecl();
604};
605
606} // end anonymous namespace
607
608/// We know that cond should be true, if not print an error message.
609#define Check(C, ...) \
610 do { \
611 if (!(C)) { \
612 CheckFailed(__VA_ARGS__); \
613 return; \
614 } \
615 } while (false)
616
617/// We know that a debug info condition should be true, if not print
618/// an error message.
619#define CheckDI(C, ...) \
620 do { \
621 if (!(C)) { \
622 DebugInfoCheckFailed(__VA_ARGS__); \
623 return; \
624 } \
625 } while (false)
626
627void Verifier::visit(Instruction &I) {
628 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
629 Check(I.getOperand(i) != nullptr, "Operand is null", &I);
631}
632
633// Helper to iterate over indirect users. By returning false, the callback can ask to stop traversing further.
634static void forEachUser(const Value *User,
636 llvm::function_ref<bool(const Value *)> Callback) {
637 if (!Visited.insert(User).second)
638 return;
639
642 while (!WorkList.empty()) {
643 const Value *Cur = WorkList.pop_back_val();
644 if (!Visited.insert(Cur).second)
645 continue;
646 if (Callback(Cur))
647 append_range(WorkList, Cur->materialized_users());
648 }
649}
650
651void Verifier::visitGlobalValue(const GlobalValue &GV) {
653 "Global is external, but doesn't have external or weak linkage!", &GV);
654
655 if (const GlobalObject *GO = dyn_cast<GlobalObject>(&GV)) {
656
657 if (MaybeAlign A = GO->getAlign()) {
658 Check(A->value() <= Value::MaximumAlignment,
659 "huge alignment values are unsupported", GO);
660 }
661
662 if (const MDNode *Associated =
663 GO->getMetadata(LLVMContext::MD_associated)) {
664 Check(Associated->getNumOperands() == 1,
665 "associated metadata must have one operand", &GV, Associated);
666 const Metadata *Op = Associated->getOperand(0).get();
667 Check(Op, "associated metadata must have a global value", GO, Associated);
668
669 const auto *VM = dyn_cast_or_null<ValueAsMetadata>(Op);
670 Check(VM, "associated metadata must be ValueAsMetadata", GO, Associated);
671 if (VM) {
672 Check(isa<PointerType>(VM->getValue()->getType()),
673 "associated value must be pointer typed", GV, Associated);
674
675 const Value *Stripped = VM->getValue()->stripPointerCastsAndAliases();
676 Check(isa<GlobalObject>(Stripped) || isa<Constant>(Stripped),
677 "associated metadata must point to a GlobalObject", GO, Stripped);
678 Check(Stripped != GO,
679 "global values should not associate to themselves", GO,
680 Associated);
681 }
682 }
683 }
684 Check(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
685 "Only global variables can have appending linkage!", &GV);
686
687 if (GV.hasAppendingLinkage()) {
688 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
689 Check(GVar && GVar->getValueType()->isArrayTy(),
690 "Only global arrays can have appending linkage!", GVar);
691 }
692
693 if (GV.isDeclarationForLinker())
694 Check(!GV.hasComdat(), "Declaration may not be in a Comdat!", &GV);
695
696 if (GV.hasDLLExportStorageClass()) {
698 "dllexport GlobalValue must have default or protected visibility",
699 &GV);
700 }
701 if (GV.hasDLLImportStorageClass()) {
703 "dllimport GlobalValue must have default visibility", &GV);
704 Check(!GV.isDSOLocal(), "GlobalValue with DLLImport Storage is dso_local!",
705 &GV);
706
707 Check((GV.isDeclaration() &&
710 "Global is marked as dllimport, but not external", &GV);
711 }
712
713 if (GV.isImplicitDSOLocal())
714 Check(GV.isDSOLocal(),
715 "GlobalValue with local linkage or non-default "
716 "visibility must be dso_local!",
717 &GV);
718
719 forEachUser(&GV, GlobalValueVisited, [&](const Value *V) -> bool {
720 if (const Instruction *I = dyn_cast<Instruction>(V)) {
721 if (!I->getParent() || !I->getParent()->getParent())
722 CheckFailed("Global is referenced by parentless instruction!", &GV, &M,
723 I);
724 else if (I->getParent()->getParent()->getParent() != &M)
725 CheckFailed("Global is referenced in a different module!", &GV, &M, I,
726 I->getParent()->getParent(),
727 I->getParent()->getParent()->getParent());
728 return false;
729 } else if (const Function *F = dyn_cast<Function>(V)) {
730 if (F->getParent() != &M)
731 CheckFailed("Global is used by function in a different module", &GV, &M,
732 F, F->getParent());
733 return false;
734 }
735 return true;
736 });
737}
738
739void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
740 if (GV.hasInitializer()) {
742 "Global variable initializer type does not match global "
743 "variable type!",
744 &GV);
745 // If the global has common linkage, it must have a zero initializer and
746 // cannot be constant.
747 if (GV.hasCommonLinkage()) {
749 "'common' global must have a zero initializer!", &GV);
750 Check(!GV.isConstant(), "'common' global may not be marked constant!",
751 &GV);
752 Check(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
753 }
754 }
755
756 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
757 GV.getName() == "llvm.global_dtors")) {
759 "invalid linkage for intrinsic global variable", &GV);
761 "invalid uses of intrinsic global variable", &GV);
762
763 // Don't worry about emitting an error for it not being an array,
764 // visitGlobalValue will complain on appending non-array.
765 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getValueType())) {
766 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
767 PointerType *FuncPtrTy =
768 FunctionType::get(Type::getVoidTy(Context), false)->
769 getPointerTo(DL.getProgramAddressSpace());
770 Check(STy && (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
771 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
772 STy->getTypeAtIndex(1) == FuncPtrTy,
773 "wrong type for intrinsic global variable", &GV);
774 Check(STy->getNumElements() == 3,
775 "the third field of the element type is mandatory, "
776 "specify ptr null to migrate from the obsoleted 2-field form");
777 Type *ETy = STy->getTypeAtIndex(2);
778 Type *Int8Ty = Type::getInt8Ty(ETy->getContext());
779 Check(ETy->isPointerTy() &&
780 cast<PointerType>(ETy)->isOpaqueOrPointeeTypeMatches(Int8Ty),
781 "wrong type for intrinsic global variable", &GV);
782 }
783 }
784
785 if (GV.hasName() && (GV.getName() == "llvm.used" ||
786 GV.getName() == "llvm.compiler.used")) {
788 "invalid linkage for intrinsic global variable", &GV);
790 "invalid uses of intrinsic global variable", &GV);
791
792 Type *GVType = GV.getValueType();
793 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
794 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
795 Check(PTy, "wrong type for intrinsic global variable", &GV);
796 if (GV.hasInitializer()) {
797 const Constant *Init = GV.getInitializer();
798 const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
799 Check(InitArray, "wrong initalizer for intrinsic global variable",
800 Init);
801 for (Value *Op : InitArray->operands()) {
802 Value *V = Op->stripPointerCasts();
803 Check(isa<GlobalVariable>(V) || isa<Function>(V) ||
804 isa<GlobalAlias>(V),
805 Twine("invalid ") + GV.getName() + " member", V);
806 Check(V->hasName(),
807 Twine("members of ") + GV.getName() + " must be named", V);
808 }
809 }
810 }
811 }
812
813 // Visit any debug info attachments.
815 GV.getMetadata(LLVMContext::MD_dbg, MDs);
816 for (auto *MD : MDs) {
817 if (auto *GVE = dyn_cast<DIGlobalVariableExpression>(MD))
818 visitDIGlobalVariableExpression(*GVE);
819 else
820 CheckDI(false, "!dbg attachment of global variable must be a "
821 "DIGlobalVariableExpression");
822 }
823
824 // Scalable vectors cannot be global variables, since we don't know
825 // the runtime size. If the global is an array containing scalable vectors,
826 // that will be caught by the isValidElementType methods in StructType or
827 // ArrayType instead.
828 Check(!isa<ScalableVectorType>(GV.getValueType()),
829 "Globals cannot contain scalable vectors", &GV);
830
831 if (auto *STy = dyn_cast<StructType>(GV.getValueType()))
833 "Globals cannot contain scalable vectors", &GV);
834
835 // Check if it's a target extension type that disallows being used as a
836 // global.
837 if (auto *TTy = dyn_cast<TargetExtType>(GV.getValueType()))
838 Check(TTy->hasProperty(TargetExtType::CanBeGlobal),
839 "Global @" + GV.getName() + " has illegal target extension type",
840 TTy);
841
842 if (!GV.hasInitializer()) {
843 visitGlobalValue(GV);
844 return;
845 }
846
847 // Walk any aggregate initializers looking for bitcasts between address spaces
848 visitConstantExprsRecursively(GV.getInitializer());
849
850 visitGlobalValue(GV);
851}
852
853void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
855 Visited.insert(&GA);
856 visitAliaseeSubExpr(Visited, GA, C);
857}
858
859void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
860 const GlobalAlias &GA, const Constant &C) {
862 Check(isa<GlobalValue>(C) &&
863 cast<GlobalValue>(C).hasAvailableExternallyLinkage(),
864 "available_externally alias must point to available_externally "
865 "global value",
866 &GA);
867 }
868 if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
870 Check(!GV->isDeclarationForLinker(), "Alias must point to a definition",
871 &GA);
872 }
873
874 if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
875 Check(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
876
877 Check(!GA2->isInterposable(),
878 "Alias cannot point to an interposable alias", &GA);
879 } else {
880 // Only continue verifying subexpressions of GlobalAliases.
881 // Do not recurse into global initializers.
882 return;
883 }
884 }
885
886 if (const auto *CE = dyn_cast<ConstantExpr>(&C))
887 visitConstantExprsRecursively(CE);
888
889 for (const Use &U : C.operands()) {
890 Value *V = &*U;
891 if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
892 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
893 else if (const auto *C2 = dyn_cast<Constant>(V))
894 visitAliaseeSubExpr(Visited, GA, *C2);
895 }
896}
897
898void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
900 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
901 "weak_odr, external, or available_externally linkage!",
902 &GA);
903 const Constant *Aliasee = GA.getAliasee();
904 Check(Aliasee, "Aliasee cannot be NULL!", &GA);
905 Check(GA.getType() == Aliasee->getType(),
906 "Alias and aliasee types should match!", &GA);
907
908 Check(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
909 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
910
911 visitAliaseeSubExpr(GA, *Aliasee);
912
913 visitGlobalValue(GA);
914}
915
916void Verifier::visitGlobalIFunc(const GlobalIFunc &GI) {
918 "IFunc should have private, internal, linkonce, weak, linkonce_odr, "
919 "weak_odr, or external linkage!",
920 &GI);
921 // Pierce through ConstantExprs and GlobalAliases and check that the resolver
922 // is a Function definition.
924 Check(Resolver, "IFunc must have a Function resolver", &GI);
925 Check(!Resolver->isDeclarationForLinker(),
926 "IFunc resolver must be a definition", &GI);
927
928 // Check that the immediate resolver operand (prior to any bitcasts) has the
929 // correct type.
930 const Type *ResolverTy = GI.getResolver()->getType();
931
932 Check(isa<PointerType>(Resolver->getFunctionType()->getReturnType()),
933 "IFunc resolver must return a pointer", &GI);
934
935 const Type *ResolverFuncTy =
937 Check(ResolverTy == ResolverFuncTy->getPointerTo(GI.getAddressSpace()),
938 "IFunc resolver has incorrect type", &GI);
939}
940
941void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
942 // There used to be various other llvm.dbg.* nodes, but we don't support
943 // upgrading them and we want to reserve the namespace for future uses.
944 if (NMD.getName().startswith("llvm.dbg."))
945 CheckDI(NMD.getName() == "llvm.dbg.cu",
946 "unrecognized named metadata node in the llvm.dbg namespace", &NMD);
947 for (const MDNode *MD : NMD.operands()) {
948 if (NMD.getName() == "llvm.dbg.cu")
949 CheckDI(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD);
950
951 if (!MD)
952 continue;
953
954 visitMDNode(*MD, AreDebugLocsAllowed::Yes);
955 }
956}
957
958void Verifier::visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs) {
959 // Only visit each node once. Metadata can be mutually recursive, so this
960 // avoids infinite recursion here, as well as being an optimization.
961 if (!MDNodes.insert(&MD).second)
962 return;
963
964 Check(&MD.getContext() == &Context,
965 "MDNode context does not match Module context!", &MD);
966
967 switch (MD.getMetadataID()) {
968 default:
969 llvm_unreachable("Invalid MDNode subclass");
970 case Metadata::MDTupleKind:
971 break;
972#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
973 case Metadata::CLASS##Kind: \
974 visit##CLASS(cast<CLASS>(MD)); \
975 break;
976#include "llvm/IR/Metadata.def"
977 }
978
979 for (const Metadata *Op : MD.operands()) {
980 if (!Op)
981 continue;
982 Check(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
983 &MD, Op);
984 CheckDI(!isa<DILocation>(Op) || AllowLocs == AreDebugLocsAllowed::Yes,
985 "DILocation not allowed within this metadata node", &MD, Op);
986 if (auto *N = dyn_cast<MDNode>(Op)) {
987 visitMDNode(*N, AllowLocs);
988 continue;
989 }
990 if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
991 visitValueAsMetadata(*V, nullptr);
992 continue;
993 }
994 }
995
996 // Check these last, so we diagnose problems in operands first.
997 Check(!MD.isTemporary(), "Expected no forward declarations!", &MD);
998 Check(MD.isResolved(), "All nodes should be resolved!", &MD);
999}
1000
1001void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
1002 Check(MD.getValue(), "Expected valid value", &MD);
1003 Check(!MD.getValue()->getType()->isMetadataTy(),
1004 "Unexpected metadata round-trip through values", &MD, MD.getValue());
1005
1006 auto *L = dyn_cast<LocalAsMetadata>(&MD);
1007 if (!L)
1008 return;
1009
1010 Check(F, "function-local metadata used outside a function", L);
1011
1012 // If this was an instruction, bb, or argument, verify that it is in the
1013 // function that we expect.
1014 Function *ActualF = nullptr;
1015 if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
1016 Check(I->getParent(), "function-local metadata not in basic block", L, I);
1017 ActualF = I->getParent()->getParent();
1018 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
1019 ActualF = BB->getParent();
1020 else if (Argument *A = dyn_cast<Argument>(L->getValue()))
1021 ActualF = A->getParent();
1022 assert(ActualF && "Unimplemented function local metadata case!");
1023
1024 Check(ActualF == F, "function-local metadata used in wrong function", L);
1025}
1026
1027void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
1028 Metadata *MD = MDV.getMetadata();
1029 if (auto *N = dyn_cast<MDNode>(MD)) {
1030 visitMDNode(*N, AreDebugLocsAllowed::No);
1031 return;
1032 }
1033
1034 // Only visit each node once. Metadata can be mutually recursive, so this
1035 // avoids infinite recursion here, as well as being an optimization.
1036 if (!MDNodes.insert(MD).second)
1037 return;
1038
1039 if (auto *V = dyn_cast<ValueAsMetadata>(MD))
1040 visitValueAsMetadata(*V, F);
1041}
1042
1043static bool isType(const Metadata *MD) { return !MD || isa<DIType>(MD); }
1044static bool isScope(const Metadata *MD) { return !MD || isa<DIScope>(MD); }
1045static bool isDINode(const Metadata *MD) { return !MD || isa<DINode>(MD); }
1046
1047void Verifier::visitDILocation(const DILocation &N) {
1048 CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1049 "location requires a valid scope", &N, N.getRawScope());
1050 if (auto *IA = N.getRawInlinedAt())
1051 CheckDI(isa<DILocation>(IA), "inlined-at should be a location", &N, IA);
1052 if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
1053 CheckDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
1054}
1055
1056void Verifier::visitGenericDINode(const GenericDINode &N) {
1057 CheckDI(N.getTag(), "invalid tag", &N);
1058}
1059
1060void Verifier::visitDIScope(const DIScope &N) {
1061 if (auto *F = N.getRawFile())
1062 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1063}
1064
1065void Verifier::visitDISubrange(const DISubrange &N) {
1066 CheckDI(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
1067 bool HasAssumedSizedArraySupport = dwarf::isFortran(CurrentSourceLang);
1068 CheckDI(HasAssumedSizedArraySupport || N.getRawCountNode() ||
1069 N.getRawUpperBound(),
1070 "Subrange must contain count or upperBound", &N);
1071 CheckDI(!N.getRawCountNode() || !N.getRawUpperBound(),
1072 "Subrange can have any one of count or upperBound", &N);
1073 auto *CBound = N.getRawCountNode();
1074 CheckDI(!CBound || isa<ConstantAsMetadata>(CBound) ||
1075 isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
1076 "Count must be signed constant or DIVariable or DIExpression", &N);
1077 auto Count = N.getCount();
1078 CheckDI(!Count || !Count.is<ConstantInt *>() ||
1079 Count.get<ConstantInt *>()->getSExtValue() >= -1,
1080 "invalid subrange count", &N);
1081 auto *LBound = N.getRawLowerBound();
1082 CheckDI(!LBound || isa<ConstantAsMetadata>(LBound) ||
1083 isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
1084 "LowerBound must be signed constant or DIVariable or DIExpression",
1085 &N);
1086 auto *UBound = N.getRawUpperBound();
1087 CheckDI(!UBound || isa<ConstantAsMetadata>(UBound) ||
1088 isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
1089 "UpperBound must be signed constant or DIVariable or DIExpression",
1090 &N);
1091 auto *Stride = N.getRawStride();
1092 CheckDI(!Stride || isa<ConstantAsMetadata>(Stride) ||
1093 isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
1094 "Stride must be signed constant or DIVariable or DIExpression", &N);
1095}
1096
1097void Verifier::visitDIGenericSubrange(const DIGenericSubrange &N) {
1098 CheckDI(N.getTag() == dwarf::DW_TAG_generic_subrange, "invalid tag", &N);
1099 CheckDI(N.getRawCountNode() || N.getRawUpperBound(),
1100 "GenericSubrange must contain count or upperBound", &N);
1101 CheckDI(!N.getRawCountNode() || !N.getRawUpperBound(),
1102 "GenericSubrange can have any one of count or upperBound", &N);
1103 auto *CBound = N.getRawCountNode();
1104 CheckDI(!CBound || isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
1105 "Count must be signed constant or DIVariable or DIExpression", &N);
1106 auto *LBound = N.getRawLowerBound();
1107 CheckDI(LBound, "GenericSubrange must contain lowerBound", &N);
1108 CheckDI(isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
1109 "LowerBound must be signed constant or DIVariable or DIExpression",
1110 &N);
1111 auto *UBound = N.getRawUpperBound();
1112 CheckDI(!UBound || isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
1113 "UpperBound must be signed constant or DIVariable or DIExpression",
1114 &N);
1115 auto *Stride = N.getRawStride();
1116 CheckDI(Stride, "GenericSubrange must contain stride", &N);
1117 CheckDI(isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
1118 "Stride must be signed constant or DIVariable or DIExpression", &N);
1119}
1120
1121void Verifier::visitDIEnumerator(const DIEnumerator &N) {
1122 CheckDI(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
1123}
1124
1125void Verifier::visitDIBasicType(const DIBasicType &N) {
1126 CheckDI(N.getTag() == dwarf::DW_TAG_base_type ||
1127 N.getTag() == dwarf::DW_TAG_unspecified_type ||
1128 N.getTag() == dwarf::DW_TAG_string_type,
1129 "invalid tag", &N);
1130}
1131
1132void Verifier::visitDIStringType(const DIStringType &N) {
1133 CheckDI(N.getTag() == dwarf::DW_TAG_string_type, "invalid tag", &N);
1134 CheckDI(!(N.isBigEndian() && N.isLittleEndian()), "has conflicting flags",
1135 &N);
1136}
1137
1138void Verifier::visitDIDerivedType(const DIDerivedType &N) {
1139 // Common scope checks.
1140 visitDIScope(N);
1141
1142 CheckDI(N.getTag() == dwarf::DW_TAG_typedef ||
1143 N.getTag() == dwarf::DW_TAG_pointer_type ||
1144 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
1145 N.getTag() == dwarf::DW_TAG_reference_type ||
1146 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
1147 N.getTag() == dwarf::DW_TAG_const_type ||
1148 N.getTag() == dwarf::DW_TAG_immutable_type ||
1149 N.getTag() == dwarf::DW_TAG_volatile_type ||
1150 N.getTag() == dwarf::DW_TAG_restrict_type ||
1151 N.getTag() == dwarf::DW_TAG_atomic_type ||
1152 N.getTag() == dwarf::DW_TAG_member ||
1153 N.getTag() == dwarf::DW_TAG_inheritance ||
1154 N.getTag() == dwarf::DW_TAG_friend ||
1155 N.getTag() == dwarf::DW_TAG_set_type,
1156 "invalid tag", &N);
1157 if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
1158 CheckDI(isType(N.getRawExtraData()), "invalid pointer to member type", &N,
1159 N.getRawExtraData());
1160 }
1161
1162 if (N.getTag() == dwarf::DW_TAG_set_type) {
1163 if (auto *T = N.getRawBaseType()) {
1164 auto *Enum = dyn_cast_or_null<DICompositeType>(T);
1165 auto *Basic = dyn_cast_or_null<DIBasicType>(T);
1166 CheckDI(
1167 (Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type) ||
1168 (Basic && (Basic->getEncoding() == dwarf::DW_ATE_unsigned ||
1169 Basic->getEncoding() == dwarf::DW_ATE_signed ||
1170 Basic->getEncoding() == dwarf::DW_ATE_unsigned_char ||
1171 Basic->getEncoding() == dwarf::DW_ATE_signed_char ||
1172 Basic->getEncoding() == dwarf::DW_ATE_boolean)),
1173 "invalid set base type", &N, T);
1174 }
1175 }
1176
1177 CheckDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
1178 CheckDI(isType(N.getRawBaseType()), "invalid base type", &N,
1179 N.getRawBaseType());
1180
1181 if (N.getDWARFAddressSpace()) {
1182 CheckDI(N.getTag() == dwarf::DW_TAG_pointer_type ||
1183 N.getTag() == dwarf::DW_TAG_reference_type ||
1184 N.getTag() == dwarf::DW_TAG_rvalue_reference_type,
1185 "DWARF address space only applies to pointer or reference types",
1186 &N);
1187 }
1188}
1189
1190/// Detect mutually exclusive flags.
1191static bool hasConflictingReferenceFlags(unsigned Flags) {
1192 return ((Flags & DINode::FlagLValueReference) &&
1193 (Flags & DINode::FlagRValueReference)) ||
1194 ((Flags & DINode::FlagTypePassByValue) &&
1195 (Flags & DINode::FlagTypePassByReference));
1196}
1197
1198void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) {
1199 auto *Params = dyn_cast<MDTuple>(&RawParams);
1200 CheckDI(Params, "invalid template params", &N, &RawParams);
1201 for (Metadata *Op : Params->operands()) {
1202 CheckDI(Op && isa<DITemplateParameter>(Op), "invalid template parameter",
1203 &N, Params, Op);
1204 }
1205}
1206
1207void Verifier::visitDICompositeType(const DICompositeType &N) {
1208 // Common scope checks.
1209 visitDIScope(N);
1210
1211 CheckDI(N.getTag() == dwarf::DW_TAG_array_type ||
1212 N.getTag() == dwarf::DW_TAG_structure_type ||
1213 N.getTag() == dwarf::DW_TAG_union_type ||
1214 N.getTag() == dwarf::DW_TAG_enumeration_type ||
1215 N.getTag() == dwarf::DW_TAG_class_type ||
1216 N.getTag() == dwarf::DW_TAG_variant_part ||
1217 N.getTag() == dwarf::DW_TAG_namelist,
1218 "invalid tag", &N);
1219
1220 CheckDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
1221 CheckDI(isType(N.getRawBaseType()), "invalid base type", &N,
1222 N.getRawBaseType());
1223
1224 CheckDI(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
1225 "invalid composite elements", &N, N.getRawElements());
1226 CheckDI(isType(N.getRawVTableHolder()), "invalid vtable holder", &N,
1227 N.getRawVTableHolder());
1229 "invalid reference flags", &N);
1230 unsigned DIBlockByRefStruct = 1 << 4;
1231 CheckDI((N.getFlags() & DIBlockByRefStruct) == 0,
1232 "DIBlockByRefStruct on DICompositeType is no longer supported", &N);
1233
1234 if (N.isVector()) {
1235 const DINodeArray Elements = N.getElements();
1236 CheckDI(Elements.size() == 1 &&
1237 Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
1238 "invalid vector, expected one element of type subrange", &N);
1239 }
1240
1241 if (auto *Params = N.getRawTemplateParams())
1242 visitTemplateParams(N, *Params);
1243
1244 if (auto *D = N.getRawDiscriminator()) {
1245 CheckDI(isa<DIDerivedType>(D) && N.getTag() == dwarf::DW_TAG_variant_part,
1246 "discriminator can only appear on variant part");
1247 }
1248
1249 if (N.getRawDataLocation()) {
1250 CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1251 "dataLocation can only appear in array type");
1252 }
1253
1254 if (N.getRawAssociated()) {
1255 CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1256 "associated can only appear in array type");
1257 }
1258
1259 if (N.getRawAllocated()) {
1260 CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1261 "allocated can only appear in array type");
1262 }
1263
1264 if (N.getRawRank()) {
1265 CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1266 "rank can only appear in array type");
1267 }
1268}
1269
1270void Verifier::visitDISubroutineType(const DISubroutineType &N) {
1271 CheckDI(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
1272 if (auto *Types = N.getRawTypeArray()) {
1273 CheckDI(isa<MDTuple>(Types), "invalid composite elements", &N, Types);
1274 for (Metadata *Ty : N.getTypeArray()->operands()) {
1275 CheckDI(isType(Ty), "invalid subroutine type ref", &N, Types, Ty);
1276 }
1277 }
1279 "invalid reference flags", &N);
1280}
1281
1282void Verifier::visitDIFile(const DIFile &N) {
1283 CheckDI(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
1284 std::optional<DIFile::ChecksumInfo<StringRef>> Checksum = N.getChecksum();
1285 if (Checksum) {
1286 CheckDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last,
1287 "invalid checksum kind", &N);
1288 size_t Size;
1289 switch (Checksum->Kind) {
1290 case DIFile::CSK_MD5:
1291 Size = 32;
1292 break;
1293 case DIFile::CSK_SHA1:
1294 Size = 40;
1295 break;
1296 case DIFile::CSK_SHA256:
1297 Size = 64;
1298 break;
1299 }
1300 CheckDI(Checksum->Value.size() == Size, "invalid checksum length", &N);
1301 CheckDI(Checksum->Value.find_if_not(llvm::isHexDigit) == StringRef::npos,
1302 "invalid checksum", &N);
1303 }
1304}
1305
1306void Verifier::visitDICompileUnit(const DICompileUnit &N) {
1307 CheckDI(N.isDistinct(), "compile units must be distinct", &N);
1308 CheckDI(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
1309
1310 // Don't bother verifying the compilation directory or producer string
1311 // as those could be empty.
1312 CheckDI(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N,
1313 N.getRawFile());
1314 CheckDI(!N.getFile()->getFilename().empty(), "invalid filename", &N,
1315 N.getFile());
1316
1317 CurrentSourceLang = (dwarf::SourceLanguage)N.getSourceLanguage();
1318
1319 verifySourceDebugInfo(N, *N.getFile());
1320
1321 CheckDI((N.getEmissionKind() <= DICompileUnit::LastEmissionKind),
1322 "invalid emission kind", &N);
1323
1324 if (auto *Array = N.getRawEnumTypes()) {
1325 CheckDI(isa<MDTuple>(Array), "invalid enum list", &N, Array);
1326 for (Metadata *Op : N.getEnumTypes()->operands()) {
1327 auto *Enum = dyn_cast_or_null<DICompositeType>(Op);
1328 CheckDI(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
1329 "invalid enum type", &N, N.getEnumTypes(), Op);
1330 }
1331 }
1332 if (auto *Array = N.getRawRetainedTypes()) {
1333 CheckDI(isa<MDTuple>(Array), "invalid retained type list", &N, Array);
1334 for (Metadata *Op : N.getRetainedTypes()->operands()) {
1335 CheckDI(
1336 Op && (isa<DIType>(Op) || (isa<DISubprogram>(Op) &&
1337 !cast<DISubprogram>(Op)->isDefinition())),
1338 "invalid retained type", &N, Op);
1339 }
1340 }
1341 if (auto *Array = N.getRawGlobalVariables()) {
1342 CheckDI(isa<MDTuple>(Array), "invalid global variable list", &N, Array);
1343 for (Metadata *Op : N.getGlobalVariables()->operands()) {
1344 CheckDI(Op && (isa<DIGlobalVariableExpression>(Op)),
1345 "invalid global variable ref", &N, Op);
1346 }
1347 }
1348 if (auto *Array = N.getRawImportedEntities()) {
1349 CheckDI(isa<MDTuple>(Array), "invalid imported entity list", &N, Array);
1350 for (Metadata *Op : N.getImportedEntities()->operands()) {
1351 CheckDI(Op && isa<DIImportedEntity>(Op), "invalid imported entity ref",
1352 &N, Op);
1353 }
1354 }
1355 if (auto *Array = N.getRawMacros()) {
1356 CheckDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
1357 for (Metadata *Op : N.getMacros()->operands()) {
1358 CheckDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
1359 }
1360 }
1361 CUVisited.insert(&N);
1362}
1363
1364void Verifier::visitDISubprogram(const DISubprogram &N) {
1365 CheckDI(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
1366 CheckDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
1367 if (auto *F = N.getRawFile())
1368 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1369 else
1370 CheckDI(N.getLine() == 0, "line specified with no file", &N, N.getLine());
1371 if (auto *T = N.getRawType())
1372 CheckDI(isa<DISubroutineType>(T), "invalid subroutine type", &N, T);
1373 CheckDI(isType(N.getRawContainingType()), "invalid containing type", &N,
1374 N.getRawContainingType());
1375 if (auto *Params = N.getRawTemplateParams())
1376 visitTemplateParams(N, *Params);
1377 if (auto *S = N.getRawDeclaration())
1378 CheckDI(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(),
1379 "invalid subprogram declaration", &N, S);
1380 if (auto *RawNode = N.getRawRetainedNodes()) {
1381 auto *Node = dyn_cast<MDTuple>(RawNode);
1382 CheckDI(Node, "invalid retained nodes list", &N, RawNode);
1383 for (Metadata *Op : Node->operands()) {
1384 CheckDI(Op && (isa<DILocalVariable>(Op) || isa<DILabel>(Op)),
1385 "invalid retained nodes, expected DILocalVariable or DILabel", &N,
1386 Node, Op);
1387 }
1388 }
1390 "invalid reference flags", &N);
1391
1392 auto *Unit = N.getRawUnit();
1393 if (N.isDefinition()) {
1394 // Subprogram definitions (not part of the type hierarchy).
1395 CheckDI(N.isDistinct(), "subprogram definitions must be distinct", &N);
1396 CheckDI(Unit, "subprogram definitions must have a compile unit", &N);
1397 CheckDI(isa<DICompileUnit>(Unit), "invalid unit type", &N, Unit);
1398 if (N.getFile())
1399 verifySourceDebugInfo(*N.getUnit(), *N.getFile());
1400 } else {
1401 // Subprogram declarations (part of the type hierarchy).
1402 CheckDI(!Unit, "subprogram declarations must not have a compile unit", &N);
1403 CheckDI(!N.getRawDeclaration(),
1404 "subprogram declaration must not have a declaration field");
1405 }
1406
1407 if (auto *RawThrownTypes = N.getRawThrownTypes()) {
1408 auto *ThrownTypes = dyn_cast<MDTuple>(RawThrownTypes);
1409 CheckDI(ThrownTypes, "invalid thrown types list", &N, RawThrownTypes);
1410 for (Metadata *Op : ThrownTypes->operands())
1411 CheckDI(Op && isa<DIType>(Op), "invalid thrown type", &N, ThrownTypes,
1412 Op);
1413 }
1414
1415 if (N.areAllCallsDescribed())
1416 CheckDI(N.isDefinition(),
1417 "DIFlagAllCallsDescribed must be attached to a definition");
1418}
1419
1420void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) {
1421 CheckDI(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
1422 CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1423 "invalid local scope", &N, N.getRawScope());
1424 if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
1425 CheckDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
1426}
1427
1428void Verifier::visitDILexicalBlock(const DILexicalBlock &N) {
1429 visitDILexicalBlockBase(N);
1430
1431 CheckDI(N.getLine() || !N.getColumn(),
1432 "cannot have column info without line info", &N);
1433}
1434
1435void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) {
1436 visitDILexicalBlockBase(N);
1437}
1438
1439void Verifier::visitDICommonBlock(const DICommonBlock &N) {
1440 CheckDI(N.getTag() == dwarf::DW_TAG_common_block, "invalid tag", &N);
1441 if (auto *S = N.getRawScope())
1442 CheckDI(isa<DIScope>(S), "invalid scope ref", &N, S);
1443 if (auto *S = N.getRawDecl())
1444 CheckDI(isa<DIGlobalVariable>(S), "invalid declaration", &N, S);
1445}
1446
1447void Verifier::visitDINamespace(const DINamespace &N) {
1448 CheckDI(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
1449 if (auto *S = N.getRawScope())
1450 CheckDI(isa<DIScope>(S), "invalid scope ref", &N, S);
1451}
1452
1453void Verifier::visitDIMacro(const DIMacro &N) {
1454 CheckDI(N.getMacinfoType() == dwarf::DW_MACINFO_define ||
1455 N.getMacinfoType() == dwarf::DW_MACINFO_undef,
1456 "invalid macinfo type", &N);
1457 CheckDI(!N.getName().empty(), "anonymous macro", &N);
1458 if (!N.getValue().empty()) {
1459 assert(N.getValue().data()[0] != ' ' && "Macro value has a space prefix");
1460 }
1461}
1462
1463void Verifier::visitDIMacroFile(const DIMacroFile &N) {
1464 CheckDI(N.getMacinfoType() == dwarf::DW_MACINFO_start_file,
1465 "invalid macinfo type", &N);
1466 if (auto *F = N.getRawFile())
1467 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1468
1469 if (auto *Array = N.getRawElements()) {
1470 CheckDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
1471 for (Metadata *Op : N.getElements()->operands()) {
1472 CheckDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
1473 }
1474 }
1475}
1476
1477void Verifier::visitDIArgList(const DIArgList &N) {
1478 CheckDI(!N.getNumOperands(),
1479 "DIArgList should have no operands other than a list of "
1480 "ValueAsMetadata",
1481 &N);
1482}
1483
1484void Verifier::visitDIModule(const DIModule &N) {
1485 CheckDI(N.getTag() == dwarf::DW_TAG_module, "invalid tag", &N);
1486 CheckDI(!N.getName().empty(), "anonymous module", &N);
1487}
1488
1489void Verifier::visitDITemplateParameter(const DITemplateParameter &N) {
1490 CheckDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
1491}
1492
1493void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) {
1494 visitDITemplateParameter(N);
1495
1496 CheckDI(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
1497 &N);
1498}
1499
1500void Verifier::visitDITemplateValueParameter(
1501 const DITemplateValueParameter &N) {
1502 visitDITemplateParameter(N);
1503
1504 CheckDI(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1505 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1506 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1507 "invalid tag", &N);
1508}
1509
1510void Verifier::visitDIVariable(const DIVariable &N) {
1511 if (auto *S = N.getRawScope())
1512 CheckDI(isa<DIScope>(S), "invalid scope", &N, S);
1513 if (auto *F = N.getRawFile())
1514 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1515}
1516
1517void Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) {
1518 // Checks common to all variables.
1519 visitDIVariable(N);
1520
1521 CheckDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1522 CheckDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
1523 // Check only if the global variable is not an extern
1524 if (N.isDefinition())
1525 CheckDI(N.getType(), "missing global variable type", &N);
1526 if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
1527 CheckDI(isa<DIDerivedType>(Member),
1528 "invalid static data member declaration", &N, Member);
1529 }
1530}
1531
1532void Verifier::visitDILocalVariable(const DILocalVariable &N) {
1533 // Checks common to all variables.
1534 visitDIVariable(N);
1535
1536 CheckDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
1537 CheckDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1538 CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1539 "local variable requires a valid scope", &N, N.getRawScope());
1540 if (auto Ty = N.getType())
1541 CheckDI(!isa<DISubroutineType>(Ty), "invalid type", &N, N.getType());
1542}
1543
1544void Verifier::visitDIAssignID(const DIAssignID &N) {
1545 CheckDI(!N.getNumOperands(), "DIAssignID has no arguments", &N);
1546 CheckDI(N.isDistinct(), "DIAssignID must be distinct", &N);
1547}
1548
1549void Verifier::visitDILabel(const DILabel &N) {
1550 if (auto *S = N.getRawScope())
1551 CheckDI(isa<DIScope>(S), "invalid scope", &N, S);
1552 if (auto *F = N.getRawFile())
1553 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1554
1555 CheckDI(N.getTag() == dwarf::DW_TAG_label, "invalid tag", &N);
1556 CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1557 "label requires a valid scope", &N, N.getRawScope());
1558}
1559
1560void Verifier::visitDIExpression(const DIExpression &N) {
1561 CheckDI(N.isValid(), "invalid expression", &N);
1562}
1563
1564void Verifier::visitDIGlobalVariableExpression(
1565 const DIGlobalVariableExpression &GVE) {
1566 CheckDI(GVE.getVariable(), "missing variable");
1567 if (auto *Var = GVE.getVariable())
1568 visitDIGlobalVariable(*Var);
1569 if (auto *Expr = GVE.getExpression()) {
1570 visitDIExpression(*Expr);
1571 if (auto Fragment = Expr->getFragmentInfo())
1572 verifyFragmentExpression(*GVE.getVariable(), *Fragment, &GVE);
1573 }
1574}
1575
1576void Verifier::visitDIObjCProperty(const DIObjCProperty &N) {
1577 CheckDI(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
1578 if (auto *T = N.getRawType())
1579 CheckDI(isType(T), "invalid type ref", &N, T);
1580 if (auto *F = N.getRawFile())
1581 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1582}
1583
1584void Verifier::visitDIImportedEntity(const DIImportedEntity &N) {
1585 CheckDI(N.getTag() == dwarf::DW_TAG_imported_module ||
1586 N.getTag() == dwarf::DW_TAG_imported_declaration,
1587 "invalid tag", &N);
1588 if (auto *S = N.getRawScope())
1589 CheckDI(isa<DIScope>(S), "invalid scope for imported entity", &N, S);
1590 CheckDI(isDINode(N.getRawEntity()), "invalid imported entity", &N,
1591 N.getRawEntity());
1592}
1593
1594void Verifier::visitComdat(const Comdat &C) {
1595 // In COFF the Module is invalid if the GlobalValue has private linkage.
1596 // Entities with private linkage don't have entries in the symbol table.
1597 if (TT.isOSBinFormatCOFF())
1598 if (const GlobalValue *GV = M.getNamedValue(C.getName()))
1599 Check(!GV->hasPrivateLinkage(), "comdat global value has private linkage",
1600 GV);
1601}
1602
1603void Verifier::visitModuleIdents() {
1604 const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
1605 if (!Idents)
1606 return;
1607
1608 // llvm.ident takes a list of metadata entry. Each entry has only one string.
1609 // Scan each llvm.ident entry and make sure that this requirement is met.
1610 for (const MDNode *N : Idents->operands()) {
1611 Check(N->getNumOperands() == 1,
1612 "incorrect number of operands in llvm.ident metadata", N);
1613 Check(dyn_cast_or_null<MDString>(N->getOperand(0)),
1614 ("invalid value for llvm.ident metadata entry operand"
1615 "(the operand should be a string)"),
1616 N->getOperand(0));
1617 }
1618}
1619
1620void Verifier::visitModuleCommandLines() {
1621 const NamedMDNode *CommandLines = M.getNamedMetadata("llvm.commandline");
1622 if (!CommandLines)
1623 return;
1624
1625 // llvm.commandline takes a list of metadata entry. Each entry has only one
1626 // string. Scan each llvm.commandline entry and make sure that this
1627 // requirement is met.
1628 for (const MDNode *N : CommandLines->operands()) {
1629 Check(N->getNumOperands() == 1,
1630 "incorrect number of operands in llvm.commandline metadata", N);
1631 Check(dyn_cast_or_null<MDString>(N->getOperand(0)),
1632 ("invalid value for llvm.commandline metadata entry operand"
1633 "(the operand should be a string)"),
1634 N->getOperand(0));
1635 }
1636}
1637
1638void Verifier::visitModuleFlags() {
1639 const NamedMDNode *Flags = M.getModuleFlagsMetadata();
1640 if (!Flags) return;
1641
1642 // Scan each flag, and track the flags and requirements.
1644 SmallVector<const MDNode*, 16> Requirements;
1645 for (const MDNode *MDN : Flags->operands())
1646 visitModuleFlag(MDN, SeenIDs, Requirements);
1647
1648 // Validate that the requirements in the module are valid.
1649 for (const MDNode *Requirement : Requirements) {
1650 const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1651 const Metadata *ReqValue = Requirement->getOperand(1);
1652
1653 const MDNode *Op = SeenIDs.lookup(Flag);
1654 if (!Op) {
1655 CheckFailed("invalid requirement on flag, flag is not present in module",
1656 Flag);
1657 continue;
1658 }
1659
1660 if (Op->getOperand(2) != ReqValue) {
1661 CheckFailed(("invalid requirement on flag, "
1662 "flag does not have the required value"),
1663 Flag);
1664 continue;
1665 }
1666 }
1667}
1668
1669void
1670Verifier::visitModuleFlag(const MDNode *Op,
1672 SmallVectorImpl<const MDNode *> &Requirements) {
1673 // Each module flag should have three arguments, the merge behavior (a
1674 // constant int), the flag ID (an MDString), and the value.
1675 Check(Op->getNumOperands() == 3,
1676 "incorrect number of operands in module flag", Op);
1678 if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
1679 Check(mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)),
1680 "invalid behavior operand in module flag (expected constant integer)",
1681 Op->getOperand(0));
1682 Check(false,
1683 "invalid behavior operand in module flag (unexpected constant)",
1684 Op->getOperand(0));
1685 }
1686 MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
1687 Check(ID, "invalid ID operand in module flag (expected metadata string)",
1688 Op->getOperand(1));
1689
1690 // Check the values for behaviors with additional requirements.
1691 switch (MFB) {
1692 case Module::Error:
1693 case Module::Warning:
1694 case Module::Override:
1695 // These behavior types accept any value.
1696 break;
1697
1698 case Module::Min: {
1699 auto *V = mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
1700 Check(V && V->getValue().isNonNegative(),
1701 "invalid value for 'min' module flag (expected constant non-negative "
1702 "integer)",
1703 Op->getOperand(2));
1704 break;
1705 }
1706
1707 case Module::Max: {
1708 Check(mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2)),
1709 "invalid value for 'max' module flag (expected constant integer)",
1710 Op->getOperand(2));
1711 break;
1712 }
1713
1714 case Module::Require: {
1715 // The value should itself be an MDNode with two operands, a flag ID (an
1716 // MDString), and a value.
1717 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
1718 Check(Value && Value->getNumOperands() == 2,
1719 "invalid value for 'require' module flag (expected metadata pair)",
1720 Op->getOperand(2));
1721 Check(isa<MDString>(Value->getOperand(0)),
1722 ("invalid value for 'require' module flag "
1723 "(first value operand should be a string)"),
1724 Value->getOperand(0));
1725
1726 // Append it to the list of requirements, to check once all module flags are
1727 // scanned.
1728 Requirements.push_back(Value);
1729 break;
1730 }
1731
1732 case Module::Append:
1733 case Module::AppendUnique: {
1734 // These behavior types require the operand be an MDNode.
1735 Check(isa<MDNode>(Op->getOperand(2)),
1736 "invalid value for 'append'-type module flag "
1737 "(expected a metadata node)",
1738 Op->getOperand(2));
1739 break;
1740 }
1741 }
1742
1743 // Unless this is a "requires" flag, check the ID is unique.
1744 if (MFB != Module::Require) {
1745 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
1746 Check(Inserted,
1747 "module flag identifiers must be unique (or of 'require' type)", ID);
1748 }
1749
1750 if (ID->getString() == "wchar_size") {
1752 = mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
1753 Check(Value, "wchar_size metadata requires constant integer argument");
1754 }
1755
1756 if (ID->getString() == "Linker Options") {
1757 // If the llvm.linker.options named metadata exists, we assume that the
1758 // bitcode reader has upgraded the module flag. Otherwise the flag might
1759 // have been created by a client directly.
1760 Check(M.getNamedMetadata("llvm.linker.options"),
1761 "'Linker Options' named metadata no longer supported");
1762 }
1763
1764 if (ID->getString() == "SemanticInterposition") {
1766 mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
1767 Check(Value,
1768 "SemanticInterposition metadata requires constant integer argument");
1769 }
1770
1771 if (ID->getString() == "CG Profile") {
1772 for (const MDOperand &MDO : cast<MDNode>(Op->getOperand(2))->operands())
1773 visitModuleFlagCGProfileEntry(MDO);
1774 }
1775}
1776
1777void Verifier::visitModuleFlagCGProfileEntry(const MDOperand &MDO) {
1778 auto CheckFunction = [&](const MDOperand &FuncMDO) {
1779 if (!FuncMDO)
1780 return;
1781 auto F = dyn_cast<ValueAsMetadata>(FuncMDO);
1782 Check(F && isa<Function>(F->getValue()->stripPointerCasts()),
1783 "expected a Function or null", FuncMDO);
1784 };
1785 auto Node = dyn_cast_or_null<MDNode>(MDO);
1786 Check(Node && Node->getNumOperands() == 3, "expected a MDNode triple", MDO);
1787 CheckFunction(Node->getOperand(0));
1788 CheckFunction(Node->getOperand(1));
1789 auto Count = dyn_cast_or_null<ConstantAsMetadata>(Node->getOperand(2));
1790 Check(Count && Count->getType()->isIntegerTy(),
1791 "expected an integer constant", Node->getOperand(2));
1792}
1793
1794void Verifier::verifyAttributeTypes(AttributeSet Attrs, const Value *V) {
1795 for (Attribute A : Attrs) {
1796
1797 if (A.isStringAttribute()) {
1798#define GET_ATTR_NAMES
1799#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)
1800#define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME) \
1801 if (A.getKindAsString() == #DISPLAY_NAME) { \
1802 auto V = A.getValueAsString(); \
1803 if (!(V.empty() || V == "true" || V == "false")) \
1804 CheckFailed("invalid value for '" #DISPLAY_NAME "' attribute: " + V + \
1805 ""); \
1806 }
1807
1808#include "llvm/IR/Attributes.inc"
1809 continue;
1810 }
1811
1812 if (A.isIntAttribute() != Attribute::isIntAttrKind(A.getKindAsEnum())) {
1813 CheckFailed("Attribute '" + A.getAsString() + "' should have an Argument",
1814 V);
1815 return;
1816 }
1817 }
1818}
1819
1820// VerifyParameterAttrs - Check the given attributes for an argument or return
1821// value of the specified type. The value V is printed in error messages.
1822void Verifier::verifyParameterAttrs(AttributeSet Attrs, Type *Ty,
1823 const Value *V) {
1824 if (!Attrs.hasAttributes())
1825 return;
1826
1827 verifyAttributeTypes(Attrs, V);
1828
1829 for (Attribute Attr : Attrs)
1830 Check(Attr.isStringAttribute() ||
1831 Attribute::canUseAsParamAttr(Attr.getKindAsEnum()),
1832 "Attribute '" + Attr.getAsString() + "' does not apply to parameters",
1833 V);
1834
1835 if (Attrs.hasAttribute(Attribute::ImmArg)) {
1836 Check(Attrs.getNumAttributes() == 1,
1837 "Attribute 'immarg' is incompatible with other attributes", V);
1838 }
1839
1840 // Check for mutually incompatible attributes. Only inreg is compatible with
1841 // sret.
1842 unsigned AttrCount = 0;
1843 AttrCount += Attrs.hasAttribute(Attribute::ByVal);
1844 AttrCount += Attrs.hasAttribute(Attribute::InAlloca);
1845 AttrCount += Attrs.hasAttribute(Attribute::Preallocated);
1846 AttrCount += Attrs.hasAttribute(Attribute::StructRet) ||
1847 Attrs.hasAttribute(Attribute::InReg);
1848 AttrCount += Attrs.hasAttribute(Attribute::Nest);
1849 AttrCount += Attrs.hasAttribute(Attribute::ByRef);
1850 Check(AttrCount <= 1,
1851 "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
1852 "'byref', and 'sret' are incompatible!",
1853 V);
1854
1855 Check(!(Attrs.hasAttribute(Attribute::InAlloca) &&
1856 Attrs.hasAttribute(Attribute::ReadOnly)),
1857 "Attributes "
1858 "'inalloca and readonly' are incompatible!",
1859 V);
1860
1861 Check(!(Attrs.hasAttribute(Attribute::StructRet) &&
1862 Attrs.hasAttribute(Attribute::Returned)),
1863 "Attributes "
1864 "'sret and returned' are incompatible!",
1865 V);
1866
1867 Check(!(Attrs.hasAttribute(Attribute::ZExt) &&
1868 Attrs.hasAttribute(Attribute::SExt)),
1869 "Attributes "
1870 "'zeroext and signext' are incompatible!",
1871 V);
1872
1873 Check(!(Attrs.hasAttribute(Attribute::ReadNone) &&
1874 Attrs.hasAttribute(Attribute::ReadOnly)),
1875 "Attributes "
1876 "'readnone and readonly' are incompatible!",
1877 V);
1878
1879 Check(!(Attrs.hasAttribute(Attribute::ReadNone) &&
1880 Attrs.hasAttribute(Attribute::WriteOnly)),
1881 "Attributes "
1882 "'readnone and writeonly' are incompatible!",
1883 V);
1884
1885 Check(!(Attrs.hasAttribute(Attribute::ReadOnly) &&
1886 Attrs.hasAttribute(Attribute::WriteOnly)),
1887 "Attributes "
1888 "'readonly and writeonly' are incompatible!",
1889 V);
1890
1891 Check(!(Attrs.hasAttribute(Attribute::NoInline) &&
1892 Attrs.hasAttribute(Attribute::AlwaysInline)),
1893 "Attributes "
1894 "'noinline and alwaysinline' are incompatible!",
1895 V);
1896
1897 AttributeMask IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty);
1898 for (Attribute Attr : Attrs) {
1899 if (!Attr.isStringAttribute() &&
1900 IncompatibleAttrs.contains(Attr.getKindAsEnum())) {
1901 CheckFailed("Attribute '" + Attr.getAsString() +
1902 "' applied to incompatible type!", V);
1903 return;
1904 }
1905 }
1906
1907 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1908 if (Attrs.hasAttribute(Attribute::ByVal)) {
1909 if (Attrs.hasAttribute(Attribute::Alignment)) {
1910 Align AttrAlign = Attrs.getAlignment().valueOrOne();
1911 Align MaxAlign(ParamMaxAlignment);
1912 Check(AttrAlign <= MaxAlign,
1913 "Attribute 'align' exceed the max size 2^14", V);
1914 }
1915 SmallPtrSet<Type *, 4> Visited;
1916 Check(Attrs.getByValType()->isSized(&Visited),
1917 "Attribute 'byval' does not support unsized types!", V);
1918 }
1919 if (Attrs.hasAttribute(Attribute::ByRef)) {
1920 SmallPtrSet<Type *, 4> Visited;
1921 Check(Attrs.getByRefType()->isSized(&Visited),
1922 "Attribute 'byref' does not support unsized types!", V);
1923 }
1924 if (Attrs.hasAttribute(Attribute::InAlloca)) {
1925 SmallPtrSet<Type *, 4> Visited;
1926 Check(Attrs.getInAllocaType()->isSized(&Visited),
1927 "Attribute 'inalloca' does not support unsized types!", V);
1928 }
1929 if (Attrs.hasAttribute(Attribute::Preallocated)) {
1930 SmallPtrSet<Type *, 4> Visited;
1931 Check(Attrs.getPreallocatedType()->isSized(&Visited),
1932 "Attribute 'preallocated' does not support unsized types!", V);
1933 }
1934 if (!PTy->isOpaque()) {
1935 if (!isa<PointerType>(PTy->getNonOpaquePointerElementType()))
1936 Check(!Attrs.hasAttribute(Attribute::SwiftError),
1937 "Attribute 'swifterror' only applies to parameters "
1938 "with pointer to pointer type!",
1939 V);
1940 if (Attrs.hasAttribute(Attribute::ByRef)) {
1941 Check(Attrs.getByRefType() == PTy->getNonOpaquePointerElementType(),
1942 "Attribute 'byref' type does not match parameter!", V);
1943 }
1944
1945 if (Attrs.hasAttribute(Attribute::ByVal) && Attrs.getByValType()) {
1946 Check(Attrs.getByValType() == PTy->getNonOpaquePointerElementType(),
1947 "Attribute 'byval' type does not match parameter!", V);
1948 }
1949
1950 if (Attrs.hasAttribute(Attribute::Preallocated)) {
1951 Check(Attrs.getPreallocatedType() ==
1952 PTy->getNonOpaquePointerElementType(),
1953 "Attribute 'preallocated' type does not match parameter!", V);
1954 }
1955
1956 if (Attrs.hasAttribute(Attribute::InAlloca)) {
1957 Check(Attrs.getInAllocaType() == PTy->getNonOpaquePointerElementType(),
1958 "Attribute 'inalloca' type does not match parameter!", V);
1959 }
1960
1961 if (Attrs.hasAttribute(Attribute::ElementType)) {
1962 Check(Attrs.getElementType() == PTy->getNonOpaquePointerElementType(),
1963 "Attribute 'elementtype' type does not match parameter!", V);
1964 }
1965 }
1966 }
1967
1968 if (Attrs.hasAttribute(Attribute::NoFPClass)) {
1969 uint64_t Val = Attrs.getAttribute(Attribute::NoFPClass).getValueAsInt();
1970 Check(Val != 0, "Attribute 'nofpclass' must have at least one test bit set",
1971 V);
1972 Check((Val & ~static_cast<unsigned>(fcAllFlags)) == 0,
1973 "Invalid value for 'nofpclass' test mask", V);
1974 }
1975}
1976
1977void Verifier::checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
1978 const Value *V) {
1979 if (Attrs.hasFnAttr(Attr)) {
1980 StringRef S = Attrs.getFnAttr(Attr).getValueAsString();
1981 unsigned N;
1982 if (S.getAsInteger(10, N))
1983 CheckFailed("\"" + Attr + "\" takes an unsigned integer: " + S, V);
1984 }
1985}
1986
1987// Check parameter attributes against a function type.
1988// The value V is printed in error messages.
1989void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
1990 const Value *V, bool IsIntrinsic,
1991 bool IsInlineAsm) {
1992 if (Attrs.isEmpty())
1993 return;
1994
1995 if (AttributeListsVisited.insert(Attrs.getRawPointer()).second) {
1996 Check(Attrs.hasParentContext(Context),
1997 "Attribute list does not match Module context!", &Attrs, V);
1998 for (const auto &AttrSet : Attrs) {
1999 Check(!AttrSet.hasAttributes() || AttrSet.hasParentContext(Context),
2000 "Attribute set does not match Module context!", &AttrSet, V);
2001 for (const auto &A : AttrSet) {
2002 Check(A.hasParentContext(Context),
2003 "Attribute does not match Module context!", &A, V);
2004 }
2005 }
2006 }
2007
2008 bool SawNest = false;
2009 bool SawReturned = false;
2010 bool SawSRet = false;
2011 bool SawSwiftSelf = false;
2012 bool SawSwiftAsync = false;
2013 bool SawSwiftError = false;
2014
2015 // Verify return value attributes.
2016 AttributeSet RetAttrs = Attrs.getRetAttrs();
2017 for (Attribute RetAttr : RetAttrs)
2018 Check(RetAttr.isStringAttribute() ||
2019 Attribute::canUseAsRetAttr(RetAttr.getKindAsEnum()),
2020 "Attribute '" + RetAttr.getAsString() +
2021 "' does not apply to function return values",
2022 V);
2023
2024 verifyParameterAttrs(RetAttrs, FT->getReturnType(), V);
2025
2026 // Verify parameter attributes.
2027 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2028 Type *Ty = FT->getParamType(i);
2029 AttributeSet ArgAttrs = Attrs.getParamAttrs(i);
2030
2031 if (!IsIntrinsic) {
2032 Check(!ArgAttrs.hasAttribute(Attribute::ImmArg),
2033 "immarg attribute only applies to intrinsics", V);
2034 if (!IsInlineAsm)
2035 Check(!ArgAttrs.hasAttribute(Attribute::ElementType),
2036 "Attribute 'elementtype' can only be applied to intrinsics"
2037 " and inline asm.",
2038 V);
2039 }
2040
2041 verifyParameterAttrs(ArgAttrs, Ty, V);
2042
2043 if (ArgAttrs.hasAttribute(Attribute::Nest)) {
2044 Check(!SawNest, "More than one parameter has attribute nest!", V);
2045 SawNest = true;
2046 }
2047
2048 if (ArgAttrs.hasAttribute(Attribute::Returned)) {
2049 Check(!SawReturned, "More than one parameter has attribute returned!", V);
2050 Check(Ty->canLosslesslyBitCastTo(FT->getReturnType()),
2051 "Incompatible argument and return types for 'returned' attribute",
2052 V);
2053 SawReturned = true;
2054 }
2055
2056 if (ArgAttrs.hasAttribute(Attribute::StructRet)) {
2057 Check(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
2058 Check(i == 0 || i == 1,
2059 "Attribute 'sret' is not on first or second parameter!", V);
2060 SawSRet = true;
2061 }
2062
2063 if (ArgAttrs.hasAttribute(Attribute::SwiftSelf)) {
2064 Check(!SawSwiftSelf, "Cannot have multiple 'swiftself' parameters!", V);
2065 SawSwiftSelf = true;
2066 }
2067
2068 if (ArgAttrs.hasAttribute(Attribute::SwiftAsync)) {
2069 Check(!SawSwiftAsync, "Cannot have multiple 'swiftasync' parameters!", V);
2070 SawSwiftAsync = true;
2071 }
2072
2073 if (ArgAttrs.hasAttribute(Attribute::SwiftError)) {
2074 Check(!SawSwiftError, "Cannot have multiple 'swifterror' parameters!", V);
2075 SawSwiftError = true;
2076 }
2077
2078 if (ArgAttrs.hasAttribute(Attribute::InAlloca)) {
2079 Check(i == FT->getNumParams() - 1,
2080 "inalloca isn't on the last parameter!", V);
2081 }
2082 }
2083
2084 if (!Attrs.hasFnAttrs())
2085 return;
2086
2087 verifyAttributeTypes(Attrs.getFnAttrs(), V);
2088 for (Attribute FnAttr : Attrs.getFnAttrs())
2089 Check(FnAttr.isStringAttribute() ||
2090 Attribute::canUseAsFnAttr(FnAttr.getKindAsEnum()),
2091 "Attribute '" + FnAttr.getAsString() +
2092 "' does not apply to functions!",
2093 V);
2094
2095 Check(!(Attrs.hasFnAttr(Attribute::NoInline) &&
2096 Attrs.hasFnAttr(Attribute::AlwaysInline)),
2097 "Attributes 'noinline and alwaysinline' are incompatible!", V);
2098
2099 if (Attrs.hasFnAttr(Attribute::OptimizeNone)) {
2100 Check(Attrs.hasFnAttr(Attribute::NoInline),
2101 "Attribute 'optnone' requires 'noinline'!", V);
2102
2103 Check(!Attrs.hasFnAttr(Attribute::OptimizeForSize),
2104 "Attributes 'optsize and optnone' are incompatible!", V);
2105
2106 Check(!Attrs.hasFnAttr(Attribute::MinSize),
2107 "Attributes 'minsize and optnone' are incompatible!", V);
2108 }
2109
2110 if (Attrs.hasFnAttr("aarch64_pstate_sm_enabled")) {
2111 Check(!Attrs.hasFnAttr("aarch64_pstate_sm_compatible"),
2112 "Attributes 'aarch64_pstate_sm_enabled and "
2113 "aarch64_pstate_sm_compatible' are incompatible!",
2114 V);
2115 }
2116
2117 if (Attrs.hasFnAttr("aarch64_pstate_za_new")) {
2118 Check(!Attrs.hasFnAttr("aarch64_pstate_za_preserved"),
2119 "Attributes 'aarch64_pstate_za_new and aarch64_pstate_za_preserved' "
2120 "are incompatible!",
2121 V);
2122
2123 Check(!Attrs.hasFnAttr("aarch64_pstate_za_shared"),
2124 "Attributes 'aarch64_pstate_za_new and aarch64_pstate_za_shared' "
2125 "are incompatible!",
2126 V);
2127 }
2128
2129 if (Attrs.hasFnAttr(Attribute::JumpTable)) {
2130 const GlobalValue *GV = cast<GlobalValue>(V);
2132 "Attribute 'jumptable' requires 'unnamed_addr'", V);
2133 }
2134
2135 if (auto Args = Attrs.getFnAttrs().getAllocSizeArgs()) {
2136 auto CheckParam = [&](StringRef Name, unsigned ParamNo) {
2137 if (ParamNo >= FT->getNumParams()) {
2138 CheckFailed("'allocsize' " + Name + " argument is out of bounds", V);
2139 return false;
2140 }
2141
2142 if (!FT->getParamType(ParamNo)->isIntegerTy()) {
2143 CheckFailed("'allocsize' " + Name +
2144 " argument must refer to an integer parameter",
2145 V);
2146 return false;
2147 }
2148
2149 return true;
2150 };
2151
2152 if (!CheckParam("element size", Args->first))
2153 return;
2154
2155 if (Args->second && !CheckParam("number of elements", *Args->second))
2156 return;
2157 }
2158
2159 if (Attrs.hasFnAttr(Attribute::AllocKind)) {
2160 AllocFnKind K = Attrs.getAllocKind();
2163 if (!is_contained(
2165 Type))
2166 CheckFailed(
2167 "'allockind()' requires exactly one of alloc, realloc, and free");
2168 if ((Type == AllocFnKind::Free) &&
2171 CheckFailed("'allockind(\"free\")' doesn't allow uninitialized, zeroed, "
2172 "or aligned modifiers.");
2174 if ((K & ZeroedUninit) == ZeroedUninit)
2175 CheckFailed("'allockind()' can't be both zeroed and uninitialized");
2176 }
2177
2178 if (Attrs.hasFnAttr(Attribute::VScaleRange)) {
2179 unsigned VScaleMin = Attrs.getFnAttrs().getVScaleRangeMin();
2180 if (VScaleMin == 0)
2181 CheckFailed("'vscale_range' minimum must be greater than 0", V);
2182
2183 std::optional<unsigned> VScaleMax = Attrs.getFnAttrs().getVScaleRangeMax();
2184 if (VScaleMax && VScaleMin > VScaleMax)
2185 CheckFailed("'vscale_range' minimum cannot be greater than maximum", V);
2186 }
2187
2188 if (Attrs.hasFnAttr("frame-pointer")) {
2189 StringRef FP = Attrs.getFnAttr("frame-pointer").getValueAsString();
2190 if (FP != "all" && FP != "non-leaf" && FP != "none")
2191 CheckFailed("invalid value for 'frame-pointer' attribute: " + FP, V);
2192 }
2193
2194 checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-prefix", V);
2195 checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-entry", V);
2196 checkUnsignedBaseTenFuncAttr(Attrs, "warn-stack-size", V);
2197}
2198
2199void Verifier::verifyFunctionMetadata(
2200 ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
2201 for (const auto &Pair : MDs) {
2202 if (Pair.first == LLVMContext::MD_prof) {
2203 MDNode *MD = Pair.second;
2204 Check(MD->getNumOperands() >= 2,
2205 "!prof annotations should have no less than 2 operands", MD);
2206
2207 // Check first operand.
2208 Check(MD->getOperand(0) != nullptr, "first operand should not be null",
2209 MD);
2210 Check(isa<MDString>(MD->getOperand(0)),
2211 "expected string with name of the !prof annotation", MD);
2212 MDString *MDS = cast<MDString>(MD->getOperand(0));
2213 StringRef ProfName = MDS->getString();
2214 Check(ProfName.equals("function_entry_count") ||
2215 ProfName.equals("synthetic_function_entry_count"),
2216 "first operand should be 'function_entry_count'"
2217 " or 'synthetic_function_entry_count'",
2218 MD);
2219
2220 // Check second operand.
2221 Check(MD->getOperand(1) != nullptr, "second operand should not be null",
2222 MD);
2223 Check(isa<ConstantAsMetadata>(MD->getOperand(1)),
2224 "expected integer argument to function_entry_count", MD);
2225 } else if (Pair.first == LLVMContext::MD_kcfi_type) {
2226 MDNode *MD = Pair.second;
2227 Check(MD->getNumOperands() == 1,
2228 "!kcfi_type must have exactly one operand", MD);
2229 Check(MD->getOperand(0) != nullptr, "!kcfi_type operand must not be null",
2230 MD);
2231 Check(isa<ConstantAsMetadata>(MD->getOperand(0)),
2232 "expected a constant operand for !kcfi_type", MD);
2233 Constant *C = cast<ConstantAsMetadata>(MD->getOperand(0))->getValue();
2234 Check(isa<ConstantInt>(C),
2235 "expected a constant integer operand for !kcfi_type", MD);
2236 IntegerType *Type = cast<ConstantInt>(C)->getType();
2237 Check(Type->getBitWidth() == 32,
2238 "expected a 32-bit integer constant operand for !kcfi_type", MD);
2239 }
2240 }
2241}
2242
2243void Verifier::visitConstantExprsRecursively(const Constant *EntryC) {
2244 if (!ConstantExprVisited.insert(EntryC).second)
2245 return;
2246
2248 Stack.push_back(EntryC);
2249
2250 while (!Stack.empty()) {
2251 const Constant *C = Stack.pop_back_val();
2252
2253 // Check this constant expression.
2254 if (const auto *CE = dyn_cast<ConstantExpr>(C))
2255 visitConstantExpr(CE);
2256
2257 if (const auto *GV = dyn_cast<GlobalValue>(C)) {
2258 // Global Values get visited separately, but we do need to make sure
2259 // that the global value is in the correct module
2260 Check(GV->getParent() == &M, "Referencing global in another module!",
2261 EntryC, &M, GV, GV->getParent());
2262 continue;
2263 }
2264
2265 // Visit all sub-expressions.
2266 for (const Use &U : C->operands()) {
2267 const auto *OpC = dyn_cast<Constant>(U);
2268 if (!OpC)
2269 continue;
2270 if (!ConstantExprVisited.insert(OpC).second)
2271 continue;
2272 Stack.push_back(OpC);
2273 }
2274 }
2275}
2276
2277void Verifier::visitConstantExpr(const ConstantExpr *CE) {
2278 if (CE->getOpcode() == Instruction::BitCast)
2279 Check(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
2280 CE->getType()),
2281 "Invalid bitcast", CE);
2282}
2283
2284bool Verifier::verifyAttributeCount(AttributeList Attrs, unsigned Params) {
2285 // There shouldn't be more attribute sets than there are parameters plus the
2286 // function and return value.
2287 return Attrs.getNumAttrSets() <= Params + 2;
2288}
2289
2290void Verifier::verifyInlineAsmCall(const CallBase &Call) {
2291 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
2292 unsigned ArgNo = 0;
2293 unsigned LabelNo = 0;
2294 for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
2295 if (CI.Type == InlineAsm::isLabel) {
2296 ++LabelNo;
2297 continue;
2298 }
2299
2300 // Only deal with constraints that correspond to call arguments.
2301 if (!CI.hasArg())
2302 continue;
2303
2304 if (CI.isIndirect) {
2305 const Value *Arg = Call.getArgOperand(ArgNo);
2306 Check(Arg->getType()->isPointerTy(),
2307 "Operand for indirect constraint must have pointer type", &Call);
2308
2309 Check(Call.getParamElementType(ArgNo),
2310 "Operand for indirect constraint must have elementtype attribute",
2311 &Call);
2312 } else {
2313 Check(!Call.paramHasAttr(ArgNo, Attribute::ElementType),
2314 "Elementtype attribute can only be applied for indirect "
2315 "constraints",
2316 &Call);
2317 }
2318
2319 ArgNo++;
2320 }
2321
2322 if (auto *CallBr = dyn_cast<CallBrInst>(&Call)) {
2323 Check(LabelNo == CallBr->getNumIndirectDests(),
2324 "Number of label constraints does not match number of callbr dests",
2325 &Call);
2326 } else {
2327 Check(LabelNo == 0, "Label constraints can only be used with callbr",
2328 &Call);
2329 }
2330}
2331
2332/// Verify that statepoint intrinsic is well formed.
2333void Verifier::verifyStatepoint(const CallBase &Call) {
2334 assert(Call.getCalledFunction() &&
2335 Call.getCalledFunction()->getIntrinsicID() ==
2336 Intrinsic::experimental_gc_statepoint);
2337
2338 Check(!Call.doesNotAccessMemory() && !Call.onlyReadsMemory() &&
2339 !Call.onlyAccessesArgMemory(),
2340 "gc.statepoint must read and write all memory to preserve "
2341 "reordering restrictions required by safepoint semantics",
2342 Call);
2343
2344 const int64_t NumPatchBytes =
2345 cast<ConstantInt>(Call.getArgOperand(1))->getSExtValue();
2346 assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!");
2347 Check(NumPatchBytes >= 0,
2348 "gc.statepoint number of patchable bytes must be "
2349 "positive",
2350 Call);
2351
2352 Type *TargetElemType = Call.getParamElementType(2);
2353 Check(TargetElemType,
2354 "gc.statepoint callee argument must have elementtype attribute", Call);
2355 FunctionType *TargetFuncType = dyn_cast<FunctionType>(TargetElemType);
2356 Check(TargetFuncType,
2357 "gc.statepoint callee elementtype must be function type", Call);
2358
2359 const int NumCallArgs = cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue();
2360 Check(NumCallArgs >= 0,
2361 "gc.statepoint number of arguments to underlying call "
2362 "must be positive",
2363 Call);
2364 const int NumParams = (int)TargetFuncType->getNumParams();
2365 if (TargetFuncType->isVarArg()) {
2366 Check(NumCallArgs >= NumParams,
2367 "gc.statepoint mismatch in number of vararg call args", Call);
2368
2369 // TODO: Remove this limitation
2370 Check(TargetFuncType->getReturnType()->isVoidTy(),
2371 "gc.statepoint doesn't support wrapping non-void "
2372 "vararg functions yet",
2373 Call);
2374 } else
2375 Check(NumCallArgs == NumParams,
2376 "gc.statepoint mismatch in number of call args", Call);
2377
2378 const uint64_t Flags
2379 = cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue();
2380 Check((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
2381 "unknown flag used in gc.statepoint flags argument", Call);
2382
2383 // Verify that the types of the call parameter arguments match
2384 // the type of the wrapped callee.
2385 AttributeList Attrs = Call.getAttributes();
2386 for (int i = 0; i < NumParams; i++) {
2387 Type *ParamType = TargetFuncType->getParamType(i);
2388 Type *ArgType = Call.getArgOperand(5 + i)->getType();
2389 Check(ArgType == ParamType,
2390 "gc.statepoint call argument does not match wrapped "
2391 "function type",
2392 Call);
2393
2394 if (TargetFuncType->isVarArg()) {
2395 AttributeSet ArgAttrs = Attrs.getParamAttrs(5 + i);
2396 Check(!ArgAttrs.hasAttribute(Attribute::StructRet),
2397 "Attribute 'sret' cannot be used for vararg call arguments!", Call);
2398 }
2399 }
2400
2401 const int EndCallArgsInx = 4 + NumCallArgs;
2402
2403 const Value *NumTransitionArgsV = Call.getArgOperand(EndCallArgsInx + 1);
2404 Check(isa<ConstantInt>(NumTransitionArgsV),
2405 "gc.statepoint number of transition arguments "
2406 "must be constant integer",
2407 Call);
2408 const int NumTransitionArgs =
2409 cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
2410 Check(NumTransitionArgs == 0,
2411 "gc.statepoint w/inline transition bundle is deprecated", Call);
2412 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
2413
2414 const Value *NumDeoptArgsV = Call.getArgOperand(EndTransitionArgsInx + 1);
2415 Check(isa<ConstantInt>(NumDeoptArgsV),
2416 "gc.statepoint number of deoptimization arguments "
2417 "must be constant integer",
2418 Call);
2419 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
2420 Check(NumDeoptArgs == 0,
2421 "gc.statepoint w/inline deopt operands is deprecated", Call);
2422
2423 const int ExpectedNumArgs = 7 + NumCallArgs;
2424 Check(ExpectedNumArgs == (int)Call.arg_size(),
2425 "gc.statepoint too many arguments", Call);
2426
2427 // Check that the only uses of this gc.statepoint are gc.result or
2428 // gc.relocate calls which are tied to this statepoint and thus part
2429 // of the same statepoint sequence
2430 for (const User *U : Call.users()) {
2431 const CallInst *UserCall = dyn_cast<const CallInst>(U);
2432 Check(UserCall, "illegal use of statepoint token", Call, U);
2433 if (!UserCall)
2434 continue;
2435 Check(isa<GCRelocateInst>(UserCall) || isa<GCResultInst>(UserCall),
2436 "gc.result or gc.relocate are the only value uses "
2437 "of a gc.statepoint",
2438 Call, U);
2439 if (isa<GCResultInst>(UserCall)) {
2440 Check(UserCall->getArgOperand(0) == &Call,
2441 "gc.result connected to wrong gc.statepoint", Call, UserCall);
2442 } else if (isa<GCRelocateInst>(Call)) {
2443 Check(UserCall->getArgOperand(0) == &Call,
2444 "gc.relocate connected to wrong gc.statepoint", Call, UserCall);
2445 }
2446 }
2447
2448 // Note: It is legal for a single derived pointer to be listed multiple
2449 // times. It's non-optimal, but it is legal. It can also happen after
2450 // insertion if we strip a bitcast away.
2451 // Note: It is really tempting to check that each base is relocated and
2452 // that a derived pointer is never reused as a base pointer. This turns
2453 // out to be problematic since optimizations run after safepoint insertion
2454 // can recognize equality properties that the insertion logic doesn't know
2455 // about. See example statepoint.ll in the verifier subdirectory
2456}
2457
2458void Verifier::verifyFrameRecoverIndices() {
2459 for (auto &Counts : FrameEscapeInfo) {
2460 Function *F = Counts.first;
2461 unsigned EscapedObjectCount = Counts.second.first;
2462 unsigned MaxRecoveredIndex = Counts.second.second;
2463 Check(MaxRecoveredIndex <= EscapedObjectCount,
2464 "all indices passed to llvm.localrecover must be less than the "
2465 "number of arguments passed to llvm.localescape in the parent "
2466 "function",
2467 F);
2468 }
2469}
2470
2471static Instruction *getSuccPad(Instruction *Terminator) {
2472 BasicBlock *UnwindDest;
2473 if (auto *II = dyn_cast<InvokeInst>(Terminator))
2474 UnwindDest = II->getUnwindDest();
2475 else if (auto *CSI = dyn_cast<CatchSwitchInst>(Terminator))
2476 UnwindDest = CSI->getUnwindDest();
2477 else
2478 UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest();
2479 return UnwindDest->getFirstNonPHI();
2480}
2481
2482void Verifier::verifySiblingFuncletUnwinds() {
2485 for (const auto &Pair : SiblingFuncletInfo) {
2486 Instruction *PredPad = Pair.first;
2487 if (Visited.count(PredPad))
2488 continue;
2489 Active.insert(PredPad);
2490 Instruction *Terminator = Pair.second;
2491 do {
2492 Instruction *SuccPad = getSuccPad(Terminator);
2493 if (Active.count(SuccPad)) {
2494 // Found a cycle; report error
2495 Instruction *CyclePad = SuccPad;
2497 do {
2498 CycleNodes.push_back(CyclePad);
2499 Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
2500 if (CycleTerminator != CyclePad)
2501 CycleNodes.push_back(CycleTerminator);
2502 CyclePad = getSuccPad(CycleTerminator);
2503 } while (CyclePad != SuccPad);
2504 Check(false, "EH pads can't handle each other's exceptions",
2505 ArrayRef<Instruction *>(CycleNodes));
2506 }
2507 // Don't re-walk a node we've already checked
2508 if (!Visited.insert(SuccPad).second)
2509 break;
2510 // Walk to this successor if it has a map entry.
2511 PredPad = SuccPad;
2512 auto TermI = SiblingFuncletInfo.find(PredPad);
2513 if (TermI == SiblingFuncletInfo.end())
2514 break;
2515 Terminator = TermI->second;
2516 Active.insert(PredPad);
2517 } while (true);
2518 // Each node only has one successor, so we've walked all the active
2519 // nodes' successors.
2520 Active.clear();
2521 }
2522}
2523
2524// visitFunction - Verify that a function is ok.
2525//
2526void Verifier::visitFunction(const Function &F) {
2527 visitGlobalValue(F);
2528
2529 // Check function arguments.
2530 FunctionType *FT = F.getFunctionType();
2531 unsigned NumArgs = F.arg_size();
2532
2533 Check(&Context == &F.getContext(),
2534 "Function context does not match Module context!", &F);
2535
2536 Check(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
2537 Check(FT->getNumParams() == NumArgs,
2538 "# formal arguments must match # of arguments for function type!", &F,
2539 FT);
2540 Check(F.getReturnType()->isFirstClassType() ||
2541 F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
2542 "Functions cannot return aggregate values!", &F);
2543
2544 Check(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
2545 "Invalid struct return type!", &F);
2546
2547 AttributeList Attrs = F.getAttributes();
2548
2549 Check(verifyAttributeCount(Attrs, FT->getNumParams()),
2550 "Attribute after last parameter!", &F);
2551
2552 bool IsIntrinsic = F.isIntrinsic();
2553
2554 // Check function attributes.
2555 verifyFunctionAttrs(FT, Attrs, &F, IsIntrinsic, /* IsInlineAsm */ false);
2556
2557 // On function declarations/definitions, we do not support the builtin
2558 // attribute. We do not check this in VerifyFunctionAttrs since that is
2559 // checking for Attributes that can/can not ever be on functions.
2560 Check(!Attrs.hasFnAttr(Attribute::Builtin),
2561 "Attribute 'builtin' can only be applied to a callsite.", &F);
2562
2563 Check(!Attrs.hasAttrSomewhere(Attribute::ElementType),
2564 "Attribute 'elementtype' can only be applied to a callsite.", &F);
2565
2566 // Check that this function meets the restrictions on this calling convention.
2567 // Sometimes varargs is used for perfectly forwarding thunks, so some of these
2568 // restrictions can be lifted.
2569 switch (F.getCallingConv()) {
2570 default:
2571 case CallingConv::C:
2572 break;
2573 case CallingConv::X86_INTR: {
2574 Check(F.arg_empty() || Attrs.hasParamAttr(0, Attribute::ByVal),
2575 "Calling convention parameter requires byval", &F);
2576 break;
2577 }
2580 Check(F.getReturnType()->isVoidTy(),
2581 "Calling convention requires void return type", &F);
2582 [[fallthrough]];
2588 Check(!F.hasStructRetAttr(), "Calling convention does not allow sret", &F);
2589 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2590 const unsigned StackAS = DL.getAllocaAddrSpace();
2591 unsigned i = 0;
2592 for (const Argument &Arg : F.args()) {
2593 Check(!Attrs.hasParamAttr(i, Attribute::ByVal),
2594 "Calling convention disallows byval", &F);
2595 Check(!Attrs.hasParamAttr(i, Attribute::Preallocated),
2596 "Calling convention disallows preallocated", &F);
2597 Check(!Attrs.hasParamAttr(i, Attribute::InAlloca),
2598 "Calling convention disallows inalloca", &F);
2599
2600 if (Attrs.hasParamAttr(i, Attribute::ByRef)) {
2601 // FIXME: Should also disallow LDS and GDS, but we don't have the enum
2602 // value here.
2603 Check(Arg.getType()->getPointerAddressSpace() != StackAS,
2604 "Calling convention disallows stack byref", &F);
2605 }
2606
2607 ++i;
2608 }
2609 }
2610
2611 [[fallthrough]];
2612 case CallingConv::Fast:
2613 case CallingConv::Cold:
2617 Check(!F.isVarArg(),
2618 "Calling convention does not support varargs or "
2619 "perfect forwarding!",
2620 &F);
2621 break;
2622 }
2623
2624 // Check that the argument values match the function type for this function...
2625 unsigned i = 0;
2626 for (const Argument &Arg : F.args()) {
2627 Check(Arg.getType() == FT->getParamType(i),
2628 "Argument value does not match function argument type!", &Arg,
2629 FT->getParamType(i));
2630 Check(Arg.getType()->isFirstClassType(),
2631 "Function arguments must have first-class types!", &Arg);
2632 if (!IsIntrinsic) {
2633 Check(!Arg.getType()->isMetadataTy(),
2634 "Function takes metadata but isn't an intrinsic", &Arg, &F);
2635 Check(!Arg.getType()->isTokenTy(),
2636 "Function takes token but isn't an intrinsic", &Arg, &F);
2637 Check(!Arg.getType()->isX86_AMXTy(),
2638 "Function takes x86_amx but isn't an intrinsic", &Arg, &F);
2639 }
2640
2641 // Check that swifterror argument is only used by loads and stores.
2642 if (Attrs.hasParamAttr(i, Attribute::SwiftError)) {
2643 verifySwiftErrorValue(&Arg);
2644 }
2645 ++i;
2646 }
2647
2648 if (!IsIntrinsic) {
2649 Check(!F.getReturnType()->isTokenTy(),
2650 "Function returns a token but isn't an intrinsic", &F);
2651 Check(!F.getReturnType()->isX86_AMXTy(),
2652 "Function returns a x86_amx but isn't an intrinsic", &F);
2653 }
2654
2655 // Get the function metadata attachments.
2657 F.getAllMetadata(MDs);
2658 assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync");
2659 verifyFunctionMetadata(MDs);
2660
2661 // Check validity of the personality function
2662 if (F.hasPersonalityFn()) {
2663 auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
2664 if (Per)
2665 Check(Per->getParent() == F.getParent(),
2666 "Referencing personality function in another module!", &F,
2667 F.getParent(), Per, Per->getParent());
2668 }
2669
2670 // EH funclet coloring can be expensive, recompute on-demand
2671 BlockEHFuncletColors.clear();
2672
2673 if (F.isMaterializable()) {
2674 // Function has a body somewhere we can't see.
2675 Check(MDs.empty(), "unmaterialized function cannot have metadata", &F,
2676 MDs.empty() ? nullptr : MDs.front().second);
2677 } else if (F.isDeclaration()) {
2678 for (const auto &I : MDs) {
2679 // This is used for call site debug information.
2680 CheckDI(I.first != LLVMContext::MD_dbg ||
2681 !cast<DISubprogram>(I.second)->isDistinct(),
2682 "function declaration may only have a unique !dbg attachment",
2683 &F);
2684 Check(I.first != LLVMContext::MD_prof,
2685 "function declaration may not have a !prof attachment", &F);
2686
2687 // Verify the metadata itself.
2688 visitMDNode(*I.second, AreDebugLocsAllowed::Yes);
2689 }
2690 Check(!F.hasPersonalityFn(),
2691 "Function declaration shouldn't have a personality routine", &F);
2692 } else {
2693 // Verify that this function (which has a body) is not named "llvm.*". It
2694 // is not legal to define intrinsics.
2695 Check(!IsIntrinsic, "llvm intrinsics cannot be defined!", &F);
2696
2697 // Check the entry node
2698 const BasicBlock *Entry = &F.getEntryBlock();
2699 Check(pred_empty(Entry),
2700 "Entry block to function must not have predecessors!", Entry);
2701
2702 // The address of the entry block cannot be taken, unless it is dead.
2703 if (Entry->hasAddressTaken()) {
2704 Check(!BlockAddress::lookup(Entry)->isConstantUsed(),
2705 "blockaddress may not be used with the entry block!", Entry);
2706 }
2707
2708 unsigned NumDebugAttachments = 0, NumProfAttachments = 0,
2709 NumKCFIAttachments = 0;
2710 // Visit metadata attachments.
2711 for (const auto &I : MDs) {
2712 // Verify that the attachment is legal.
2713 auto AllowLocs = AreDebugLocsAllowed::No;
2714 switch (I.first) {
2715 default:
2716 break;
2717 case LLVMContext::MD_dbg: {
2718 ++NumDebugAttachments;
2719 CheckDI(NumDebugAttachments == 1,
2720 "function must have a single !dbg attachment", &F, I.second);
2721 CheckDI(isa<DISubprogram>(I.second),
2722 "function !dbg attachment must be a subprogram", &F, I.second);
2723 CheckDI(cast<DISubprogram>(I.second)->isDistinct(),
2724 "function definition may only have a distinct !dbg attachment",
2725 &F);
2726
2727 auto *SP = cast<DISubprogram>(I.second);
2728 const Function *&AttachedTo = DISubprogramAttachments[SP];
2729 CheckDI(!AttachedTo || AttachedTo == &F,
2730 "DISubprogram attached to more than one function", SP, &F);
2731 AttachedTo = &F;
2732 AllowLocs = AreDebugLocsAllowed::Yes;
2733 break;
2734 }
2735 case LLVMContext::MD_prof:
2736 ++NumProfAttachments;
2737 Check(NumProfAttachments == 1,
2738 "function must have a single !prof attachment", &F, I.second);
2739 break;
2740 case LLVMContext::MD_kcfi_type:
2741 ++NumKCFIAttachments;
2742 Check(NumKCFIAttachments == 1,
2743 "function must have a single !kcfi_type attachment", &F,
2744 I.second);
2745 break;
2746 }
2747
2748 // Verify the metadata itself.
2749 visitMDNode(*I.second, AllowLocs);
2750 }
2751 }
2752
2753 // If this function is actually an intrinsic, verify that it is only used in
2754 // direct call/invokes, never having its "address taken".
2755 // Only do this if the module is materialized, otherwise we don't have all the
2756 // uses.
2757 if (F.isIntrinsic() && F.getParent()->isMaterialized()) {
2758 const User *U;
2759 if (F.hasAddressTaken(&U, false, true, false,
2760 /*IgnoreARCAttachedCall=*/true))
2761 Check(false, "Invalid user of intrinsic instruction!", U);
2762 }
2763
2764 // Check intrinsics' signatures.
2765 switch (F.getIntrinsicID()) {
2766 case Intrinsic::experimental_gc_get_pointer_base: {
2767 FunctionType *FT = F.getFunctionType();
2768 Check(FT->getNumParams() == 1, "wrong number of parameters", F);
2769 Check(isa<PointerType>(F.getReturnType()),
2770 "gc.get.pointer.base must return a pointer", F);
2771 Check(FT->getParamType(0) == F.getReturnType(),
2772 "gc.get.pointer.base operand and result must be of the same type", F);
2773 break;
2774 }
2775 case Intrinsic::experimental_gc_get_pointer_offset: {
2776 FunctionType *FT = F.getFunctionType();
2777 Check(FT->getNumParams() == 1, "wrong number of parameters", F);
2778 Check(isa<PointerType>(FT->getParamType(0)),
2779 "gc.get.pointer.offset operand must be a pointer", F);
2780 Check(F.getReturnType()->isIntegerTy(),
2781 "gc.get.pointer.offset must return integer", F);
2782 break;
2783 }
2784 }
2785
2786 auto *N = F.getSubprogram();
2787 HasDebugInfo = (N != nullptr);
2788 if (!HasDebugInfo)
2789 return;
2790
2791 // Check that all !dbg attachments lead to back to N.
2792 //
2793 // FIXME: Check this incrementally while visiting !dbg attachments.
2794 // FIXME: Only check when N is the canonical subprogram for F.
2796 auto VisitDebugLoc = [&](const Instruction &I, const MDNode *Node) {
2797 // Be careful about using DILocation here since we might be dealing with
2798 // broken code (this is the Verifier after all).
2799 const DILocation *DL = dyn_cast_or_null<DILocation>(Node);
2800 if (!DL)
2801 return;
2802 if (!Seen.insert(DL).second)
2803 return;
2804
2805 Metadata *Parent = DL->getRawScope();
2806 CheckDI(Parent && isa<DILocalScope>(Parent),
2807 "DILocation's scope must be a DILocalScope", N, &F, &I, DL, Parent);
2808
2809 DILocalScope *Scope = DL->getInlinedAtScope();
2810 Check(Scope, "Failed to find DILocalScope", DL);
2811
2812 if (!Seen.insert(Scope).second)
2813 return;
2814
2815 DISubprogram *SP = Scope->getSubprogram();
2816
2817 // Scope and SP could be the same MDNode and we don't want to skip
2818 // validation in that case
2819 if (SP && ((Scope != SP) && !Seen.insert(SP).second))
2820 return;
2821
2822 CheckDI(SP->describes(&F),
2823 "!dbg attachment points at wrong subprogram for function", N, &F,
2824 &I, DL, Scope, SP);
2825 };
2826 for (auto &BB : F)
2827 for (auto &I : BB) {
2828 VisitDebugLoc(I, I.getDebugLoc().getAsMDNode());
2829 // The llvm.loop annotations also contain two DILocations.
2830 if (auto MD = I.getMetadata(LLVMContext::MD_loop))
2831 for (unsigned i = 1; i < MD->getNumOperands(); ++i)
2832 VisitDebugLoc(I, dyn_cast_or_null<MDNode>(MD->getOperand(i)));
2833 if (BrokenDebugInfo)
2834 return;
2835 }
2836}
2837
2838// verifyBasicBlock - Verify that a basic block is well formed...
2839//
2840void Verifier::visitBasicBlock(BasicBlock &BB) {
2841 InstsInThisBlock.clear();
2842
2843 // Ensure that basic blocks have terminators!
2844 Check(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
2845
2846 // Check constraints that this basic block imposes on all of the PHI nodes in
2847 // it.
2848 if (isa<PHINode>(BB.front())) {
2851 llvm::sort(Preds);
2852 for (const PHINode &PN : BB.phis()) {
2853 Check(PN.getNumIncomingValues() == Preds.size(),
2854 "PHINode should have one entry for each predecessor of its "
2855 "parent basic block!",
2856 &PN);
2857
2858 // Get and sort all incoming values in the PHI node...
2859 Values.clear();
2860 Values.reserve(PN.getNumIncomingValues());
2861 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
2862 Values.push_back(
2863 std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
2864 llvm::sort(Values);
2865
2866 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
2867 // Check to make sure that if there is more than one entry for a
2868 // particular basic block in this PHI node, that the incoming values are
2869 // all identical.
2870 //
2871 Check(i == 0 || Values[i].first != Values[i - 1].first ||
2872 Values[i].second == Values[i - 1].second,
2873 "PHI node has multiple entries for the same basic block with "
2874 "different incoming values!",
2875 &PN, Values[i].first, Values[i].second, Values[i - 1].second);
2876
2877 // Check to make sure that the predecessors and PHI node entries are
2878 // matched up.
2879 Check(Values[i].first == Preds[i],
2880 "PHI node entries do not match predecessors!", &PN,
2881 Values[i].first, Preds[i]);
2882 }
2883 }
2884 }
2885
2886 // Check that all instructions have their parent pointers set up correctly.
2887 for (auto &I : BB)
2888 {
2889 Check(I.getParent() == &BB, "Instruction has bogus parent pointer!");
2890 }
2891}
2892
2893void Verifier::visitTerminator(Instruction &I) {
2894 // Ensure that terminators only exist at the end of the basic block.
2895 Check(&I == I.getParent()->getTerminator(),
2896 "Terminator found in the middle of a basic block!", I.getParent());
2898}
2899
2900void Verifier::visitBranchInst(BranchInst &BI) {
2901 if (BI.isConditional()) {
2903 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
2904 }
2905 visitTerminator(BI);
2906}
2907
2908void Verifier::visitReturnInst(ReturnInst &RI) {
2909 Function *F = RI.getParent()->getParent();
2910 unsigned N = RI.getNumOperands();
2911 if (F->getReturnType()->isVoidTy())
2912 Check(N == 0,
2913 "Found return instr that returns non-void in Function of void "
2914 "return type!",
2915 &RI, F->getReturnType());
2916 else
2917 Check(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
2918 "Function return type does not match operand "
2919 "type of return inst!",
2920 &RI, F->getReturnType());
2921
2922 // Check to make sure that the return value has necessary properties for
2923 // terminators...
2924 visitTerminator(RI);
2925}
2926
2927void Verifier::visitSwitchInst(SwitchInst &SI) {
2928 Check(SI.getType()->isVoidTy(), "Switch must have void result type!", &SI);
2929 // Check to make sure that all of the constants in the switch instruction
2930 // have the same type as the switched-on value.
2931 Type *SwitchTy = SI.getCondition()->getType();
2933 for (auto &Case : SI.cases()) {
2934 Check(isa<ConstantInt>(SI.getOperand(Case.getCaseIndex() * 2 + 2)),
2935 "Case value is not a constant integer.", &SI);
2936 Check(Case.getCaseValue()->getType() == SwitchTy,
2937 "Switch constants must all be same type as switch value!", &SI);
2938 Check(Constants.insert(Case.getCaseValue()).second,
2939 "Duplicate integer as switch case", &SI, Case.getCaseValue());
2940 }
2941
2942 visitTerminator(SI);
2943}
2944
2945void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
2947 "Indirectbr operand must have pointer type!", &BI);
2948 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
2950 "Indirectbr destinations must all have pointer type!", &BI);
2951
2952 visitTerminator(BI);
2953}
2954
2955void Verifier::visitCallBrInst(CallBrInst &CBI) {
2956 Check(CBI.isInlineAsm(), "Callbr is currently only used for asm-goto!", &CBI);
2957 const InlineAsm *IA = cast<InlineAsm>(CBI.getCalledOperand());
2958 Check(!IA->canThrow(), "Unwinding from Callbr is not allowed");
2959
2960 verifyInlineAsmCall(CBI);
2961 visitTerminator(CBI);
2962}
2963
2964void Verifier::visitSelectInst(SelectInst &SI) {
2965 Check(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
2966 SI.getOperand(2)),
2967 "Invalid operands for select instruction!", &SI);
2968
2969 Check(SI.getTrueValue()->getType() == SI.getType(),
2970 "Select values must have same type as select instruction!", &SI);
2971 visitInstruction(SI);
2972}
2973
2974/// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
2975/// a pass, if any exist, it's an error.
2976///
2977void Verifier::visitUserOp1(Instruction &I) {
2978 Check(false, "User-defined operators should not live outside of a pass!", &I);
2979}
2980
2981void Verifier::visitTruncInst(TruncInst &I) {
2982 // Get the source and destination types
2983 Type *SrcTy = I.getOperand(0)->getType();
2984 Type *DestTy = I.getType();
2985
2986 // Get the size of the types in bits, we'll need this later
2987 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2988 unsigned DestBitSize = DestTy->getScalarSizeInBits();
2989
2990 Check(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
2991 Check(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
2992 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2993 "trunc source and destination must both be a vector or neither", &I);
2994 Check(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
2995
2997}
2998
2999void Verifier::visitZExtInst(ZExtInst &I) {
3000 // Get the source and destination types
3001 Type *SrcTy = I.getOperand(0)->getType();
3002 Type *DestTy = I.getType();
3003
3004 // Get the size of the types in bits, we'll need this later
3005 Check(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
3006 Check(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
3007 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
3008 "zext source and destination must both be a vector or neither", &I);
3009 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3010 unsigned DestBitSize = DestTy->getScalarSizeInBits();
3011
3012 Check(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
3013
3015}
3016
3017void Verifier::visitSExtInst(SExtInst &I) {
3018 // Get the source and destination types
3019 Type *SrcTy = I.getOperand(0)->getType();
3020 Type *DestTy = I.getType();
3021
3022 // Get the size of the types in bits, we'll need this later
3023 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3024 unsigned DestBitSize = DestTy->getScalarSizeInBits();
3025
3026 Check(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
3027 Check(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
3028 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
3029 "sext source and destination must both be a vector or neither", &I);
3030 Check(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
3031
3033}
3034
3035void Verifier::visitFPTruncInst(FPTruncInst &I) {
3036 // Get the source and destination types
3037 Type *SrcTy = I.getOperand(0)->getType();
3038 Type *DestTy = I.getType();
3039 // Get the size of the types in bits, we'll need this later
3040 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3041 unsigned DestBitSize = DestTy->getScalarSizeInBits();
3042
3043 Check(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
3044 Check(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
3045 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
3046 "fptrunc source and destination must both be a vector or neither", &I);
3047 Check(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
3048
3050}
3051
3052void Verifier::visitFPExtInst(FPExtInst &I) {
3053 // Get the source and destination types
3054 Type *SrcTy = I.getOperand(0)->getType();
3055 Type *DestTy = I.getType();
3056
3057 // Get the size of the types in bits, we'll need this later
3058 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3059 unsigned DestBitSize = DestTy->getScalarSizeInBits();
3060
3061 Check(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
3062 Check(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
3063 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
3064 "fpext source and destination must both be a vector or neither", &I);
3065 Check(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
3066
3068}
3069
3070void Verifier::visitUIToFPInst(UIToFPInst &I) {
3071 // Get the source and destination types
3072 Type *SrcTy = I.getOperand(0)->getType();
3073 Type *DestTy = I.getType();
3074
3075 bool SrcVec = SrcTy->isVectorTy();
3076 bool DstVec = DestTy->isVectorTy();
3077
3078 Check(SrcVec == DstVec,
3079 "UIToFP source and dest must both be vector or scalar", &I);
3080 Check(SrcTy->isIntOrIntVectorTy(),
3081 "UIToFP source must be integer or integer vector", &I);
3082 Check(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
3083 &I);
3084
3085 if (SrcVec && DstVec)
3086 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3087 cast<VectorType>(DestTy)->getElementCount(),
3088 "UIToFP source and dest vector length mismatch", &I);
3089
3091}
3092
3093void Verifier::visitSIToFPInst(SIToFPInst &I) {
3094 // Get the source and destination types
3095 Type *SrcTy = I.getOperand(0)->getType();
3096 Type *DestTy = I.getType();
3097
3098 bool SrcVec = SrcTy->isVectorTy();
3099 bool DstVec = DestTy->isVectorTy();
3100
3101 Check(SrcVec == DstVec,
3102 "SIToFP source and dest must both be vector or scalar", &I);
3103 Check(SrcTy->isIntOrIntVectorTy(),
3104 "SIToFP source must be integer or integer vector", &I);
3105 Check(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
3106 &I);
3107
3108 if (SrcVec && DstVec)
3109 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3110 cast<VectorType>(DestTy)->getElementCount(),
3111 "SIToFP source and dest vector length mismatch", &I);
3112
3114}
3115
3116void Verifier::visitFPToUIInst(FPToUIInst &I) {
3117 // Get the source and destination types
3118 Type *SrcTy = I.getOperand(0)->getType();
3119 Type *DestTy = I.getType();
3120
3121 bool SrcVec = SrcTy->isVectorTy();
3122 bool DstVec = DestTy->isVectorTy();
3123
3124 Check(SrcVec == DstVec,
3125 "FPToUI source and dest must both be vector or scalar", &I);
3126 Check(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector", &I);
3127 Check(DestTy->isIntOrIntVectorTy(),
3128 "FPToUI result must be integer or integer vector", &I);
3129
3130 if (SrcVec && DstVec)
3131 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3132 cast<VectorType>(DestTy)->getElementCount(),
3133 "FPToUI source and dest vector length mismatch", &I);
3134
3136}
3137
3138void Verifier::visitFPToSIInst(FPToSIInst &I) {
3139 // Get the source and destination types
3140 Type *SrcTy = I.getOperand(0)->getType();
3141 Type *DestTy = I.getType();
3142
3143 bool SrcVec = SrcTy->isVectorTy();
3144 bool DstVec = DestTy->isVectorTy();
3145
3146 Check(SrcVec == DstVec,
3147 "FPToSI source and dest must both be vector or scalar", &I);
3148 Check(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector", &I);
3149 Check(DestTy->isIntOrIntVectorTy(),
3150 "FPToSI result must be integer or integer vector", &I);
3151
3152 if (SrcVec && DstVec)
3153 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3154 cast<VectorType>(DestTy)->getElementCount(),
3155 "FPToSI source and dest vector length mismatch", &I);
3156
3158}
3159
3160void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
3161 // Get the source and destination types
3162 Type *SrcTy = I.getOperand(0)->getType();
3163 Type *DestTy = I.getType();
3164
3165 Check(SrcTy->isPtrOrPtrVectorTy(), "PtrToInt source must be pointer", &I);
3166
3167 Check(DestTy->isIntOrIntVectorTy(), "PtrToInt result must be integral", &I);
3168 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
3169 &I);
3170
3171 if (SrcTy->isVectorTy()) {
3172 auto *VSrc = cast<VectorType>(SrcTy);
3173 auto *VDest = cast<VectorType>(DestTy);
3174 Check(VSrc->getElementCount() == VDest->getElementCount(),
3175 "PtrToInt Vector width mismatch", &I);
3176 }
3177
3179}
3180
3181void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
3182 // Get the source and destination types
3183 Type *SrcTy = I.getOperand(0)->getType();
3184 Type *DestTy = I.getType();
3185
3186 Check(SrcTy->isIntOrIntVectorTy(), "IntToPtr source must be an integral", &I);
3187 Check(DestTy->isPtrOrPtrVectorTy(), "IntToPtr result must be a pointer", &I);
3188
3189 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
3190 &I);
3191 if (SrcTy->isVectorTy()) {
3192 auto *VSrc = cast<VectorType>(SrcTy);
3193 auto *VDest = cast<VectorType>(DestTy);
3194 Check(VSrc->getElementCount() == VDest->getElementCount(),
3195 "IntToPtr Vector width mismatch", &I);
3196 }
3198}
3199
3200void Verifier::visitBitCastInst(BitCastInst &I) {
3201 Check(
3202 CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
3203 "Invalid bitcast", &I);
3205}
3206
3207void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
3208 Type *SrcTy = I.getOperand(0)->getType();
3209 Type *DestTy = I.getType();
3210
3211 Check(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
3212 &I);
3213 Check(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
3214 &I);
3216 "AddrSpaceCast must be between different address spaces", &I);
3217 if (auto *SrcVTy = dyn_cast<VectorType>(SrcTy))
3218 Check(SrcVTy->getElementCount() ==
3219 cast<VectorType>(DestTy)->getElementCount(),
3220 "AddrSpaceCast vector pointer number of elements mismatch", &I);
3222}
3223
3224/// visitPHINode - Ensure that a PHI node is well formed.
3225///
3226void Verifier::visitPHINode(PHINode &PN) {
3227 // Ensure that the PHI nodes are all grouped together at the top of the block.
3228 // This can be tested by checking whether the instruction before this is
3229 // either nonexistent (because this is begin()) or is a PHI node. If not,
3230 // then there is some other instruction before a PHI.
3231 Check(&PN == &PN.getParent()->front() ||
3232 isa<PHINode>(--BasicBlock::iterator(&PN)),
3233 "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
3234
3235 // Check that a PHI doesn't yield a Token.
3236 Check(!PN.getType()->isTokenTy(), "PHI nodes cannot have token type!");
3237
3238 // Check that all of the values of the PHI node have the same type as the
3239 // result, and that the incoming blocks are really basic blocks.
3240 for (Value *IncValue : PN.incoming_values()) {
3241 Check(PN.getType() == IncValue->getType(),
3242 "PHI node operands are not the same type as the result!", &PN);
3243 }
3244
3245 // All other PHI node constraints are checked in the visitBasicBlock method.
3246
3247 visitInstruction(PN);
3248}
3249
3250void Verifier::visitCallBase(CallBase &Call) {
3251 Check(Call.getCalledOperand()->getType()->isPointerTy(),
3252 "Called function must be a pointer!", Call);
3253 PointerType *FPTy = cast<PointerType>(Call.getCalledOperand()->getType());
3254
3255 Check(FPTy->isOpaqueOrPointeeTypeMatches(Call.getFunctionType()),
3256 "Called function is not the same type as the call!", Call);
3257
3258 FunctionType *FTy = Call.getFunctionType();
3259
3260 // Verify that the correct number of arguments are being passed
3261 if (FTy->isVarArg())
3262 Check(Call.arg_size() >= FTy->getNumParams(),
3263 "Called function requires more parameters than were provided!", Call);
3264 else
3265 Check(Call.arg_size() == FTy->getNumParams(),
3266 "Incorrect number of arguments passed to called function!", Call);
3267
3268 // Verify that all arguments to the call match the function type.
3269 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3270 Check(Call.getArgOperand(i)->getType() == FTy->getParamType(i),
3271 "Call parameter type does not match function signature!",
3272 Call.getArgOperand(i), FTy->getParamType(i), Call);
3273
3274 AttributeList Attrs = Call.getAttributes();
3275
3276 Check(verifyAttributeCount(Attrs, Call.arg_size()),
3277 "Attribute after last parameter!", Call);
3278
3279 Function *Callee =
3280 dyn_cast<Function>(Call.getCalledOperand()->stripPointerCasts());
3281 bool IsIntrinsic = Callee && Callee->isIntrinsic();
3282 if (IsIntrinsic)
3283 Check(Callee->getValueType() == FTy,
3284 "Intrinsic called with incompatible signature", Call);
3285
3286 auto VerifyTypeAlign = [&](Type *Ty, const Twine &Message) {
3287 if (!Ty->isSized())
3288 return;
3289 Align ABIAlign = DL.getABITypeAlign(Ty);
3290 Align MaxAlign(ParamMaxAlignment);
3291 Check(ABIAlign <= MaxAlign,
3292 "Incorrect alignment of " + Message + " to called function!", Call);
3293 };
3294
3295 if (!IsIntrinsic) {
3296 VerifyTypeAlign(FTy->getReturnType(), "return type");
3297 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3298 Type *Ty = FTy->getParamType(i);
3299 VerifyTypeAlign(Ty, "argument passed");
3300 }
3301 }
3302
3303 if (Attrs.hasFnAttr(Attribute::Speculatable)) {
3304 // Don't allow speculatable on call sites, unless the underlying function
3305 // declaration is also speculatable.
3306 Check(Callee && Callee->isSpeculatable(),
3307 "speculatable attribute may not apply to call sites", Call);
3308 }
3309
3310 if (Attrs.hasFnAttr(Attribute::Preallocated)) {
3311 Check(Call.getCalledFunction()->getIntrinsicID() ==
3312 Intrinsic::call_preallocated_arg,
3313 "preallocated as a call site attribute can only be on "
3314 "llvm.call.preallocated.arg");
3315 }
3316
3317 // Verify call attributes.
3318 verifyFunctionAttrs(FTy, Attrs, &Call, IsIntrinsic, Call.isInlineAsm());
3319
3320 // Conservatively check the inalloca argument.
3321 // We have a bug if we can find that there is an underlying alloca without
3322 // inalloca.
3323 if (Call.hasInAllocaArgument()) {
3324 Value *InAllocaArg = Call.getArgOperand(FTy->getNumParams() - 1);
3325 if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
3326 Check(AI->isUsedWithInAlloca(),
3327 "inalloca argument for call has mismatched alloca", AI, Call);
3328 }
3329
3330 // For each argument of the callsite, if it has the swifterror argument,
3331 // make sure the underlying alloca/parameter it comes from has a swifterror as
3332 // well.
3333 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3334 if (Call.paramHasAttr(i, Attribute::SwiftError)) {
3335 Value *SwiftErrorArg = Call.getArgOperand(i);
3336 if (auto AI = dyn_cast<AllocaInst>(SwiftErrorArg->stripInBoundsOffsets())) {
3337 Check(AI->isSwiftError(),
3338 "swifterror argument for call has mismatched alloca", AI, Call);
3339 continue;
3340 }
3341 auto ArgI = dyn_cast<Argument>(SwiftErrorArg);
3342 Check(ArgI, "swifterror argument should come from an alloca or parameter",
3343 SwiftErrorArg, Call);
3344 Check(ArgI->hasSwiftErrorAttr(),
3345 "swifterror argument for call has mismatched parameter", ArgI,
3346 Call);
3347 }
3348
3349 if (Attrs.hasParamAttr(i, Attribute::ImmArg)) {
3350 // Don't allow immarg on call sites, unless the underlying declaration
3351 // also has the matching immarg.
3352 Check(Callee && Callee->hasParamAttribute(i, Attribute::ImmArg),
3353 "immarg may not apply only to call sites", Call.getArgOperand(i),
3354 Call);
3355 }
3356
3357 if (Call.paramHasAttr(i, Attribute::ImmArg)) {
3358 Value *ArgVal = Call.getArgOperand(i);
3359 Check(isa<ConstantInt>(ArgVal) || isa<ConstantFP>(ArgVal),
3360 "immarg operand has non-immediate parameter", ArgVal, Call);
3361 }
3362
3363 if (Call.paramHasAttr(i, Attribute::Preallocated)) {
3364 Value *ArgVal = Call.getArgOperand(i);
3365 bool hasOB =
3366 Call.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0;
3367 bool isMustTail = Call.isMustTailCall();
3368 Check(hasOB != isMustTail,
3369 "preallocated operand either requires a preallocated bundle or "
3370 "the call to be musttail (but not both)",
3371 ArgVal, Call);
3372 }
3373 }
3374
3375 if (FTy->isVarArg()) {
3376 // FIXME? is 'nest' even legal here?
3377 bool SawNest = false;
3378 bool SawReturned = false;
3379
3380 for (unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) {
3381 if (Attrs.hasParamAttr(Idx, Attribute::Nest))
3382 SawNest = true;
3383 if (Attrs.hasParamAttr(Idx, Attribute::Returned))
3384 SawReturned = true;
3385 }
3386
3387 // Check attributes on the varargs part.
3388 for (unsigned Idx = FTy->getNumParams(); Idx < Call.arg_size(); ++Idx) {
3389 Type *Ty = Call.getArgOperand(Idx)->getType();
3390 AttributeSet ArgAttrs = Attrs.getParamAttrs(Idx);
3391 verifyParameterAttrs(ArgAttrs, Ty, &Call);
3392
3393 if (ArgAttrs.hasAttribute(Attribute::Nest)) {
3394 Check(!SawNest, "More than one parameter has attribute nest!", Call);
3395 SawNest = true;
3396 }
3397
3398 if (ArgAttrs.hasAttribute(Attribute::Returned)) {
3399 Check(!SawReturned, "More than one parameter has attribute returned!",
3400 Call);
3401 Check(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
3402 "Incompatible argument and return types for 'returned' "
3403 "attribute",
3404 Call);
3405 SawReturned = true;
3406 }
3407
3408 // Statepoint intrinsic is vararg but the wrapped function may be not.
3409 // Allow sret here and check the wrapped function in verifyStatepoint.
3410 if (!Call.getCalledFunction() ||
3411 Call.getCalledFunction()->getIntrinsicID() !=
3412 Intrinsic::experimental_gc_statepoint)
3413 Check(!ArgAttrs.hasAttribute(Attribute::StructRet),
3414 "Attribute 'sret' cannot be used for vararg call arguments!",
3415 Call);
3416
3417 if (ArgAttrs.hasAttribute(Attribute::InAlloca))
3418 Check(Idx == Call.arg_size() - 1,
3419 "inalloca isn't on the last argument!", Call);
3420 }
3421 }
3422
3423 // Verify that there's no metadata unless it's a direct call to an intrinsic.
3424 if (!IsIntrinsic) {
3425 for (Type *ParamTy : FTy->params()) {
3426 Check(!ParamTy->isMetadataTy(),
3427 "Function has metadata parameter but isn't an intrinsic", Call);
3428 Check(!ParamTy->isTokenTy(),
3429 "Function has token parameter but isn't an intrinsic", Call);
3430 }
3431 }
3432
3433 // Verify that indirect calls don't return tokens.
3434 if (!Call.getCalledFunction()) {
3435 Check(!FTy->getReturnType()->isTokenTy(),
3436 "Return type cannot be token for indirect call!");
3437 Check(!FTy->getReturnType()->isX86_AMXTy(),
3438 "Return type cannot be x86_amx for indirect call!");
3439 }
3440
3441 if (Function *F = Call.getCalledFunction())
3442 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
3443 visitIntrinsicCall(ID, Call);
3444
3445 // Verify that a callsite has at most one "deopt", at most one "funclet", at
3446 // most one "gc-transition", at most one "cfguardtarget", at most one
3447 // "preallocated" operand bundle, and at most one "ptrauth" operand bundle.
3448 bool FoundDeoptBundle = false, FoundFuncletBundle = false,
3449 FoundGCTransitionBundle = false, FoundCFGuardTargetBundle = false,
3450 FoundPreallocatedBundle = false, FoundGCLiveBundle = false,
3451 FoundPtrauthBundle = false, FoundKCFIBundle = false,
3452 FoundAttachedCallBundle = false;
3453 for (unsigned i = 0, e = Call.getNumOperandBundles(); i < e; ++i) {
3454 OperandBundleUse BU = Call.getOperandBundleAt(i);
3455 uint32_t Tag = BU.getTagID();
3456 if (Tag == LLVMContext::OB_deopt) {
3457 Check(!FoundDeoptBundle, "Multiple deopt operand bundles", Call);
3458 FoundDeoptBundle = true;
3459 } else if (Tag == LLVMContext::OB_gc_transition) {
3460 Check(!FoundGCTransitionBundle, "Multiple gc-transition operand bundles",
3461 Call);
3462 FoundGCTransitionBundle = true;
3463 } else if (Tag == LLVMContext::OB_funclet) {
3464 Check(!FoundFuncletBundle, "Multiple funclet operand bundles", Call);
3465 FoundFuncletBundle = true;
3466 Check(BU.Inputs.size() == 1,
3467 "Expected exactly one funclet bundle operand", Call);
3468 Check(isa<FuncletPadInst>(BU.Inputs.front()),
3469 "Funclet bundle operands should correspond to a FuncletPadInst",
3470 Call);
3471 } else if (Tag == LLVMContext::OB_cfguardtarget) {
3472 Check(!FoundCFGuardTargetBundle, "Multiple CFGuardTarget operand bundles",
3473 Call);
3474 FoundCFGuardTargetBundle = true;
3475 Check(BU.Inputs.size() == 1,
3476 "Expected exactly one cfguardtarget bundle operand", Call);
3477 } else if (Tag == LLVMContext::OB_ptrauth) {
3478 Check(!FoundPtrauthBundle, "Multiple ptrauth operand bundles", Call);
3479 FoundPtrauthBundle = true;
3480 Check(BU.Inputs.size() == 2,
3481 "Expected exactly two ptrauth bundle operands", Call);
3482 Check(isa<ConstantInt>(BU.Inputs[0]) &&
3483 BU.Inputs[0]->getType()->isIntegerTy(32),
3484 "Ptrauth bundle key operand must be an i32 constant", Call);
3485 Check(BU.Inputs[1]->getType()->isIntegerTy(64),
3486 "Ptrauth bundle discriminator operand must be an i64", Call);
3487 } else if (Tag == LLVMContext::OB_kcfi) {
3488 Check(!FoundKCFIBundle, "Multiple kcfi operand bundles", Call);
3489 FoundKCFIBundle = true;
3490 Check(BU.Inputs.size() == 1, "Expected exactly one kcfi bundle operand",
3491 Call);
3492 Check(isa<ConstantInt>(BU.Inputs[0]) &&
3493 BU.Inputs[0]->getType()->isIntegerTy(32),
3494 "Kcfi bundle operand must be an i32 constant", Call);
3495 } else if (Tag == LLVMContext::OB_preallocated) {
3496 Check(!FoundPreallocatedBundle, "Multiple preallocated operand bundles",
3497 Call);
3498 FoundPreallocatedBundle = true;
3499 Check(BU.Inputs.size() == 1,
3500 "Expected exactly one preallocated bundle operand", Call);
3501 auto Input = dyn_cast<IntrinsicInst>(BU.Inputs.front());
3502 Check(Input &&
3503 Input->getIntrinsicID() == Intrinsic::call_preallocated_setup,
3504 "\"preallocated\" argument must be a token from "
3505 "llvm.call.preallocated.setup",
3506 Call);
3507 } else if (Tag == LLVMContext::OB_gc_live) {
3508 Check(!FoundGCLiveBundle, "Multiple gc-live operand bundles", Call);
3509 FoundGCLiveBundle = true;
3511 Check(!FoundAttachedCallBundle,
3512 "Multiple \"clang.arc.attachedcall\" operand bundles", Call);
3513 FoundAttachedCallBundle = true;
3514 verifyAttachedCallBundle(Call, BU);
3515 }
3516 }
3517
3518 // Verify that callee and callsite agree on whether to use pointer auth.
3519 Check(!(Call.getCalledFunction() && FoundPtrauthBundle),
3520 "Direct call cannot have a ptrauth bundle", Call);
3521
3522 // Verify that each inlinable callsite of a debug-info-bearing function in a
3523 // debug-info-bearing function has a debug location attached to it. Failure to
3524 // do so causes assertion failures when the inliner sets up inline scope info
3525 // (Interposable functions are not inlinable, neither are functions without
3526 // definitions.)
3527 if (Call.getFunction()->getSubprogram() && Call.getCalledFunction() &&
3528 !Call.getCalledFunction()->isInterposable() &&
3529 !Call.getCalledFunction()->isDeclaration() &&
3530 Call.getCalledFunction()->getSubprogram())
3531 CheckDI(Call.getDebugLoc(),
3532 "inlinable function call in a function with "
3533 "debug info must have a !dbg location",
3534 Call);
3535
3536 if (Call.isInlineAsm())
3537 verifyInlineAsmCall(Call);
3538
3539 visitInstruction(Call);
3540}
3541
3542void Verifier::verifyTailCCMustTailAttrs(const AttrBuilder &Attrs,
3543 StringRef Context) {
3544 Check(!Attrs.contains(Attribute::InAlloca),
3545 Twine("inalloca attribute not allowed in ") + Context);
3546 Check(!Attrs.contains(Attribute::InReg),
3547 Twine("inreg attribute not allowed in ") + Context);
3548 Check(!Attrs.contains(Attribute::SwiftError),
3549 Twine("swifterror attribute not allowed in ") + Context);
3550 Check(!Attrs.contains(Attribute::Preallocated),
3551 Twine("preallocated attribute not allowed in ") + Context);
3552 Check(!Attrs.contains(Attribute::ByRef),
3553 Twine("byref attribute not allowed in ") + Context);
3554}
3555
3556/// Two types are "congruent" if they are identical, or if they are both pointer
3557/// types with different pointee types and the same address space.
3558static bool isTypeCongruent(Type *L, Type *R) {
3559 if (L == R)
3560 return true;
3561 PointerType *PL = dyn_cast<PointerType>(L);
3562 PointerType *PR = dyn_cast<PointerType>(R);
3563 if (!PL || !PR)
3564 return false;
3565 return PL->getAddressSpace() == PR->getAddressSpace();
3566}
3567
3569 static const Attribute::AttrKind ABIAttrs[] = {
3570 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
3571 Attribute::InReg, Attribute::StackAlignment, Attribute::SwiftSelf,
3572 Attribute::SwiftAsync, Attribute::SwiftError, Attribute::Preallocated,
3573 Attribute::ByRef};
3574 AttrBuilder Copy(C);
3575 for (auto AK : ABIAttrs) {
3576 Attribute Attr = Attrs.getParamAttrs(I).getAttribute(AK);
3577 if (Attr.isValid())
3578 Copy.addAttribute(Attr);
3579 }
3580
3581 // `align` is ABI-affecting only in combination with `byval` or `byref`.
3582 if (Attrs.hasParamAttr(I, Attribute::Alignment) &&
3583 (Attrs.hasParamAttr(I, Attribute::ByVal) ||
3584 Attrs.hasParamAttr(I, Attribute::ByRef)))
3585 Copy.addAlignmentAttr(Attrs.getParamAlignment(I));
3586 return Copy;
3587}
3588
3589void Verifier::verifyMustTailCall(CallInst &CI) {
3590 Check(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
3591
3592 Function *F = CI.getParent()->getParent();
3593 FunctionType *CallerTy = F->getFunctionType();
3594 FunctionType *CalleeTy = CI.getFunctionType();
3595 Check(CallerTy->isVarArg() == CalleeTy->isVarArg(),
3596 "cannot guarantee tail call due to mismatched varargs", &CI);
3597 Check(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
3598 "cannot guarantee tail call due to mismatched return types", &CI);
3599
3600 // - The calling conventions of the caller and callee must match.
3601 Check(F->getCallingConv() == CI.getCallingConv(),
3602 "cannot guarantee tail call due to mismatched calling conv", &CI);
3603
3604 // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
3605 // or a pointer bitcast followed by a ret instruction.
3606 // - The ret instruction must return the (possibly bitcasted) value
3607 // produced by the call or void.
3608 Value *RetVal = &CI;
3609 Instruction *Next = CI.getNextNode();
3610
3611 // Handle the optional bitcast.
3612 if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
3613 Check(BI->getOperand(0) == RetVal,
3614 "bitcast following musttail call must use the call", BI);
3615 RetVal = BI;
3616 Next = BI->getNextNode();
3617 }
3618
3619 // Check the return.
3620 ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
3621 Check(Ret, "musttail call must precede a ret with an optional bitcast", &CI);
3622 Check(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal ||
3623 isa<UndefValue>(Ret->getReturnValue()),
3624 "musttail call result must be returned", Ret);
3625
3626 AttributeList CallerAttrs = F->getAttributes();
3627 AttributeList CalleeAttrs = CI.getAttributes();
3630 StringRef CCName =
3631 CI.getCallingConv() == CallingConv::Tail ? "tailcc" : "swifttailcc";
3632
3633 // - Only sret, byval, swiftself, and swiftasync ABI-impacting attributes
3634 // are allowed in swifttailcc call
3635 for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
3636 AttrBuilder ABIAttrs = getParameterABIAttributes(F->getContext(), I, CallerAttrs);
3637 SmallString<32> Context{CCName, StringRef(" musttail caller")};
3638 verifyTailCCMustTailAttrs(ABIAttrs, Context);
3639 }
3640 for (unsigned I = 0, E = CalleeTy->getNumParams(); I != E; ++I) {
3641 AttrBuilder ABIAttrs = getParameterABIAttributes(F->getContext(), I, CalleeAttrs);
3642 SmallString<32> Context{CCName, StringRef(" musttail callee")};
3643 verifyTailCCMustTailAttrs(ABIAttrs, Context);
3644 }
3645 // - Varargs functions are not allowed
3646 Check(!CallerTy->isVarArg(), Twine("cannot guarantee ") + CCName +
3647 " tail call for varargs function");
3648 return;
3649 }
3650
3651 // - The caller and callee prototypes must match. Pointer types of
3652 // parameters or return types may differ in pointee type, but not
3653 // address space.
3654 if (!CI.getCalledFunction() || !CI.getCalledFunction()->isIntrinsic()) {
3655 Check(CallerTy->getNumParams() == CalleeTy->getNumParams(),
3656 "cannot guarantee tail call due to mismatched parameter counts", &CI);
3657 for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
3658 Check(
3659 isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
3660 "cannot guarantee tail call due to mismatched parameter types", &CI);
3661 }
3662 }
3663
3664 // - All ABI-impacting function attributes, such as sret, byval, inreg,
3665 // returned, preallocated, and inalloca, must match.
3666 for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
3667 AttrBuilder CallerABIAttrs = getParameterABIAttributes(F->getContext(), I, CallerAttrs);
3668 AttrBuilder CalleeABIAttrs = getParameterABIAttributes(F->getContext(), I, CalleeAttrs);
3669 Check(CallerABIAttrs == CalleeABIAttrs,
3670 "cannot guarantee tail call due to mismatched ABI impacting "
3671 "function attributes",
3672 &CI, CI.getOperand(I));
3673 }
3674}
3675
3676void Verifier::visitCallInst(CallInst &CI) {
3677 visitCallBase(CI);
3678
3679 if (CI.isMustTailCall())
3680 verifyMustTailCall(CI);
3681}
3682
3683void Verifier::visitInvokeInst(InvokeInst &II) {
3684 visitCallBase(II);
3685
3686 // Verify that the first non-PHI instruction of the unwind destination is an
3687 // exception handling instruction.
3688 Check(
3689 II.getUnwindDest()->isEHPad(),
3690 "The unwind destination does not have an exception handling instruction!",
3691 &II);
3692
3693 visitTerminator(II);
3694}
3695
3696/// visitUnaryOperator - Check the argument to the unary operator.
3697///
3698void Verifier::visitUnaryOperator(UnaryOperator &U) {
3699 Check(U.getType() == U.getOperand(0)->getType(),
3700 "Unary operators must have same type for"
3701 "operands and result!",
3702 &U);
3703
3704 switch (U.getOpcode()) {
3705 // Check that floating-point arithmetic operators are only used with
3706 // floating-point operands.
3707 case Instruction::FNeg:
3708 Check(U.getType()->isFPOrFPVectorTy(),
3709 "FNeg operator only works with float types!", &U);
3710 break;
3711 default:
3712 llvm_unreachable("Unknown UnaryOperator opcode!");
3713 }
3714
3716}
3717
3718/// visitBinaryOperator - Check that both arguments to the binary operator are
3719/// of the same type!
3720///
3721void Verifier::visitBinaryOperator(BinaryOperator &B) {
3722 Check(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
3723 "Both operands to a binary operator are not of the same type!", &B);
3724
3725 switch (B.getOpcode()) {
3726 // Check that integer arithmetic operators are only used with
3727 // integral operands.
3728 case Instruction::Add:
3729 case Instruction::Sub:
3730 case Instruction::Mul:
3731 case Instruction::SDiv:
3732 case Instruction::UDiv:
3733 case Instruction::SRem:
3734 case Instruction::URem:
3735 Check(B.getType()->isIntOrIntVectorTy(),
3736 "Integer arithmetic operators only work with integral types!", &B);
3737 Check(B.getType() == B.getOperand(0)->getType(),
3738 "Integer arithmetic operators must have same type "
3739 "for operands and result!",
3740 &B);
3741 break;
3742 // Check that floating-point arithmetic operators are only used with
3743 // floating-point operands.
3744 case Instruction::FAdd:
3745 case Instruction::FSub:
3746 case Instruction::FMul:
3747 case Instruction::FDiv:
3748 case Instruction::FRem:
3749 Check(B.getType()->isFPOrFPVectorTy(),
3750 "Floating-point arithmetic operators only work with "
3751 "floating-point types!",
3752 &B);
3753 Check(B.getType() == B.getOperand(0)->getType(),
3754 "Floating-point arithmetic operators must have same type "
3755 "for operands and result!",
3756 &B);
3757 break;
3758 // Check that logical operators are only used with integral operands.
3759 case Instruction::And:
3760 case Instruction::Or:
3761 case Instruction::Xor:
3762 Check(B.getType()->isIntOrIntVectorTy(),
3763 "Logical operators only work with integral types!", &B);
3764 Check(B.getType() == B.getOperand(0)->getType(),
3765 "Logical operators must have same type for operands and result!", &B);
3766 break;
3767 case Instruction::Shl:
3768 case Instruction::LShr:
3769 case Instruction::AShr:
3770 Check(B.getType()->isIntOrIntVectorTy(),
3771 "Shifts only work with integral types!", &B);
3772 Check(B.getType() == B.getOperand(0)->getType(),
3773 "Shift return type must be same as operands!", &B);
3774 break;
3775 default:
3776 llvm_unreachable("Unknown BinaryOperator opcode!");
3777 }
3778
3780}
3781
3782void Verifier::visitICmpInst(ICmpInst &IC) {
3783 // Check that the operands are the same type
3784 Type *Op0Ty = IC.getOperand(0)->getType();
3785 Type *Op1Ty = IC.getOperand(1)->getType();
3786 Check(Op0Ty == Op1Ty,
3787 "Both operands to ICmp instruction are not of the same type!", &IC);
3788 // Check that the operands are the right type
3789 Check(Op0Ty->isIntOrIntVectorTy() || Op0Ty->isPtrOrPtrVectorTy(),
3790 "Invalid operand types for ICmp instruction", &IC);
3791 // Check that the predicate is valid.
3792 Check(IC.isIntPredicate(), "Invalid predicate in ICmp instruction!", &IC);
3793
3794 visitInstruction(IC);
3795}
3796
3797void Verifier::visitFCmpInst(FCmpInst &FC) {
3798 // Check that the operands are the same type
3799 Type *Op0Ty = FC.getOperand(0)->getType();
3800 Type *Op1Ty = FC.getOperand(1)->getType();
3801 Check(Op0Ty == Op1Ty,
3802 "Both operands to FCmp instruction are not of the same type!", &FC);
3803 // Check that the operands are the right type
3804 Check(Op0Ty->isFPOrFPVectorTy(), "Invalid operand types for FCmp instruction",
3805 &FC);
3806 // Check that the predicate is valid.
3807 Check(FC.isFPPredicate(), "Invalid predicate in FCmp instruction!", &FC);
3808
3809 visitInstruction(FC);
3810}
3811
3812void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
3814 "Invalid extractelement operands!", &EI);
3815 visitInstruction(EI);
3816}
3817
3818void Verifier::visitInsertElementInst(InsertElementInst &IE) {
3819 Check(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
3820 IE.getOperand(2)),
3821 "Invalid insertelement operands!", &IE);
3822 visitInstruction(IE);
3823}
3824
3825void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
3827 SV.getShuffleMask()),
3828 "Invalid shufflevector operands!", &SV);
3829 visitInstruction(SV);
3830}
3831
3832void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
3833 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
3834
3835 Check(isa<PointerType>(TargetTy),
3836 "GEP base pointer is not a vector or a vector of pointers", &GEP);
3837 Check(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP);
3838
3839 SmallVector<Value *, 16> Idxs(GEP.indices());
3840 Check(
3841 all_of(Idxs, [](Value *V) { return V->getType()->isIntOrIntVectorTy(); }),
3842 "GEP indexes must be integers", &GEP);
3843 Type *ElTy =
3844 GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs);
3845 Check(ElTy, "Invalid indices for GEP pointer type!", &GEP);
3846
3847 Check(GEP.getType()->isPtrOrPtrVectorTy() &&
3848 GEP.getResultElementType() == ElTy,
3849 "GEP is not of right type for indices!", &GEP, ElTy);
3850
3851 if (auto *GEPVTy = dyn_cast<VectorType>(GEP.getType())) {
3852 // Additional checks for vector GEPs.
3853 ElementCount GEPWidth = GEPVTy->getElementCount();
3854 if (GEP.getPointerOperandType()->isVectorTy())
3855 Check(
3856 GEPWidth ==
3857 cast<VectorType>(GEP.getPointerOperandType())->getElementCount(),
3858 "Vector GEP result width doesn't match operand's", &GEP);
3859 for (Value *Idx : Idxs) {
3860 Type *IndexTy = Idx->getType();
3861 if (auto *IndexVTy = dyn_cast<VectorType>(IndexTy)) {
3862 ElementCount IndexWidth = IndexVTy->getElementCount();
3863 Check(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP);
3864 }
3865 Check(IndexTy->isIntOrIntVectorTy(),
3866 "All GEP indices should be of integer type");
3867 }
3868 }
3869
3870 if (auto *PTy = dyn_cast<PointerType>(GEP.getType())) {
3871 Check(GEP.getAddressSpace() == PTy->getAddressSpace(),
3872 "GEP address space doesn't match type", &GEP);
3873 }
3874
3876}
3877
3878static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
3879 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
3880}
3881
3882void Verifier::visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty) {
3883 assert(Range && Range == I.getMetadata(LLVMContext::MD_range) &&
3884 "precondition violation");
3885
3886 unsigned NumOperands = Range->getNumOperands();
3887 Check(NumOperands % 2 == 0, "Unfinished range!", Range);
3888 unsigned NumRanges = NumOperands / 2;
3889 Check(NumRanges >= 1, "It should have at least one range!", Range);
3890
3891 ConstantRange LastRange(1, true); // Dummy initial value
3892 for (unsigned i = 0; i < NumRanges; ++i) {
3893 ConstantInt *Low =
3894 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
3895 Check(Low, "The lower limit must be an integer!", Low);
3896 ConstantInt *High =
3897 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
3898 Check(High, "The upper limit must be an integer!", High);
3899 Check(High->getType() == Low->getType() &&
3900 High->getType() == Ty->getScalarType(),
3901 "Range types must match instruction type!", &I);
3902
3903 APInt HighV = High->getValue();
3904 APInt LowV = Low->getValue();
3905 ConstantRange CurRange(LowV, HighV);
3906 Check(!CurRange.isEmptySet() && !CurRange.isFullSet(),
3907 "Range must not be empty!", Range);
3908 if (i != 0) {
3909 Check(CurRange.intersectWith(LastRange).isEmptySet(),
3910 "Intervals are overlapping", Range);
3911 Check(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
3912 Range);
3913 Check(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
3914 Range);
3915 }
3916 LastRange = ConstantRange(LowV, HighV);
3917 }
3918 if (NumRanges > 2) {
3919 APInt FirstLow =
3920 mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
3921 APInt FirstHigh =
3922 mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
3923 ConstantRange FirstRange(FirstLow, FirstHigh);
3924 Check(FirstRange.intersectWith(LastRange).isEmptySet(),
3925 "Intervals are overlapping", Range);
3926 Check(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
3927 Range);
3928 }
3929}
3930
3931void Verifier::checkAtomicMemAccessSize(Type *Ty, const Instruction *I) {
3932 unsigned Size = DL.getTypeSizeInBits(Ty);
3933 Check(Size >= 8, "atomic memory access' size must be byte-sized", Ty, I);
3934 Check(!(Size & (Size - 1)),
3935 "atomic memory access' operand must have a power-of-two size", Ty, I);
3936}
3937
3938void Verifier::visitLoadInst(LoadInst &LI) {
3939 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
3940 Check(PTy, "Load operand must be a pointer.", &LI);
3941 Type *ElTy = LI.getType();
3942 if (MaybeAlign A = LI.getAlign()) {
3943 Check(A->value() <= Value::MaximumAlignment,
3944 "huge alignment values are unsupported", &LI);
3945 }
3946 Check(ElTy->isSized(), "loading unsized types is not allowed", &LI);
3947 if (LI.isAtomic()) {
3950 "Load cannot have Release ordering", &LI);
3951 Check(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(),
3952 "atomic load operand must have integer, pointer, or floating point "
3953 "type!",
3954 ElTy, &LI);
3955 checkAtomicMemAccessSize(ElTy, &LI);
3956 } else {
3958 "Non-atomic load cannot have SynchronizationScope specified", &LI);
3959 }
3960
3961 visitInstruction(LI);
3962}
3963
3964void Verifier::visitStoreInst(StoreInst &SI) {
3965 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
3966 Check(PTy, "Store operand must be a pointer.", &SI);
3967 Type *ElTy = SI.getOperand(0)->getType();
3968 Check(PTy->isOpaqueOrPointeeTypeMatches(ElTy),
3969 "Stored value type does not match pointer operand type!", &SI, ElTy);
3970 if (MaybeAlign A = SI.getAlign()) {
3971 Check(A->value() <= Value::MaximumAlignment,
3972 "huge alignment values are unsupported", &SI);
3973 }
3974 Check(ElTy->isSized(), "storing unsized types is not allowed", &SI);
3975 if (SI.isAtomic()) {
3976 Check(SI.getOrdering() != AtomicOrdering::Acquire &&
3977 SI.getOrdering() != AtomicOrdering::AcquireRelease,
3978 "Store cannot have Acquire ordering", &SI);
3979 Check(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(),
3980 "atomic store operand must have integer, pointer, or floating point "
3981 "type!",
3982 ElTy, &SI);
3983 checkAtomicMemAccessSize(ElTy, &SI);
3984 } else {
3985 Check(SI.getSyncScopeID() == SyncScope::System,
3986 "Non-atomic store cannot have SynchronizationScope specified", &SI);
3987 }
3988 visitInstruction(SI);
3989}
3990
3991/// Check that SwiftErrorVal is used as a swifterror argument in CS.
3992void Verifier::verifySwiftErrorCall(CallBase &Call,
3993 const Value *SwiftErrorVal) {
3994 for (const auto &I : llvm::enumerate(Call.args())) {
3995 if (I.value() == SwiftErrorVal) {
3996 Check(Call.paramHasAttr(I.index(), Attribute::SwiftError),
3997 "swifterror value when used in a callsite should be marked "
3998 "with swifterror attribute",
3999 SwiftErrorVal, Call);
4000 }
4001 }
4002}
4003
4004void Verifier::verifySwiftErrorValue(const Value *SwiftErrorVal) {
4005 // Check that swifterror value is only used by loads, stores, or as
4006 // a swifterror argument.
4007 for (const User *U : SwiftErrorVal->users()) {
4008 Check(isa<LoadInst>(U) || isa<StoreInst>(U) || isa<CallInst>(U) ||
4009 isa<InvokeInst>(U),
4010 "swifterror value can only be loaded and stored from, or "
4011 "as a swifterror argument!",
4012 SwiftErrorVal, U);
4013 // If it is used by a store, check it is the second operand.
4014 if (auto StoreI = dyn_cast<StoreInst>(U))
4015 Check(StoreI->getOperand(1) == SwiftErrorVal,
4016 "swifterror value should be the second operand when used "
4017 "by stores",
4018 SwiftErrorVal, U);
4019 if (auto *Call = dyn_cast<CallBase>(U))
4020 verifySwiftErrorCall(*const_cast<CallBase *>(Call), SwiftErrorVal);
4021 }
4022}
4023
4024void Verifier::visitAllocaInst(AllocaInst &AI) {
4025 SmallPtrSet<Type*, 4> Visited;
4026 Check(AI.getAllocatedType()->isSized(&Visited),
4027 "Cannot allocate unsized type", &AI);
4029 "Alloca array size must have integer type", &AI);
4030 if (MaybeAlign A = AI.getAlign()) {
4031 Check(A->value() <= Value::MaximumAlignment,
4032 "huge alignment values are unsupported", &AI);
4033 }
4034
4035 if (AI.isSwiftError()) {
4037 "swifterror alloca must have pointer type", &AI);
4039 "swifterror alloca must not be array allocation", &AI);
4040 verifySwiftErrorValue(&AI);
4041 }
4042
4043 visitInstruction(AI);
4044}
4045
4046void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
4047 Type *ElTy = CXI.getOperand(1)->getType();
4048 Check(ElTy->isIntOrPtrTy(),
4049 "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
4050 checkAtomicMemAccessSize(ElTy, &CXI);
4051 visitInstruction(CXI);
4052}
4053
4054void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
4056 "atomicrmw instructions cannot be unordered.", &RMWI);
4057 auto Op = RMWI.getOperation();
4058 Type *ElTy = RMWI.getOperand(1)->getType();
4059 if (Op == AtomicRMWInst::Xchg) {
4060 Check(ElTy->isIntegerTy() || ElTy->isFloatingPointTy() ||
4061 ElTy->isPointerTy(),
4062 "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
4063 " operand must have integer or floating point type!",
4064 &RMWI, ElTy);
4065 } else if (AtomicRMWInst::isFPOperation(Op)) {
4066 Check(ElTy->isFloatingPointTy(),
4067 "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
4068 " operand must have floating point type!",
4069 &RMWI, ElTy);
4070 } else {
4071 Check(ElTy->isIntegerTy(),
4072 "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
4073 " operand must have integer type!",
4074 &RMWI, ElTy);
4075 }
4076 checkAtomicMemAccessSize(ElTy, &RMWI);
4078 "Invalid binary operation!", &RMWI);
4079 visitInstruction(RMWI);
4080}
4081
4082void Verifier::visitFenceInst(FenceInst &FI) {
4083 const AtomicOrdering Ordering = FI.getOrdering();
4084 Check(Ordering == AtomicOrdering::Acquire ||
4085 Ordering == AtomicOrdering::Release ||
4086 Ordering == AtomicOrdering::AcquireRelease ||
4088 "fence instructions may only have acquire, release, acq_rel, or "
4089 "seq_cst ordering.",
4090 &FI);
4091 visitInstruction(FI);
4092}
4093
4094void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
4096 EVI.getIndices()) == EVI.getType(),
4097 "Invalid ExtractValueInst operands!", &EVI);
4098
4099 visitInstruction(EVI);
4100}
4101
4102void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
4104 IVI.getIndices()) ==
4105 IVI.getOperand(1)->getType(),
4106 "Invalid InsertValueInst operands!", &IVI);
4107
4108 visitInstruction(IVI);
4109}
4110
4111static Value *getParentPad(Value *EHPad) {
4112 if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
4113 return FPI->getParentPad();
4114
4115 return cast<CatchSwitchInst>(EHPad)->getParentPad();
4116}
4117
4118void Verifier::visitEHPadPredecessors(Instruction &I) {
4119 assert(I.isEHPad());
4120
4121 BasicBlock *BB = I.getParent();
4122 Function *F = BB->getParent();
4123
4124 Check(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I);
4125
4126 if (auto *LPI = dyn_cast<LandingPadInst>(&I)) {
4127 // The landingpad instruction defines its parent as a landing pad block. The
4128 // landing pad block may be branched to only by the unwind edge of an
4129 // invoke.
4130 for (BasicBlock *PredBB : predecessors(BB)) {
4131 const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator());
4132 Check(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
4133 "Block containing LandingPadInst must be jumped to "
4134 "only by the unwind edge of an invoke.",
4135 LPI);
4136 }
4137 return;
4138 }
4139 if (auto *CPI = dyn_cast<CatchPadInst>(&I)) {
4140 if (!pred_empty(BB))
4141 Check(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(),
4142 "Block containg CatchPadInst must be jumped to "
4143 "only by its catchswitch.",
4144 CPI);
4145 Check(BB != CPI->getCatchSwitch()->getUnwindDest(),
4146 "Catchswitch cannot unwind to one of its catchpads",
4147 CPI->getCatchSwitch(), CPI);
4148 return;
4149 }
4150
4151 // Verify that each pred has a legal terminator with a legal to/from EH
4152 // pad relationship.
4153 Instruction *ToPad = &I;
4154 Value *ToPadParent = getParentPad(ToPad);
4155 for (BasicBlock *PredBB : predecessors(BB)) {
4156 Instruction *TI = PredBB->getTerminator();
4157 Value *FromPad;
4158 if (auto *II = dyn_cast<InvokeInst>(TI)) {
4159 Check(II->getUnwindDest() == BB && II->getNormalDest() != BB,
4160 "EH pad must be jumped to via an unwind edge", ToPad, II);
4161 if (auto Bundle = II->getOperandBundle(LLVMContext::OB_funclet))
4162 FromPad = Bundle->Inputs[0];
4163 else
4164 FromPad = ConstantTokenNone::get(II->getContext());
4165 } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
4166 FromPad = CRI->getOperand(0);
4167 Check(FromPad != ToPadParent, "A cleanupret must exit its cleanup", CRI);
4168 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
4169 FromPad = CSI;
4170 } else {
4171 Check(false, "EH pad must be jumped to via an unwind edge", ToPad, TI);
4172 }
4173
4174 // The edge may exit from zero or more nested pads.
4176 for (;; FromPad = getParentPad(FromPad)) {
4177 Check(FromPad != ToPad,
4178 "EH pad cannot handle exceptions raised within it", FromPad, TI);
4179 if (FromPad == ToPadParent) {
4180 // This is a legal unwind edge.
4181 break;
4182 }
4183 Check(!isa<ConstantTokenNone>(FromPad),
4184 "A single unwind edge may only enter one EH pad", TI);
4185 Check(Seen.insert(FromPad).second, "EH pad jumps through a cycle of pads",
4186 FromPad);
4187
4188 // This will be diagnosed on the corresponding instruction already. We
4189 // need the extra check here to make sure getParentPad() works.
4190 Check(isa<FuncletPadInst>(FromPad) || isa<CatchSwitchInst>(FromPad),
4191 "Parent pad must be catchpad/cleanuppad/catchswitch", TI);
4192 }
4193 }
4194}
4195
4196void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
4197 // The landingpad instruction is ill-formed if it doesn't have any clauses and
4198 // isn't a cleanup.
4199 Check(LPI.getNumClauses() > 0 || LPI.isCleanup(),
4200 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
4201
4202 visitEHPadPredecessors(LPI);
4203
4204 if (!LandingPadResultTy)
4205 LandingPadResultTy = LPI.getType();
4206 else
4207 Check(LandingPadResultTy == LPI.getType(),
4208 "The landingpad instruction should have a consistent result type "
4209 "inside a function.",
4210 &LPI);
4211
4212 Function *F = LPI.getParent()->getParent();
4213 Check(F->hasPersonalityFn(),
4214 "LandingPadInst needs to be in a function with a personality.", &LPI);
4215
4216 // The landingpad instruction must be the first non-PHI instruction in the
4217 // block.
4218 Check(LPI.getParent()->getLandingPadInst() == &LPI,
4219 "LandingPadInst not the first non-PHI instruction in the block.", &LPI);
4220
4221 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
4222 Constant *Clause = LPI.getClause(i);
4223 if (LPI.isCatch(i)) {
4224 Check(isa<PointerType>(Clause->getType()),
4225 "Catch operand does not have pointer type!", &LPI);
4226 } else {
4227 Check(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
4228 Check(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
4229 "Filter operand is not an array of constants!", &LPI);
4230 }
4231 }
4232
4233 visitInstruction(LPI);
4234}
4235
4236void Verifier::visitResumeInst(ResumeInst &RI) {
4238 "ResumeInst needs to be in a function with a personality.", &RI);
4239
4240 if (!LandingPadResultTy)
4241 LandingPadResultTy = RI.getValue()->getType();
4242 else
4243 Check(LandingPadResultTy == RI.getValue()->getType(),
4244 "The resume instruction should have a consistent result type "
4245 "inside a function.",
4246 &RI);
4247
4248 visitTerminator(RI);
4249}
4250
4251void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
4252 BasicBlock *BB = CPI.getParent();
4253
4254 Function *F = BB->getParent();
4255 Check(F->hasPersonalityFn(),
4256 "CatchPadInst needs to be in a function with a personality.", &CPI);
4257
4258 Check(isa<CatchSwitchInst>(CPI.getParentPad()),
4259 "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
4260 CPI.getParentPad());
4261
4262 // The catchpad instruction must be the first non-PHI instruction in the
4263 // block.
4264 Check(BB->getFirstNonPHI() == &CPI,
4265 "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
4266
4267 visitEHPadPredecessors(CPI);
4269}
4270
4271void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
4272 Check(isa<CatchPadInst>(CatchReturn.getOperand(0)),
4273 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
4274 CatchReturn.getOperand(0));
4275
4276 visitTerminator(CatchReturn);
4277}
4278
4279void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
4280 BasicBlock *BB = CPI.getParent();
4281
4282 Function *F = BB->getParent();
4283 Check(F->hasPersonalityFn(),
4284 "CleanupPadInst needs to be in a function with a personality.", &CPI);
4285
4286 // The cleanuppad instruction must be the first non-PHI instruction in the
4287 // block.
4288 Check(BB->getFirstNonPHI() == &CPI,
4289 "CleanupPadInst not the first non-PHI instruction in the block.", &CPI);
4290
4291 auto *ParentPad = CPI.getParentPad();
4292 Check(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
4293 "CleanupPadInst has an invalid parent.", &CPI);
4294
4295 visitEHPadPredecessors(CPI);
4297}
4298
4299void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
4300 User *FirstUser = nullptr;
4301 Value *FirstUnwindPad = nullptr;
4302 SmallVector<FuncletPadInst *, 8> Worklist({&FPI});
4304
4305 while (!Worklist.empty()) {
4306 FuncletPadInst *CurrentPad = Worklist.pop_back_val();
4307 Check(Seen.insert(CurrentPad).second,
4308 "FuncletPadInst must not be nested within itself", CurrentPad);
4309 Value *UnresolvedAncestorPad = nullptr;
4310 for (User *U : CurrentPad->users()) {
4311 BasicBlock *UnwindDest;
4312 if (auto *CRI = dyn_cast<CleanupReturnInst>(U)) {
4313 UnwindDest = CRI->getUnwindDest();
4314 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(U)) {
4315 // We allow catchswitch unwind to caller to nest
4316 // within an outer pad that unwinds somewhere else,
4317 // because catchswitch doesn't have a nounwind variant.
4318 // See e.g. SimplifyCFGOpt::SimplifyUnreachable.
4319 if (CSI->unwindsToCaller())
4320 continue;
4321 UnwindDest = CSI->getUnwindDest();
4322 } else if (auto *II = dyn_cast<InvokeInst>(U)) {
4323 UnwindDest = II->getUnwindDest();
4324 } else if (isa<CallInst>(U)) {
4325 // Calls which don't unwind may be found inside funclet
4326 // pads that unwind somewhere else. We don't *require*
4327 // such calls to be annotated nounwind.
4328 continue;
4329 } else if (auto *CPI = dyn_cast<CleanupPadInst>(U)) {
4330 // The unwind dest for a cleanup can only be found by
4331 // recursive search. Add it to the worklist, and we'll
4332 // search for its first use that determines where it unwinds.
4333 Worklist.push_back(CPI);
4334 continue;
4335 } else {
4336 Check(isa<CatchReturnInst>(U), "Bogus funclet pad use", U);
4337 continue;
4338 }
4339
4340 Value *UnwindPad;
4341 bool ExitsFPI;
4342 if (UnwindDest) {
4343 UnwindPad = UnwindDest->getFirstNonPHI();
4344 if (!cast<Instruction>(UnwindPad)->isEHPad())
4345 continue;
4346 Value *UnwindParent = getParentPad(UnwindPad);
4347 // Ignore unwind edges that don't exit CurrentPad.
4348 if (UnwindParent == CurrentPad)
4349 continue;
4350 // Determine whether the original funclet pad is exited,
4351 // and if we are scanning nested pads determine how many
4352 // of them are exited so we can stop searching their
4353 // children.
4354 Value *ExitedPad = CurrentPad;
4355 ExitsFPI = false;
4356 do {
4357 if (ExitedPad == &FPI) {
4358 ExitsFPI = true;
4359 // Now we can resolve any ancestors of CurrentPad up to
4360 // FPI, but not including FPI since we need to make sure
4361 // to check all direct users of FPI for consistency.
4362 UnresolvedAncestorPad = &FPI;
4363 break;
4364 }
4365 Value *ExitedParent = getParentPad(ExitedPad);
4366 if (ExitedParent == UnwindParent) {
4367 // ExitedPad is the ancestor-most pad which this unwind
4368 // edge exits, so we can resolve up to it, meaning that
4369 // ExitedParent is the first ancestor still unresolved.
4370 UnresolvedAncestorPad = ExitedParent;
4371 break;
4372 }
4373 ExitedPad = ExitedParent;
4374 } while (!isa<ConstantTokenNone>(ExitedPad));
4375 } else {
4376 // Unwinding to caller exits all pads.
4377 UnwindPad = ConstantTokenNone::get(FPI.getContext());
4378 ExitsFPI = true;
4379 UnresolvedAncestorPad = &FPI;
4380 }
4381
4382 if (ExitsFPI) {
4383 // This unwind edge exits FPI. Make sure it agrees with other
4384 // such edges.
4385 if (FirstUser) {
4386 Check(UnwindPad == FirstUnwindPad,
4387 "Unwind edges out of a funclet "
4388 "pad must have the same unwind "
4389 "dest",
4390 &FPI, U, FirstUser);
4391 } else {
4392 FirstUser = U;
4393 FirstUnwindPad = UnwindPad;
4394 // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds
4395 if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) &&
4396 getParentPad(UnwindPad) == getParentPad(&FPI))
4397 SiblingFuncletInfo[&FPI] = cast<Instruction>(U);
4398 }
4399 }
4400 // Make sure we visit all uses of FPI, but for nested pads stop as
4401 // soon as we know where they unwind to.
4402 if (CurrentPad != &FPI)
4403 break;
4404 }
4405 if (UnresolvedAncestorPad) {
4406 if (CurrentPad == UnresolvedAncestorPad) {
4407 // When CurrentPad is FPI itself, we don't mark it as resolved even if
4408 // we've found an unwind edge that exits it, because we need to verify
4409 // all direct uses of FPI.
4410 assert(CurrentPad == &FPI);
4411 continue;
4412 }
4413 // Pop off the worklist any nested pads that we've found an unwind
4414 // destination for. The pads on the worklist are the uncles,
4415 // great-uncles, etc. of CurrentPad. We've found an unwind destination
4416 // for all ancestors of CurrentPad up to but not including
4417 // UnresolvedAncestorPad.
4418 Value *ResolvedPad = CurrentPad;
4419 while (!Worklist.empty()) {
4420 Value *UnclePad = Worklist.back();
4421 Value *AncestorPad = getParentPad(UnclePad);
4422 // Walk ResolvedPad up the ancestor list until we either find the
4423 // uncle's parent or the last resolved ancestor.
4424 while (ResolvedPad != AncestorPad) {
4425 Value *ResolvedParent = getParentPad(ResolvedPad);
4426 if (ResolvedParent == UnresolvedAncestorPad) {
4427 break;
4428 }
4429 ResolvedPad = ResolvedParent;
4430 }
4431 // If the resolved ancestor search didn't find the uncle's parent,
4432 // then the uncle is not yet resolved.
4433 if (ResolvedPad != AncestorPad)
4434 break;
4435 // This uncle is resolved, so pop it from the worklist.
4436 Worklist.pop_back();
4437 }
4438 }
4439 }
4440
4441 if (FirstUnwindPad) {
4442 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.getParentPad())) {
4443 BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
4444 Value *SwitchUnwindPad;
4445 if (SwitchUnwindDest)
4446 SwitchUnwindPad = SwitchUnwindDest->getFirstNonPHI();
4447 else
4448 SwitchUnwindPad = ConstantTokenNone::get(FPI.getContext());
4449 Check(SwitchUnwindPad == FirstUnwindPad,
4450 "Unwind edges out of a catch must have the same unwind dest as "
4451 "the parent catchswitch",
4452 &FPI, FirstUser, CatchSwitch);
4453 }
4454 }
4455
4456 visitInstruction(FPI);
4457}
4458
4459void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
4460 BasicBlock *BB = CatchSwitch.getParent();
4461
4462 Function *F = BB->getParent();
4463 Check(F->hasPersonalityFn(),
4464 "CatchSwitchInst needs to be in a function with a personality.",
4465 &CatchSwitch);
4466
4467 // The catchswitch instruction must be the first non-PHI instruction in the
4468 // block.
4469 Check(BB->getFirstNonPHI() == &CatchSwitch,
4470 "CatchSwitchInst not the first non-PHI instruction in the block.",
4471 &CatchSwitch);
4472
4473 auto *ParentPad = CatchSwitch.getParentPad();
4474 Check(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
4475 "CatchSwitchInst has an invalid parent.", ParentPad);
4476
4477 if (BasicBlock *UnwindDest = CatchSwitch.getUnwindDest()) {
4478 Instruction *I = UnwindDest->getFirstNonPHI();
4479 Check(I->isEHPad() && !isa<LandingPadInst>(I),
4480 "CatchSwitchInst must unwind to an EH block which is not a "
4481 "landingpad.",
4482 &CatchSwitch);
4483
4484 // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds
4485 if (getParentPad(I) == ParentPad)
4486 SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
4487 }
4488
4489 Check(CatchSwitch.getNumHandlers() != 0,
4490 "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
4491
4492 for (BasicBlock *Handler : CatchSwitch.handlers()) {
4493 Check(isa<CatchPadInst>(Handler->getFirstNonPHI()),
4494 "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
4495 }
4496
4497 visitEHPadPredecessors(CatchSwitch);
4498 visitTerminator(CatchSwitch);
4499}
4500
4501void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
4502 Check(isa<CleanupPadInst>(CRI.getOperand(0)),
4503 "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
4504 CRI.getOperand(0));
4505
4506 if (BasicBlock *UnwindDest = CRI.getUnwindDest()) {
4507 Instruction *I = UnwindDest->getFirstNonPHI();
4508 Check(I->isEHPad() && !isa<LandingPadInst>(I),
4509 "CleanupReturnInst must unwind to an EH block which is not a "
4510 "landingpad.",
4511 &CRI);
4512 }
4513
4514 visitTerminator(CRI);
4515}
4516
4517void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
4518 Instruction *Op = cast<Instruction>(I.getOperand(i));
4519 // If the we have an invalid invoke, don't try to compute the dominance.
4520 // We already reject it in the invoke specific checks and the dominance
4521 // computation doesn't handle multiple edges.
4522 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
4523 if (II->getNormalDest() == II->getUnwindDest())
4524 return;
4525 }
4526
4527 // Quick check whether the def has already been encountered in the same block.
4528 // PHI nodes are not checked to prevent accepting preceding PHIs, because PHI
4529 // uses are defined to happen on the incoming edge, not at the instruction.
4530 //
4531 // FIXME: If this operand is a MetadataAsValue (wrapping a LocalAsMetadata)
4532 // wrapping an SSA value, assert that we've already encountered it. See
4533 // related FIXME in Mapper::mapLocalAsMetadata in ValueMapper.cpp.
4534 if (!isa<PHINode>(I) && InstsInThisBlock.count(Op))
4535 return;
4536
4537 const Use &U = I.getOperandUse(i);
4538 Check(DT.dominates(Op, U), "Instruction does not dominate all uses!", Op, &I);
4539}
4540
4541void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) {
4542 Check(I.getType()->isPointerTy(),
4543 "dereferenceable, dereferenceable_or_null "
4544 "apply only to pointer types",
4545 &I);
4546 Check((isa<LoadInst>(I) || isa<IntToPtrInst>(I)),
4547 "dereferenceable, dereferenceable_or_null apply only to load"
4548 " and inttoptr instructions, use attributes for calls or invokes",
4549 &I);
4550 Check(MD->getNumOperands() == 1,
4551 "dereferenceable, dereferenceable_or_null "
4552 "take one operand!",
4553 &I);
4554 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
4555 Check(CI && CI->getType()->isIntegerTy(64),
4556 "dereferenceable, "
4557 "dereferenceable_or_null metadata value must be an i64!",
4558 &I);
4559}
4560
4561void Verifier::visitProfMetadata(Instruction &I, MDNode *MD) {
4562 Check(MD->getNumOperands() >= 2,
4563 "!prof annotations should have no less than 2 operands", MD);
4564
4565 // Check first operand.
4566 Check(MD->getOperand(0) != nullptr, "first operand should not be null", MD);
4567 Check(isa<MDString>(MD->getOperand(0)),
4568 "expected string with name of the !prof annotation", MD);
4569 MDString *MDS = cast<MDString>(MD->getOperand(0));
4570 StringRef ProfName = MDS->getString();
4571
4572 // Check consistency of !prof branch_weights metadata.
4573 if (ProfName.equals("branch_weights")) {
4574 if (isa<InvokeInst>(&I)) {
4575 Check(MD->getNumOperands() == 2 || MD->getNumOperands() == 3,
4576 "Wrong number of InvokeInst branch_weights operands", MD);
4577 } else {
4578 unsigned ExpectedNumOperands = 0;
4579 if (BranchInst *BI = dyn_cast<BranchInst>(&I))
4580 ExpectedNumOperands = BI->getNumSuccessors();
4581 else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
4582 ExpectedNumOperands = SI->getNumSuccessors();
4583 else if (isa<CallInst>(&I))
4584 ExpectedNumOperands = 1;
4585 else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
4586 ExpectedNumOperands = IBI->getNumDestinations();
4587 else if (isa<SelectInst>(&I))
4588 ExpectedNumOperands = 2;
4589 else if (CallBrInst *CI = dyn_cast<CallBrInst>(&I))
4590 ExpectedNumOperands = CI->getNumSuccessors();
4591 else
4592 CheckFailed("!prof branch_weights are not allowed for this instruction",
4593 MD);
4594
4595 Check(MD->getNumOperands() == 1 + ExpectedNumOperands,
4596 "Wrong number of operands", MD);
4597 }
4598 for (unsigned i = 1; i < MD->getNumOperands(); ++i) {
4599 auto &MDO = MD->getOperand(i);
4600 Check(MDO, "second operand should not be null", MD);
4601 Check(mdconst::dyn_extract<ConstantInt>(MDO),
4602 "!prof brunch_weights operand is not a const int");
4603 }
4604 }
4605}
4606
4607void Verifier::visitDIAssignIDMetadata(Instruction &I, MDNode *MD) {
4608 assert(I.hasMetadata(LLVMContext::MD_DIAssignID));
4609 bool ExpectedInstTy =
4610 isa<AllocaInst>(I) || isa<StoreInst>(I) || isa<MemIntrinsic>(I);
4611 CheckDI(ExpectedInstTy, "!DIAssignID attached to unexpected instruction kind",
4612 I, MD);
4613 // Iterate over the MetadataAsValue uses of the DIAssignID - these should
4614 // only be found as DbgAssignIntrinsic operands.
4615 if (auto *AsValue = MetadataAsValue::getIfExists(Context, MD)) {
4616 for (auto *User : AsValue->users()) {
4617 CheckDI(isa<DbgAssignIntrinsic>(User),
4618 "!DIAssignID should only be used by llvm.dbg.assign intrinsics",
4619 MD, User);
4620 // All of the dbg.assign intrinsics should be in the same function as I.
4621 if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(User))
4622 CheckDI(DAI->getFunction() == I.getFunction(),
4623 "dbg.assign not in same function as inst", DAI, &I);
4624 }
4625 }
4626}
4627
4628void Verifier::visitCallStackMetadata(MDNode *MD) {
4629 // Call stack metadata should consist of a list of at least 1 constant int
4630 // (representing a hash of the location).
4631 Check(MD->getNumOperands() >= 1,
4632 "call stack metadata should have at least 1 operand", MD);
4633
4634 for (const auto &Op : MD->operands())
4635 Check(mdconst::dyn_extract_or_null<ConstantInt>(Op),
4636 "call stack metadata operand should be constant integer", Op);
4637}
4638
4639void Verifier::visitMemProfMetadata(Instruction &I, MDNode *MD) {
4640 Check(isa<CallBase>(I), "!memprof metadata should only exist on calls", &I);
4641 Check(MD->getNumOperands() >= 1,
4642 "!memprof annotations should have at least 1 metadata operand "
4643 "(MemInfoBlock)",
4644 MD);
4645
4646 // Check each MIB
4647 for (auto &MIBOp : MD->operands()) {
4648 MDNode *MIB = dyn_cast<MDNode>(MIBOp);
4649 // The first operand of an MIB should be the call stack metadata.
4650 // There rest of the operands should be MDString tags, and there should be
4651 // at least one.
4652 Check(MIB->getNumOperands() >= 2,
4653 "Each !memprof MemInfoBlock should have at least 2 operands", MIB);
4654
4655 // Check call stack metadata (first operand).
4656 Check(MIB->getOperand(0) != nullptr,
4657 "!memprof MemInfoBlock first operand should not be null", MIB);
4658 Check(isa<MDNode>(MIB->getOperand(0)),
4659 "!memprof MemInfoBlock first operand should be an MDNode", MIB);
4660 MDNode *StackMD = dyn_cast<MDNode>(MIB->getOperand(0));
4661 visitCallStackMetadata(StackMD);
4662
4663 // Check that remaining operands are MDString.
4665 [](const MDOperand &Op) { return isa<MDString>(Op); }),
4666 "Not all !memprof MemInfoBlock operands 1 to N are MDString", MIB);
4667 }
4668}
4669
4670void Verifier::visitCallsiteMetadata(Instruction &I, MDNode *MD) {
4671 Check(isa<CallBase>(I), "!callsite metadata should only exist on calls", &I);
4672 // Verify the partial callstack annotated from memprof profiles. This callsite
4673 // is a part of a profiled allocation callstack.
4674 visitCallStackMetadata(MD);
4675}
4676
4677void Verifier::visitAnnotationMetadata(MDNode *Annotation) {
4678 Check(isa<MDTuple>(Annotation), "annotation must be a tuple");
4679 Check(Annotation->getNumOperands() >= 1,
4680 "annotation must have at least one operand");
4681 for (const MDOperand &Op : Annotation->operands())
4682 Check(isa<MDString>(Op.get()), "operands must be strings");
4683}
4684
4685void Verifier::visitAliasScopeMetadata(const MDNode *MD) {
4686 unsigned NumOps = MD->getNumOperands();
4687 Check(NumOps >= 2 && NumOps <= 3, "scope must have two or three operands",
4688 MD);
4689 Check(MD->getOperand(0).get() == MD || isa<MDString>(MD->getOperand(0)),
4690 "first scope operand must be self-referential or s