LLVM  8.0.0svn
Verifier.cpp
Go to the documentation of this file.
1 //===-- Verifier.cpp - Implement the Module Verifier -----------------------==//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the function verifier interface, that can be used for some
11 // sanity checking of input to the system.
12 //
13 // Note that this does not provide full `Java style' security and verifications,
14 // instead it just tries to ensure that code is well-formed.
15 //
16 // * Both of a binary operator's parameters are of the same type
17 // * Verify that the indices of mem access instructions match other operands
18 // * Verify that arithmetic and other things are only performed on first-class
19 // types. Verify that shifts & logicals only happen on integrals f.e.
20 // * All of the constants in a switch statement are of the correct type
21 // * The code is in valid SSA form
22 // * It should be illegal to put a label into any other type (like a structure)
23 // or to return one. [except constant arrays!]
24 // * Only phi nodes can be self referential: 'add i32 %0, %0 ; <int>:0' is bad
25 // * PHI nodes must have an entry for each predecessor, with no extras.
26 // * PHI nodes must be the first thing in a basic block, all grouped together
27 // * PHI nodes must have at least one entry
28 // * All basic blocks should only end with terminator insts, not contain them
29 // * The entry node to a function must not have predecessors
30 // * All Instructions must be embedded into a basic block
31 // * Functions cannot take a void-typed parameter
32 // * Verify that a function's argument list agrees with it's declared type.
33 // * It is illegal to specify a name for a void value.
34 // * It is illegal to have a internal global value with no initializer
35 // * It is illegal to have a ret instruction that returns a value that does not
36 // agree with the function return value type.
37 // * Function call argument types match the function prototype
38 // * A landing pad is defined by a landingpad instruction, and can be jumped to
39 // only by the unwind edge of an invoke instruction.
40 // * A landingpad instruction must be the first non-PHI instruction in the
41 // block.
42 // * Landingpad instructions must be in a function with a personality function.
43 // * All other things that are tested by asserts spread about the code...
44 //
45 //===----------------------------------------------------------------------===//
46 
47 #include "llvm/IR/Verifier.h"
48 #include "llvm/ADT/APFloat.h"
49 #include "llvm/ADT/APInt.h"
50 #include "llvm/ADT/ArrayRef.h"
51 #include "llvm/ADT/DenseMap.h"
52 #include "llvm/ADT/MapVector.h"
53 #include "llvm/ADT/Optional.h"
54 #include "llvm/ADT/STLExtras.h"
55 #include "llvm/ADT/SmallPtrSet.h"
56 #include "llvm/ADT/SmallSet.h"
57 #include "llvm/ADT/SmallVector.h"
58 #include "llvm/ADT/StringExtras.h"
59 #include "llvm/ADT/StringMap.h"
60 #include "llvm/ADT/StringRef.h"
61 #include "llvm/ADT/Twine.h"
62 #include "llvm/ADT/ilist.h"
64 #include "llvm/IR/Argument.h"
65 #include "llvm/IR/Attributes.h"
66 #include "llvm/IR/BasicBlock.h"
67 #include "llvm/IR/CFG.h"
68 #include "llvm/IR/CallSite.h"
69 #include "llvm/IR/CallingConv.h"
70 #include "llvm/IR/Comdat.h"
71 #include "llvm/IR/Constant.h"
72 #include "llvm/IR/ConstantRange.h"
73 #include "llvm/IR/Constants.h"
74 #include "llvm/IR/DataLayout.h"
75 #include "llvm/IR/DebugInfo.h"
77 #include "llvm/IR/DebugLoc.h"
78 #include "llvm/IR/DerivedTypes.h"
79 #include "llvm/IR/Dominators.h"
80 #include "llvm/IR/Function.h"
81 #include "llvm/IR/GlobalAlias.h"
82 #include "llvm/IR/GlobalValue.h"
83 #include "llvm/IR/GlobalVariable.h"
84 #include "llvm/IR/InlineAsm.h"
85 #include "llvm/IR/InstVisitor.h"
86 #include "llvm/IR/InstrTypes.h"
87 #include "llvm/IR/Instruction.h"
88 #include "llvm/IR/Instructions.h"
89 #include "llvm/IR/IntrinsicInst.h"
90 #include "llvm/IR/Intrinsics.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"
101 #include "llvm/Pass.h"
103 #include "llvm/Support/Casting.h"
105 #include "llvm/Support/Debug.h"
107 #include "llvm/Support/MathExtras.h"
109 #include <algorithm>
110 #include <cassert>
111 #include <cstdint>
112 #include <memory>
113 #include <string>
114 #include <utility>
115 
116 using namespace llvm;
117 
118 namespace llvm {
119 
122  const Module &M;
124  const DataLayout &DL;
126 
127  /// Track the brokenness of the module while recursively visiting.
128  bool Broken = false;
129  /// Broken debug info can be "recovered" from by stripping the debug info.
130  bool BrokenDebugInfo = false;
131  /// Whether to treat broken debug info as an error.
133 
134  explicit VerifierSupport(raw_ostream *OS, const Module &M)
135  : OS(OS), M(M), MST(&M), DL(M.getDataLayout()), Context(M.getContext()) {}
136 
137 private:
138  void Write(const Module *M) {
139  *OS << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
140  }
141 
142  void Write(const Value *V) {
143  if (!V)
144  return;
145  if (isa<Instruction>(V)) {
146  V->print(*OS, MST);
147  *OS << '\n';
148  } else {
149  V->printAsOperand(*OS, true, MST);
150  *OS << '\n';
151  }
152  }
153 
154  void Write(ImmutableCallSite CS) {
155  Write(CS.getInstruction());
156  }
157 
158  void Write(const Metadata *MD) {
159  if (!MD)
160  return;
161  MD->print(*OS, MST, &M);
162  *OS << '\n';
163  }
164 
165  template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) {
166  Write(MD.get());
167  }
168 
169  void Write(const NamedMDNode *NMD) {
170  if (!NMD)
171  return;
172  NMD->print(*OS, MST);
173  *OS << '\n';
174  }
175 
176  void Write(Type *T) {
177  if (!T)
178  return;
179  *OS << ' ' << *T;
180  }
181 
182  void Write(const Comdat *C) {
183  if (!C)
184  return;
185  *OS << *C;
186  }
187 
188  void Write(const APInt *AI) {
189  if (!AI)
190  return;
191  *OS << *AI << '\n';
192  }
193 
194  void Write(const unsigned i) { *OS << i << '\n'; }
195 
196  template <typename T> void Write(ArrayRef<T> Vs) {
197  for (const T &V : Vs)
198  Write(V);
199  }
200 
201  template <typename T1, typename... Ts>
202  void WriteTs(const T1 &V1, const Ts &... Vs) {
203  Write(V1);
204  WriteTs(Vs...);
205  }
206 
207  template <typename... Ts> void WriteTs() {}
208 
209 public:
210  /// A check failed, so printout out the condition and the message.
211  ///
212  /// This provides a nice place to put a breakpoint if you want to see why
213  /// something is not correct.
214  void CheckFailed(const Twine &Message) {
215  if (OS)
216  *OS << Message << '\n';
217  Broken = true;
218  }
219 
220  /// A check failed (with values to print).
221  ///
222  /// This calls the Message-only version so that the above is easier to set a
223  /// breakpoint on.
224  template <typename T1, typename... Ts>
225  void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
226  CheckFailed(Message);
227  if (OS)
228  WriteTs(V1, Vs...);
229  }
230 
231  /// A debug info check failed.
232  void DebugInfoCheckFailed(const Twine &Message) {
233  if (OS)
234  *OS << Message << '\n';
235  Broken |= TreatBrokenDebugInfoAsError;
236  BrokenDebugInfo = true;
237  }
238 
239  /// A debug info check failed (with values to print).
240  template <typename T1, typename... Ts>
241  void DebugInfoCheckFailed(const Twine &Message, const T1 &V1,
242  const Ts &... Vs) {
243  DebugInfoCheckFailed(Message);
244  if (OS)
245  WriteTs(V1, Vs...);
246  }
247 };
248 
249 } // namespace llvm
250 
251 namespace {
252 
253 class Verifier : public InstVisitor<Verifier>, VerifierSupport {
254  friend class InstVisitor<Verifier>;
255 
256  DominatorTree DT;
257 
258  /// When verifying a basic block, keep track of all of the
259  /// instructions we have seen so far.
260  ///
261  /// This allows us to do efficient dominance checks for the case when an
262  /// instruction has an operand that is an instruction in the same block.
263  SmallPtrSet<Instruction *, 16> InstsInThisBlock;
264 
265  /// Keep track of the metadata nodes that have been checked already.
267 
268  /// Keep track which DISubprogram is attached to which function.
269  DenseMap<const DISubprogram *, const Function *> DISubprogramAttachments;
270 
271  /// Track all DICompileUnits visited.
273 
274  /// The result type for a landingpad.
275  Type *LandingPadResultTy;
276 
277  /// Whether we've seen a call to @llvm.localescape in this function
278  /// already.
279  bool SawFrameEscape;
280 
281  /// Whether the current function has a DISubprogram attached to it.
282  bool HasDebugInfo = false;
283 
284  /// Stores the count of how many objects were passed to llvm.localescape for a
285  /// given function and the largest index passed to llvm.localrecover.
287 
288  // Maps catchswitches and cleanuppads that unwind to siblings to the
289  // terminators that indicate the unwind, used to detect cycles therein.
290  MapVector<Instruction *, Instruction *> SiblingFuncletInfo;
291 
292  /// Cache of constants visited in search of ConstantExprs.
293  SmallPtrSet<const Constant *, 32> ConstantExprVisited;
294 
295  /// Cache of declarations of the llvm.experimental.deoptimize.<ty> intrinsic.
296  SmallVector<const Function *, 4> DeoptimizeDeclarations;
297 
298  // Verify that this GlobalValue is only used in this module.
299  // This map is used to avoid visiting uses twice. We can arrive at a user
300  // twice, if they have multiple operands. In particular for very large
301  // constant expressions, we can arrive at a particular user many times.
302  SmallPtrSet<const Value *, 32> GlobalValueVisited;
303 
304  // Keeps track of duplicate function argument debug info.
306 
307  TBAAVerifier TBAAVerifyHelper;
308 
309  void checkAtomicMemAccessSize(Type *Ty, const Instruction *I);
310 
311 public:
312  explicit Verifier(raw_ostream *OS, bool ShouldTreatBrokenDebugInfoAsError,
313  const Module &M)
314  : VerifierSupport(OS, M), LandingPadResultTy(nullptr),
315  SawFrameEscape(false), TBAAVerifyHelper(this) {
316  TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
317  }
318 
319  bool hasBrokenDebugInfo() const { return BrokenDebugInfo; }
320 
321  bool verify(const Function &F) {
322  assert(F.getParent() == &M &&
323  "An instance of this class only works with a specific module!");
324 
325  // First ensure the function is well-enough formed to compute dominance
326  // information, and directly compute a dominance tree. We don't rely on the
327  // pass manager to provide this as it isolates us from a potentially
328  // out-of-date dominator tree and makes it significantly more complex to run
329  // this code outside of a pass manager.
330  // FIXME: It's really gross that we have to cast away constness here.
331  if (!F.empty())
332  DT.recalculate(const_cast<Function &>(F));
333 
334  for (const BasicBlock &BB : F) {
335  if (!BB.empty() && BB.back().isTerminator())
336  continue;
337 
338  if (OS) {
339  *OS << "Basic Block in function '" << F.getName()
340  << "' does not have terminator!\n";
341  BB.printAsOperand(*OS, true, MST);
342  *OS << "\n";
343  }
344  return false;
345  }
346 
347  Broken = false;
348  // FIXME: We strip const here because the inst visitor strips const.
349  visit(const_cast<Function &>(F));
350  verifySiblingFuncletUnwinds();
351  InstsInThisBlock.clear();
352  DebugFnArgs.clear();
353  LandingPadResultTy = nullptr;
354  SawFrameEscape = false;
355  SiblingFuncletInfo.clear();
356 
357  return !Broken;
358  }
359 
360  /// Verify the module that this instance of \c Verifier was initialized with.
361  bool verify() {
362  Broken = false;
363 
364  // Collect all declarations of the llvm.experimental.deoptimize intrinsic.
365  for (const Function &F : M)
366  if (F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
367  DeoptimizeDeclarations.push_back(&F);
368 
369  // Now that we've visited every function, verify that we never asked to
370  // recover a frame index that wasn't escaped.
371  verifyFrameRecoverIndices();
372  for (const GlobalVariable &GV : M.globals())
373  visitGlobalVariable(GV);
374 
375  for (const GlobalAlias &GA : M.aliases())
376  visitGlobalAlias(GA);
377 
378  for (const NamedMDNode &NMD : M.named_metadata())
379  visitNamedMDNode(NMD);
380 
381  for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
382  visitComdat(SMEC.getValue());
383 
384  visitModuleFlags(M);
385  visitModuleIdents(M);
386 
387  verifyCompileUnits();
388 
389  verifyDeoptimizeCallingConvs();
390  DISubprogramAttachments.clear();
391  return !Broken;
392  }
393 
394 private:
395  // Verification methods...
396  void visitGlobalValue(const GlobalValue &GV);
397  void visitGlobalVariable(const GlobalVariable &GV);
398  void visitGlobalAlias(const GlobalAlias &GA);
399  void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
400  void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
401  const GlobalAlias &A, const Constant &C);
402  void visitNamedMDNode(const NamedMDNode &NMD);
403  void visitMDNode(const MDNode &MD);
404  void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
405  void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
406  void visitComdat(const Comdat &C);
407  void visitModuleIdents(const Module &M);
408  void visitModuleFlags(const Module &M);
409  void visitModuleFlag(const MDNode *Op,
411  SmallVectorImpl<const MDNode *> &Requirements);
412  void visitModuleFlagCGProfileEntry(const MDOperand &MDO);
413  void visitFunction(const Function &F);
414  void visitBasicBlock(BasicBlock &BB);
415  void visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty);
416  void visitDereferenceableMetadata(Instruction &I, MDNode *MD);
417 
418  template <class Ty> bool isValidMetadataArray(const MDTuple &N);
419 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
420 #include "llvm/IR/Metadata.def"
421  void visitDIScope(const DIScope &N);
422  void visitDIVariable(const DIVariable &N);
423  void visitDILexicalBlockBase(const DILexicalBlockBase &N);
424  void visitDITemplateParameter(const DITemplateParameter &N);
425 
426  void visitTemplateParams(const MDNode &N, const Metadata &RawParams);
427 
428  // InstVisitor overrides...
430  void visit(Instruction &I);
431 
432  void visitTruncInst(TruncInst &I);
433  void visitZExtInst(ZExtInst &I);
434  void visitSExtInst(SExtInst &I);
435  void visitFPTruncInst(FPTruncInst &I);
436  void visitFPExtInst(FPExtInst &I);
437  void visitFPToUIInst(FPToUIInst &I);
438  void visitFPToSIInst(FPToSIInst &I);
439  void visitUIToFPInst(UIToFPInst &I);
440  void visitSIToFPInst(SIToFPInst &I);
441  void visitIntToPtrInst(IntToPtrInst &I);
442  void visitPtrToIntInst(PtrToIntInst &I);
443  void visitBitCastInst(BitCastInst &I);
444  void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
445  void visitPHINode(PHINode &PN);
446  void visitUnaryOperator(UnaryOperator &U);
447  void visitBinaryOperator(BinaryOperator &B);
448  void visitICmpInst(ICmpInst &IC);
449  void visitFCmpInst(FCmpInst &FC);
450  void visitExtractElementInst(ExtractElementInst &EI);
451  void visitInsertElementInst(InsertElementInst &EI);
452  void visitShuffleVectorInst(ShuffleVectorInst &EI);
453  void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
454  void visitCallInst(CallInst &CI);
455  void visitInvokeInst(InvokeInst &II);
456  void visitGetElementPtrInst(GetElementPtrInst &GEP);
457  void visitLoadInst(LoadInst &LI);
458  void visitStoreInst(StoreInst &SI);
459  void verifyDominatesUse(Instruction &I, unsigned i);
460  void visitInstruction(Instruction &I);
461  void visitTerminator(Instruction &I);
462  void visitBranchInst(BranchInst &BI);
463  void visitReturnInst(ReturnInst &RI);
464  void visitSwitchInst(SwitchInst &SI);
465  void visitIndirectBrInst(IndirectBrInst &BI);
466  void visitSelectInst(SelectInst &SI);
467  void visitUserOp1(Instruction &I);
468  void visitUserOp2(Instruction &I) { visitUserOp1(I); }
469  void visitIntrinsicCallSite(Intrinsic::ID ID, CallSite CS);
470  void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI);
471  void visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII);
472  void visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI);
473  void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
474  void visitAtomicRMWInst(AtomicRMWInst &RMWI);
475  void visitFenceInst(FenceInst &FI);
476  void visitAllocaInst(AllocaInst &AI);
477  void visitExtractValueInst(ExtractValueInst &EVI);
478  void visitInsertValueInst(InsertValueInst &IVI);
479  void visitEHPadPredecessors(Instruction &I);
480  void visitLandingPadInst(LandingPadInst &LPI);
481  void visitResumeInst(ResumeInst &RI);
482  void visitCatchPadInst(CatchPadInst &CPI);
483  void visitCatchReturnInst(CatchReturnInst &CatchReturn);
484  void visitCleanupPadInst(CleanupPadInst &CPI);
485  void visitFuncletPadInst(FuncletPadInst &FPI);
486  void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
487  void visitCleanupReturnInst(CleanupReturnInst &CRI);
488 
489  void verifyCallSite(CallSite CS);
490  void verifySwiftErrorCallSite(CallSite CS, const Value *SwiftErrorVal);
491  void verifySwiftErrorValue(const Value *SwiftErrorVal);
492  void verifyMustTailCall(CallInst &CI);
493  bool performTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT,
494  unsigned ArgNo, std::string &Suffix);
495  bool verifyAttributeCount(AttributeList Attrs, unsigned Params);
496  void verifyAttributeTypes(AttributeSet Attrs, bool IsFunction,
497  const Value *V);
498  void verifyParameterAttrs(AttributeSet Attrs, Type *Ty, const Value *V);
499  void verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
500  const Value *V);
501  void verifyFunctionMetadata(ArrayRef<std::pair<unsigned, MDNode *>> MDs);
502 
503  void visitConstantExprsRecursively(const Constant *EntryC);
504  void visitConstantExpr(const ConstantExpr *CE);
505  void verifyStatepoint(ImmutableCallSite CS);
506  void verifyFrameRecoverIndices();
507  void verifySiblingFuncletUnwinds();
508 
509  void verifyFragmentExpression(const DbgVariableIntrinsic &I);
510  template <typename ValueOrMetadata>
511  void verifyFragmentExpression(const DIVariable &V,
513  ValueOrMetadata *Desc);
514  void verifyFnArgs(const DbgVariableIntrinsic &I);
515 
516  /// Module-level debug info verification...
517  void verifyCompileUnits();
518 
519  /// Module-level verification that all @llvm.experimental.deoptimize
520  /// declarations share the same calling convention.
521  void verifyDeoptimizeCallingConvs();
522 };
523 
524 } // end anonymous namespace
525 
526 /// We know that cond should be true, if not print an error message.
527 #define Assert(C, ...) \
528  do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (false)
529 
530 /// We know that a debug info condition should be true, if not print
531 /// an error message.
532 #define AssertDI(C, ...) \
533  do { if (!(C)) { DebugInfoCheckFailed(__VA_ARGS__); return; } } while (false)
534 
535 void Verifier::visit(Instruction &I) {
536  for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
537  Assert(I.getOperand(i) != nullptr, "Operand is null", &I);
539 }
540 
541 // Helper to recursively iterate over indirect users. By
542 // returning false, the callback can ask to stop recursing
543 // further.
544 static void forEachUser(const Value *User,
546  llvm::function_ref<bool(const Value *)> Callback) {
547  if (!Visited.insert(User).second)
548  return;
549  for (const Value *TheNextUser : User->materialized_users())
550  if (Callback(TheNextUser))
551  forEachUser(TheNextUser, Visited, Callback);
552 }
553 
554 void Verifier::visitGlobalValue(const GlobalValue &GV) {
556  "Global is external, but doesn't have external or weak linkage!", &GV);
557 
559  "huge alignment values are unsupported", &GV);
560  Assert(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
561  "Only global variables can have appending linkage!", &GV);
562 
563  if (GV.hasAppendingLinkage()) {
564  const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
565  Assert(GVar && GVar->getValueType()->isArrayTy(),
566  "Only global arrays can have appending linkage!", GVar);
567  }
568 
569  if (GV.isDeclarationForLinker())
570  Assert(!GV.hasComdat(), "Declaration may not be in a Comdat!", &GV);
571 
572  if (GV.hasDLLImportStorageClass()) {
573  Assert(!GV.isDSOLocal(),
574  "GlobalValue with DLLImport Storage is dso_local!", &GV);
575 
576  Assert((GV.isDeclaration() && GV.hasExternalLinkage()) ||
578  "Global is marked as dllimport, but not external", &GV);
579  }
580 
581  if (GV.hasLocalLinkage())
582  Assert(GV.isDSOLocal(),
583  "GlobalValue with private or internal linkage must be dso_local!",
584  &GV);
585 
586  if (!GV.hasDefaultVisibility() && !GV.hasExternalWeakLinkage())
587  Assert(GV.isDSOLocal(),
588  "GlobalValue with non default visibility must be dso_local!", &GV);
589 
590  forEachUser(&GV, GlobalValueVisited, [&](const Value *V) -> bool {
591  if (const Instruction *I = dyn_cast<Instruction>(V)) {
592  if (!I->getParent() || !I->getParent()->getParent())
593  CheckFailed("Global is referenced by parentless instruction!", &GV, &M,
594  I);
595  else if (I->getParent()->getParent()->getParent() != &M)
596  CheckFailed("Global is referenced in a different module!", &GV, &M, I,
597  I->getParent()->getParent(),
598  I->getParent()->getParent()->getParent());
599  return false;
600  } else if (const Function *F = dyn_cast<Function>(V)) {
601  if (F->getParent() != &M)
602  CheckFailed("Global is used by function in a different module", &GV, &M,
603  F, F->getParent());
604  return false;
605  }
606  return true;
607  });
608 }
609 
610 void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
611  if (GV.hasInitializer()) {
612  Assert(GV.getInitializer()->getType() == GV.getValueType(),
613  "Global variable initializer type does not match global "
614  "variable type!",
615  &GV);
616  // If the global has common linkage, it must have a zero initializer and
617  // cannot be constant.
618  if (GV.hasCommonLinkage()) {
620  "'common' global must have a zero initializer!", &GV);
621  Assert(!GV.isConstant(), "'common' global may not be marked constant!",
622  &GV);
623  Assert(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
624  }
625  }
626 
627  if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
628  GV.getName() == "llvm.global_dtors")) {
630  "invalid linkage for intrinsic global variable", &GV);
631  // Don't worry about emitting an error for it not being an array,
632  // visitGlobalValue will complain on appending non-array.
633  if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getValueType())) {
634  StructType *STy = dyn_cast<StructType>(ATy->getElementType());
635  PointerType *FuncPtrTy =
637  getPointerTo(DL.getProgramAddressSpace());
638  // FIXME: Reject the 2-field form in LLVM 4.0.
639  Assert(STy &&
640  (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
641  STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
642  STy->getTypeAtIndex(1) == FuncPtrTy,
643  "wrong type for intrinsic global variable", &GV);
644  if (STy->getNumElements() == 3) {
645  Type *ETy = STy->getTypeAtIndex(2);
646  Assert(ETy->isPointerTy() &&
647  cast<PointerType>(ETy)->getElementType()->isIntegerTy(8),
648  "wrong type for intrinsic global variable", &GV);
649  }
650  }
651  }
652 
653  if (GV.hasName() && (GV.getName() == "llvm.used" ||
654  GV.getName() == "llvm.compiler.used")) {
656  "invalid linkage for intrinsic global variable", &GV);
657  Type *GVType = GV.getValueType();
658  if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
659  PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
660  Assert(PTy, "wrong type for intrinsic global variable", &GV);
661  if (GV.hasInitializer()) {
662  const Constant *Init = GV.getInitializer();
663  const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
664  Assert(InitArray, "wrong initalizer for intrinsic global variable",
665  Init);
666  for (Value *Op : InitArray->operands()) {
667  Value *V = Op->stripPointerCastsNoFollowAliases();
668  Assert(isa<GlobalVariable>(V) || isa<Function>(V) ||
669  isa<GlobalAlias>(V),
670  "invalid llvm.used member", V);
671  Assert(V->hasName(), "members of llvm.used must be named", V);
672  }
673  }
674  }
675  }
676 
677  // Visit any debug info attachments.
680  for (auto *MD : MDs) {
681  if (auto *GVE = dyn_cast<DIGlobalVariableExpression>(MD))
682  visitDIGlobalVariableExpression(*GVE);
683  else
684  AssertDI(false, "!dbg attachment of global variable must be a "
685  "DIGlobalVariableExpression");
686  }
687 
688  if (!GV.hasInitializer()) {
689  visitGlobalValue(GV);
690  return;
691  }
692 
693  // Walk any aggregate initializers looking for bitcasts between address spaces
694  visitConstantExprsRecursively(GV.getInitializer());
695 
696  visitGlobalValue(GV);
697 }
698 
699 void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
701  Visited.insert(&GA);
702  visitAliaseeSubExpr(Visited, GA, C);
703 }
704 
705 void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
706  const GlobalAlias &GA, const Constant &C) {
707  if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
708  Assert(!GV->isDeclarationForLinker(), "Alias must point to a definition",
709  &GA);
710 
711  if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
712  Assert(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
713 
714  Assert(!GA2->isInterposable(), "Alias cannot point to an interposable alias",
715  &GA);
716  } else {
717  // Only continue verifying subexpressions of GlobalAliases.
718  // Do not recurse into global initializers.
719  return;
720  }
721  }
722 
723  if (const auto *CE = dyn_cast<ConstantExpr>(&C))
724  visitConstantExprsRecursively(CE);
725 
726  for (const Use &U : C.operands()) {
727  Value *V = &*U;
728  if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
729  visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
730  else if (const auto *C2 = dyn_cast<Constant>(V))
731  visitAliaseeSubExpr(Visited, GA, *C2);
732  }
733 }
734 
735 void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
737  "Alias should have private, internal, linkonce, weak, linkonce_odr, "
738  "weak_odr, or external linkage!",
739  &GA);
740  const Constant *Aliasee = GA.getAliasee();
741  Assert(Aliasee, "Aliasee cannot be NULL!", &GA);
742  Assert(GA.getType() == Aliasee->getType(),
743  "Alias and aliasee types should match!", &GA);
744 
745  Assert(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
746  "Aliasee should be either GlobalValue or ConstantExpr", &GA);
747 
748  visitAliaseeSubExpr(GA, *Aliasee);
749 
750  visitGlobalValue(GA);
751 }
752 
753 void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
754  // There used to be various other llvm.dbg.* nodes, but we don't support
755  // upgrading them and we want to reserve the namespace for future uses.
756  if (NMD.getName().startswith("llvm.dbg."))
757  AssertDI(NMD.getName() == "llvm.dbg.cu",
758  "unrecognized named metadata node in the llvm.dbg namespace",
759  &NMD);
760  for (const MDNode *MD : NMD.operands()) {
761  if (NMD.getName() == "llvm.dbg.cu")
762  AssertDI(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD);
763 
764  if (!MD)
765  continue;
766 
767  visitMDNode(*MD);
768  }
769 }
770 
771 void Verifier::visitMDNode(const MDNode &MD) {
772  // Only visit each node once. Metadata can be mutually recursive, so this
773  // avoids infinite recursion here, as well as being an optimization.
774  if (!MDNodes.insert(&MD).second)
775  return;
776 
777  switch (MD.getMetadataID()) {
778  default:
779  llvm_unreachable("Invalid MDNode subclass");
780  case Metadata::MDTupleKind:
781  break;
782 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
783  case Metadata::CLASS##Kind: \
784  visit##CLASS(cast<CLASS>(MD)); \
785  break;
786 #include "llvm/IR/Metadata.def"
787  }
788 
789  for (const Metadata *Op : MD.operands()) {
790  if (!Op)
791  continue;
792  Assert(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
793  &MD, Op);
794  if (auto *N = dyn_cast<MDNode>(Op)) {
795  visitMDNode(*N);
796  continue;
797  }
798  if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
799  visitValueAsMetadata(*V, nullptr);
800  continue;
801  }
802  }
803 
804  // Check these last, so we diagnose problems in operands first.
805  Assert(!MD.isTemporary(), "Expected no forward declarations!", &MD);
806  Assert(MD.isResolved(), "All nodes should be resolved!", &MD);
807 }
808 
809 void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
810  Assert(MD.getValue(), "Expected valid value", &MD);
811  Assert(!MD.getValue()->getType()->isMetadataTy(),
812  "Unexpected metadata round-trip through values", &MD, MD.getValue());
813 
814  auto *L = dyn_cast<LocalAsMetadata>(&MD);
815  if (!L)
816  return;
817 
818  Assert(F, "function-local metadata used outside a function", L);
819 
820  // If this was an instruction, bb, or argument, verify that it is in the
821  // function that we expect.
822  Function *ActualF = nullptr;
823  if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
824  Assert(I->getParent(), "function-local metadata not in basic block", L, I);
825  ActualF = I->getParent()->getParent();
826  } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
827  ActualF = BB->getParent();
828  else if (Argument *A = dyn_cast<Argument>(L->getValue()))
829  ActualF = A->getParent();
830  assert(ActualF && "Unimplemented function local metadata case!");
831 
832  Assert(ActualF == F, "function-local metadata used in wrong function", L);
833 }
834 
835 void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
836  Metadata *MD = MDV.getMetadata();
837  if (auto *N = dyn_cast<MDNode>(MD)) {
838  visitMDNode(*N);
839  return;
840  }
841 
842  // Only visit each node once. Metadata can be mutually recursive, so this
843  // avoids infinite recursion here, as well as being an optimization.
844  if (!MDNodes.insert(MD).second)
845  return;
846 
847  if (auto *V = dyn_cast<ValueAsMetadata>(MD))
848  visitValueAsMetadata(*V, F);
849 }
850 
851 static bool isType(const Metadata *MD) { return !MD || isa<DIType>(MD); }
852 static bool isScope(const Metadata *MD) { return !MD || isa<DIScope>(MD); }
853 static bool isDINode(const Metadata *MD) { return !MD || isa<DINode>(MD); }
854 
855 void Verifier::visitDILocation(const DILocation &N) {
856  AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
857  "location requires a valid scope", &N, N.getRawScope());
858  if (auto *IA = N.getRawInlinedAt())
859  AssertDI(isa<DILocation>(IA), "inlined-at should be a location", &N, IA);
860  if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
861  AssertDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
862 }
863 
864 void Verifier::visitGenericDINode(const GenericDINode &N) {
865  AssertDI(N.getTag(), "invalid tag", &N);
866 }
867 
868 void Verifier::visitDIScope(const DIScope &N) {
869  if (auto *F = N.getRawFile())
870  AssertDI(isa<DIFile>(F), "invalid file", &N, F);
871 }
872 
873 void Verifier::visitDISubrange(const DISubrange &N) {
874  AssertDI(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
875  auto Count = N.getCount();
876  AssertDI(Count, "Count must either be a signed constant or a DIVariable",
877  &N);
878  AssertDI(!Count.is<ConstantInt*>() ||
879  Count.get<ConstantInt*>()->getSExtValue() >= -1,
880  "invalid subrange count", &N);
881 }
882 
883 void Verifier::visitDIEnumerator(const DIEnumerator &N) {
884  AssertDI(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
885 }
886 
887 void Verifier::visitDIBasicType(const DIBasicType &N) {
888  AssertDI(N.getTag() == dwarf::DW_TAG_base_type ||
889  N.getTag() == dwarf::DW_TAG_unspecified_type,
890  "invalid tag", &N);
891  AssertDI(!(N.isBigEndian() && N.isLittleEndian()) ,
892  "has conflicting flags", &N);
893 }
894 
895 void Verifier::visitDIDerivedType(const DIDerivedType &N) {
896  // Common scope checks.
897  visitDIScope(N);
898 
899  AssertDI(N.getTag() == dwarf::DW_TAG_typedef ||
900  N.getTag() == dwarf::DW_TAG_pointer_type ||
901  N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
902  N.getTag() == dwarf::DW_TAG_reference_type ||
903  N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
904  N.getTag() == dwarf::DW_TAG_const_type ||
905  N.getTag() == dwarf::DW_TAG_volatile_type ||
906  N.getTag() == dwarf::DW_TAG_restrict_type ||
907  N.getTag() == dwarf::DW_TAG_atomic_type ||
908  N.getTag() == dwarf::DW_TAG_member ||
909  N.getTag() == dwarf::DW_TAG_inheritance ||
910  N.getTag() == dwarf::DW_TAG_friend,
911  "invalid tag", &N);
912  if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
913  AssertDI(isType(N.getRawExtraData()), "invalid pointer to member type", &N,
914  N.getRawExtraData());
915  }
916 
917  AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
918  AssertDI(isType(N.getRawBaseType()), "invalid base type", &N,
919  N.getRawBaseType());
920 
921  if (N.getDWARFAddressSpace()) {
922  AssertDI(N.getTag() == dwarf::DW_TAG_pointer_type ||
923  N.getTag() == dwarf::DW_TAG_reference_type,
924  "DWARF address space only applies to pointer or reference types",
925  &N);
926  }
927 }
928 
929 /// Detect mutually exclusive flags.
930 static bool hasConflictingReferenceFlags(unsigned Flags) {
931  return ((Flags & DINode::FlagLValueReference) &&
932  (Flags & DINode::FlagRValueReference)) ||
933  ((Flags & DINode::FlagTypePassByValue) &&
934  (Flags & DINode::FlagTypePassByReference));
935 }
936 
937 void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) {
938  auto *Params = dyn_cast<MDTuple>(&RawParams);
939  AssertDI(Params, "invalid template params", &N, &RawParams);
940  for (Metadata *Op : Params->operands()) {
941  AssertDI(Op && isa<DITemplateParameter>(Op), "invalid template parameter",
942  &N, Params, Op);
943  }
944 }
945 
946 void Verifier::visitDICompositeType(const DICompositeType &N) {
947  // Common scope checks.
948  visitDIScope(N);
949 
950  AssertDI(N.getTag() == dwarf::DW_TAG_array_type ||
951  N.getTag() == dwarf::DW_TAG_structure_type ||
952  N.getTag() == dwarf::DW_TAG_union_type ||
953  N.getTag() == dwarf::DW_TAG_enumeration_type ||
954  N.getTag() == dwarf::DW_TAG_class_type ||
955  N.getTag() == dwarf::DW_TAG_variant_part,
956  "invalid tag", &N);
957 
958  AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
959  AssertDI(isType(N.getRawBaseType()), "invalid base type", &N,
960  N.getRawBaseType());
961 
962  AssertDI(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
963  "invalid composite elements", &N, N.getRawElements());
964  AssertDI(isType(N.getRawVTableHolder()), "invalid vtable holder", &N,
965  N.getRawVTableHolder());
967  "invalid reference flags", &N);
968 
969  if (N.isVector()) {
970  const DINodeArray Elements = N.getElements();
971  AssertDI(Elements.size() == 1 &&
972  Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
973  "invalid vector, expected one element of type subrange", &N);
974  }
975 
976  if (auto *Params = N.getRawTemplateParams())
977  visitTemplateParams(N, *Params);
978 
979  if (N.getTag() == dwarf::DW_TAG_class_type ||
980  N.getTag() == dwarf::DW_TAG_union_type) {
981  AssertDI(N.getFile() && !N.getFile()->getFilename().empty(),
982  "class/union requires a filename", &N, N.getFile());
983  }
984 
985  if (auto *D = N.getRawDiscriminator()) {
986  AssertDI(isa<DIDerivedType>(D) && N.getTag() == dwarf::DW_TAG_variant_part,
987  "discriminator can only appear on variant part");
988  }
989 }
990 
991 void Verifier::visitDISubroutineType(const DISubroutineType &N) {
992  AssertDI(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
993  if (auto *Types = N.getRawTypeArray()) {
994  AssertDI(isa<MDTuple>(Types), "invalid composite elements", &N, Types);
995  for (Metadata *Ty : N.getTypeArray()->operands()) {
996  AssertDI(isType(Ty), "invalid subroutine type ref", &N, Types, Ty);
997  }
998  }
1000  "invalid reference flags", &N);
1001 }
1002 
1003 void Verifier::visitDIFile(const DIFile &N) {
1004  AssertDI(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
1005  Optional<DIFile::ChecksumInfo<StringRef>> Checksum = N.getChecksum();
1006  if (Checksum) {
1007  AssertDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last,
1008  "invalid checksum kind", &N);
1009  size_t Size;
1010  switch (Checksum->Kind) {
1011  case DIFile::CSK_MD5:
1012  Size = 32;
1013  break;
1014  case DIFile::CSK_SHA1:
1015  Size = 40;
1016  break;
1017  }
1018  AssertDI(Checksum->Value.size() == Size, "invalid checksum length", &N);
1019  AssertDI(Checksum->Value.find_if_not(llvm::isHexDigit) == StringRef::npos,
1020  "invalid checksum", &N);
1021  }
1022 }
1023 
1024 void Verifier::visitDICompileUnit(const DICompileUnit &N) {
1025  AssertDI(N.isDistinct(), "compile units must be distinct", &N);
1026  AssertDI(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
1027 
1028  // Don't bother verifying the compilation directory or producer string
1029  // as those could be empty.
1030  AssertDI(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N,
1031  N.getRawFile());
1032  AssertDI(!N.getFile()->getFilename().empty(), "invalid filename", &N,
1033  N.getFile());
1034 
1036  "invalid emission kind", &N);
1037 
1038  if (auto *Array = N.getRawEnumTypes()) {
1039  AssertDI(isa<MDTuple>(Array), "invalid enum list", &N, Array);
1040  for (Metadata *Op : N.getEnumTypes()->operands()) {
1041  auto *Enum = dyn_cast_or_null<DICompositeType>(Op);
1042  AssertDI(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
1043  "invalid enum type", &N, N.getEnumTypes(), Op);
1044  }
1045  }
1046  if (auto *Array = N.getRawRetainedTypes()) {
1047  AssertDI(isa<MDTuple>(Array), "invalid retained type list", &N, Array);
1048  for (Metadata *Op : N.getRetainedTypes()->operands()) {
1049  AssertDI(Op && (isa<DIType>(Op) ||
1050  (isa<DISubprogram>(Op) &&
1051  !cast<DISubprogram>(Op)->isDefinition())),
1052  "invalid retained type", &N, Op);
1053  }
1054  }
1055  if (auto *Array = N.getRawGlobalVariables()) {
1056  AssertDI(isa<MDTuple>(Array), "invalid global variable list", &N, Array);
1057  for (Metadata *Op : N.getGlobalVariables()->operands()) {
1058  AssertDI(Op && (isa<DIGlobalVariableExpression>(Op)),
1059  "invalid global variable ref", &N, Op);
1060  }
1061  }
1062  if (auto *Array = N.getRawImportedEntities()) {
1063  AssertDI(isa<MDTuple>(Array), "invalid imported entity list", &N, Array);
1064  for (Metadata *Op : N.getImportedEntities()->operands()) {
1065  AssertDI(Op && isa<DIImportedEntity>(Op), "invalid imported entity ref",
1066  &N, Op);
1067  }
1068  }
1069  if (auto *Array = N.getRawMacros()) {
1070  AssertDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
1071  for (Metadata *Op : N.getMacros()->operands()) {
1072  AssertDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
1073  }
1074  }
1075  CUVisited.insert(&N);
1076 }
1077 
1078 void Verifier::visitDISubprogram(const DISubprogram &N) {
1079  AssertDI(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
1080  AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
1081  if (auto *F = N.getRawFile())
1082  AssertDI(isa<DIFile>(F), "invalid file", &N, F);
1083  else
1084  AssertDI(N.getLine() == 0, "line specified with no file", &N, N.getLine());
1085  if (auto *T = N.getRawType())
1086  AssertDI(isa<DISubroutineType>(T), "invalid subroutine type", &N, T);
1087  AssertDI(isType(N.getRawContainingType()), "invalid containing type", &N,
1088  N.getRawContainingType());
1089  if (auto *Params = N.getRawTemplateParams())
1090  visitTemplateParams(N, *Params);
1091  if (auto *S = N.getRawDeclaration())
1092  AssertDI(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(),
1093  "invalid subprogram declaration", &N, S);
1094  if (auto *RawNode = N.getRawRetainedNodes()) {
1095  auto *Node = dyn_cast<MDTuple>(RawNode);
1096  AssertDI(Node, "invalid retained nodes list", &N, RawNode);
1097  for (Metadata *Op : Node->operands()) {
1098  AssertDI(Op && (isa<DILocalVariable>(Op) || isa<DILabel>(Op)),
1099  "invalid retained nodes, expected DILocalVariable or DILabel",
1100  &N, Node, Op);
1101  }
1102  }
1103  AssertDI(!hasConflictingReferenceFlags(N.getFlags()),
1104  "invalid reference flags", &N);
1105 
1106  auto *Unit = N.getRawUnit();
1107  if (N.isDefinition()) {
1108  // Subprogram definitions (not part of the type hierarchy).
1109  AssertDI(N.isDistinct(), "subprogram definitions must be distinct", &N);
1110  AssertDI(Unit, "subprogram definitions must have a compile unit", &N);
1111  AssertDI(isa<DICompileUnit>(Unit), "invalid unit type", &N, Unit);
1112  } else {
1113  // Subprogram declarations (part of the type hierarchy).
1114  AssertDI(!Unit, "subprogram declarations must not have a compile unit", &N);
1115  }
1116 
1117  if (auto *RawThrownTypes = N.getRawThrownTypes()) {
1118  auto *ThrownTypes = dyn_cast<MDTuple>(RawThrownTypes);
1119  AssertDI(ThrownTypes, "invalid thrown types list", &N, RawThrownTypes);
1120  for (Metadata *Op : ThrownTypes->operands())
1121  AssertDI(Op && isa<DIType>(Op), "invalid thrown type", &N, ThrownTypes,
1122  Op);
1123  }
1124 
1125  if (N.areAllCallsDescribed())
1126  AssertDI(N.isDefinition(),
1127  "DIFlagAllCallsDescribed must be attached to a definition");
1128 }
1129 
1130 void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) {
1131  AssertDI(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
1132  AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1133  "invalid local scope", &N, N.getRawScope());
1134  if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
1135  AssertDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
1136 }
1137 
1138 void Verifier::visitDILexicalBlock(const DILexicalBlock &N) {
1139  visitDILexicalBlockBase(N);
1140 
1141  AssertDI(N.getLine() || !N.getColumn(),
1142  "cannot have column info without line info", &N);
1143 }
1144 
1145 void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) {
1146  visitDILexicalBlockBase(N);
1147 }
1148 
1149 void Verifier::visitDINamespace(const DINamespace &N) {
1150  AssertDI(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
1151  if (auto *S = N.getRawScope())
1152  AssertDI(isa<DIScope>(S), "invalid scope ref", &N, S);
1153 }
1154 
1155 void Verifier::visitDIMacro(const DIMacro &N) {
1158  "invalid macinfo type", &N);
1159  AssertDI(!N.getName().empty(), "anonymous macro", &N);
1160  if (!N.getValue().empty()) {
1161  assert(N.getValue().data()[0] != ' ' && "Macro value has a space prefix");
1162  }
1163 }
1164 
1165 void Verifier::visitDIMacroFile(const DIMacroFile &N) {
1167  "invalid macinfo type", &N);
1168  if (auto *F = N.getRawFile())
1169  AssertDI(isa<DIFile>(F), "invalid file", &N, F);
1170 
1171  if (auto *Array = N.getRawElements()) {
1172  AssertDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
1173  for (Metadata *Op : N.getElements()->operands()) {
1174  AssertDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
1175  }
1176  }
1177 }
1178 
1179 void Verifier::visitDIModule(const DIModule &N) {
1180  AssertDI(N.getTag() == dwarf::DW_TAG_module, "invalid tag", &N);
1181  AssertDI(!N.getName().empty(), "anonymous module", &N);
1182 }
1183 
1184 void Verifier::visitDITemplateParameter(const DITemplateParameter &N) {
1185  AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
1186 }
1187 
1188 void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) {
1189  visitDITemplateParameter(N);
1190 
1191  AssertDI(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
1192  &N);
1193 }
1194 
1195 void Verifier::visitDITemplateValueParameter(
1196  const DITemplateValueParameter &N) {
1197  visitDITemplateParameter(N);
1198 
1199  AssertDI(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1200  N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1201  N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1202  "invalid tag", &N);
1203 }
1204 
1205 void Verifier::visitDIVariable(const DIVariable &N) {
1206  if (auto *S = N.getRawScope())
1207  AssertDI(isa<DIScope>(S), "invalid scope", &N, S);
1208  if (auto *F = N.getRawFile())
1209  AssertDI(isa<DIFile>(F), "invalid file", &N, F);
1210 }
1211 
1212 void Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) {
1213  // Checks common to all variables.
1214  visitDIVariable(N);
1215 
1216  AssertDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1217  AssertDI(!N.getName().empty(), "missing global variable name", &N);
1218  AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
1219  AssertDI(N.getType(), "missing global variable type", &N);
1220  if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
1221  AssertDI(isa<DIDerivedType>(Member),
1222  "invalid static data member declaration", &N, Member);
1223  }
1224 }
1225 
1226 void Verifier::visitDILocalVariable(const DILocalVariable &N) {
1227  // Checks common to all variables.
1228  visitDIVariable(N);
1229 
1230  AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
1231  AssertDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1232  AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1233  "local variable requires a valid scope", &N, N.getRawScope());
1234 }
1235 
1236 void Verifier::visitDILabel(const DILabel &N) {
1237  if (auto *S = N.getRawScope())
1238  AssertDI(isa<DIScope>(S), "invalid scope", &N, S);
1239  if (auto *F = N.getRawFile())
1240  AssertDI(isa<DIFile>(F), "invalid file", &N, F);
1241 
1242  AssertDI(N.getTag() == dwarf::DW_TAG_label, "invalid tag", &N);
1243  AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1244  "label requires a valid scope", &N, N.getRawScope());
1245 }
1246 
1247 void Verifier::visitDIExpression(const DIExpression &N) {
1248  AssertDI(N.isValid(), "invalid expression", &N);
1249 }
1250 
1251 void Verifier::visitDIGlobalVariableExpression(
1252  const DIGlobalVariableExpression &GVE) {
1253  AssertDI(GVE.getVariable(), "missing variable");
1254  if (auto *Var = GVE.getVariable())
1255  visitDIGlobalVariable(*Var);
1256  if (auto *Expr = GVE.getExpression()) {
1257  visitDIExpression(*Expr);
1258  if (auto Fragment = Expr->getFragmentInfo())
1259  verifyFragmentExpression(*GVE.getVariable(), *Fragment, &GVE);
1260  }
1261 }
1262 
1263 void Verifier::visitDIObjCProperty(const DIObjCProperty &N) {
1264  AssertDI(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
1265  if (auto *T = N.getRawType())
1266  AssertDI(isType(T), "invalid type ref", &N, T);
1267  if (auto *F = N.getRawFile())
1268  AssertDI(isa<DIFile>(F), "invalid file", &N, F);
1269 }
1270 
1271 void Verifier::visitDIImportedEntity(const DIImportedEntity &N) {
1272  AssertDI(N.getTag() == dwarf::DW_TAG_imported_module ||
1273  N.getTag() == dwarf::DW_TAG_imported_declaration,
1274  "invalid tag", &N);
1275  if (auto *S = N.getRawScope())
1276  AssertDI(isa<DIScope>(S), "invalid scope for imported entity", &N, S);
1277  AssertDI(isDINode(N.getRawEntity()), "invalid imported entity", &N,
1278  N.getRawEntity());
1279 }
1280 
1281 void Verifier::visitComdat(const Comdat &C) {
1282  // The Module is invalid if the GlobalValue has private linkage. Entities
1283  // with private linkage don't have entries in the symbol table.
1284  if (const GlobalValue *GV = M.getNamedValue(C.getName()))
1285  Assert(!GV->hasPrivateLinkage(), "comdat global value has private linkage",
1286  GV);
1287 }
1288 
1289 void Verifier::visitModuleIdents(const Module &M) {
1290  const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
1291  if (!Idents)
1292  return;
1293 
1294  // llvm.ident takes a list of metadata entry. Each entry has only one string.
1295  // Scan each llvm.ident entry and make sure that this requirement is met.
1296  for (const MDNode *N : Idents->operands()) {
1297  Assert(N->getNumOperands() == 1,
1298  "incorrect number of operands in llvm.ident metadata", N);
1299  Assert(dyn_cast_or_null<MDString>(N->getOperand(0)),
1300  ("invalid value for llvm.ident metadata entry operand"
1301  "(the operand should be a string)"),
1302  N->getOperand(0));
1303  }
1304 }
1305 
1306 void Verifier::visitModuleFlags(const Module &M) {
1307  const NamedMDNode *Flags = M.getModuleFlagsMetadata();
1308  if (!Flags) return;
1309 
1310  // Scan each flag, and track the flags and requirements.
1312  SmallVector<const MDNode*, 16> Requirements;
1313  for (const MDNode *MDN : Flags->operands())
1314  visitModuleFlag(MDN, SeenIDs, Requirements);
1315 
1316  // Validate that the requirements in the module are valid.
1317  for (const MDNode *Requirement : Requirements) {
1318  const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1319  const Metadata *ReqValue = Requirement->getOperand(1);
1320 
1321  const MDNode *Op = SeenIDs.lookup(Flag);
1322  if (!Op) {
1323  CheckFailed("invalid requirement on flag, flag is not present in module",
1324  Flag);
1325  continue;
1326  }
1327 
1328  if (Op->getOperand(2) != ReqValue) {
1329  CheckFailed(("invalid requirement on flag, "
1330  "flag does not have the required value"),
1331  Flag);
1332  continue;
1333  }
1334  }
1335 }
1336 
1337 void
1338 Verifier::visitModuleFlag(const MDNode *Op,
1340  SmallVectorImpl<const MDNode *> &Requirements) {
1341  // Each module flag should have three arguments, the merge behavior (a
1342  // constant int), the flag ID (an MDString), and the value.
1343  Assert(Op->getNumOperands() == 3,
1344  "incorrect number of operands in module flag", Op);
1346  if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
1347  Assert(
1348  mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)),
1349  "invalid behavior operand in module flag (expected constant integer)",
1350  Op->getOperand(0));
1351  Assert(false,
1352  "invalid behavior operand in module flag (unexpected constant)",
1353  Op->getOperand(0));
1354  }
1355  MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
1356  Assert(ID, "invalid ID operand in module flag (expected metadata string)",
1357  Op->getOperand(1));
1358 
1359  // Sanity check the values for behaviors with additional requirements.
1360  switch (MFB) {
1361  case Module::Error:
1362  case Module::Warning:
1363  case Module::Override:
1364  // These behavior types accept any value.
1365  break;
1366 
1367  case Module::Max: {
1368  Assert(mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2)),
1369  "invalid value for 'max' module flag (expected constant integer)",
1370  Op->getOperand(2));
1371  break;
1372  }
1373 
1374  case Module::Require: {
1375  // The value should itself be an MDNode with two operands, a flag ID (an
1376  // MDString), and a value.
1377  MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
1378  Assert(Value && Value->getNumOperands() == 2,
1379  "invalid value for 'require' module flag (expected metadata pair)",
1380  Op->getOperand(2));
1381  Assert(isa<MDString>(Value->getOperand(0)),
1382  ("invalid value for 'require' module flag "
1383  "(first value operand should be a string)"),
1384  Value->getOperand(0));
1385 
1386  // Append it to the list of requirements, to check once all module flags are
1387  // scanned.
1388  Requirements.push_back(Value);
1389  break;
1390  }
1391 
1392  case Module::Append:
1393  case Module::AppendUnique: {
1394  // These behavior types require the operand be an MDNode.
1395  Assert(isa<MDNode>(Op->getOperand(2)),
1396  "invalid value for 'append'-type module flag "
1397  "(expected a metadata node)",
1398  Op->getOperand(2));
1399  break;
1400  }
1401  }
1402 
1403  // Unless this is a "requires" flag, check the ID is unique.
1404  if (MFB != Module::Require) {
1405  bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
1406  Assert(Inserted,
1407  "module flag identifiers must be unique (or of 'require' type)", ID);
1408  }
1409 
1410  if (ID->getString() == "wchar_size") {
1412  = mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
1413  Assert(Value, "wchar_size metadata requires constant integer argument");
1414  }
1415 
1416  if (ID->getString() == "Linker Options") {
1417  // If the llvm.linker.options named metadata exists, we assume that the
1418  // bitcode reader has upgraded the module flag. Otherwise the flag might
1419  // have been created by a client directly.
1420  Assert(M.getNamedMetadata("llvm.linker.options"),
1421  "'Linker Options' named metadata no longer supported");
1422  }
1423 
1424  if (ID->getString() == "CG Profile") {
1425  for (const MDOperand &MDO : cast<MDNode>(Op->getOperand(2))->operands())
1426  visitModuleFlagCGProfileEntry(MDO);
1427  }
1428 }
1429 
1430 void Verifier::visitModuleFlagCGProfileEntry(const MDOperand &MDO) {
1431  auto CheckFunction = [&](const MDOperand &FuncMDO) {
1432  if (!FuncMDO)
1433  return;
1434  auto F = dyn_cast<ValueAsMetadata>(FuncMDO);
1435  Assert(F && isa<Function>(F->getValue()), "expected a Function or null",
1436  FuncMDO);
1437  };
1438  auto Node = dyn_cast_or_null<MDNode>(MDO);
1439  Assert(Node && Node->getNumOperands() == 3, "expected a MDNode triple", MDO);
1440  CheckFunction(Node->getOperand(0));
1441  CheckFunction(Node->getOperand(1));
1442  auto Count = dyn_cast_or_null<ConstantAsMetadata>(Node->getOperand(2));
1443  Assert(Count && Count->getType()->isIntegerTy(),
1444  "expected an integer constant", Node->getOperand(2));
1445 }
1446 
1447 /// Return true if this attribute kind only applies to functions.
1449  switch (Kind) {
1450  case Attribute::NoReturn:
1451  case Attribute::NoCfCheck:
1452  case Attribute::NoUnwind:
1453  case Attribute::NoInline:
1454  case Attribute::AlwaysInline:
1455  case Attribute::OptimizeForSize:
1456  case Attribute::StackProtect:
1457  case Attribute::StackProtectReq:
1458  case Attribute::StackProtectStrong:
1459  case Attribute::SafeStack:
1460  case Attribute::ShadowCallStack:
1461  case Attribute::NoRedZone:
1462  case Attribute::NoImplicitFloat:
1463  case Attribute::Naked:
1464  case Attribute::InlineHint:
1465  case Attribute::StackAlignment:
1466  case Attribute::UWTable:
1467  case Attribute::NonLazyBind:
1468  case Attribute::ReturnsTwice:
1469  case Attribute::SanitizeAddress:
1470  case Attribute::SanitizeHWAddress:
1471  case Attribute::SanitizeThread:
1472  case Attribute::SanitizeMemory:
1473  case Attribute::MinSize:
1474  case Attribute::NoDuplicate:
1475  case Attribute::Builtin:
1476  case Attribute::NoBuiltin:
1477  case Attribute::Cold:
1478  case Attribute::OptForFuzzing:
1479  case Attribute::OptimizeNone:
1480  case Attribute::JumpTable:
1481  case Attribute::Convergent:
1482  case Attribute::ArgMemOnly:
1483  case Attribute::NoRecurse:
1484  case Attribute::InaccessibleMemOnly:
1485  case Attribute::InaccessibleMemOrArgMemOnly:
1486  case Attribute::AllocSize:
1487  case Attribute::SpeculativeLoadHardening:
1488  case Attribute::Speculatable:
1489  case Attribute::StrictFP:
1490  return true;
1491  default:
1492  break;
1493  }
1494  return false;
1495 }
1496 
1497 /// Return true if this is a function attribute that can also appear on
1498 /// arguments.
1500  return Kind == Attribute::ReadOnly || Kind == Attribute::WriteOnly ||
1501  Kind == Attribute::ReadNone;
1502 }
1503 
1504 void Verifier::verifyAttributeTypes(AttributeSet Attrs, bool IsFunction,
1505  const Value *V) {
1506  for (Attribute A : Attrs) {
1507  if (A.isStringAttribute())
1508  continue;
1509 
1510  if (isFuncOnlyAttr(A.getKindAsEnum())) {
1511  if (!IsFunction) {
1512  CheckFailed("Attribute '" + A.getAsString() +
1513  "' only applies to functions!",
1514  V);
1515  return;
1516  }
1517  } else if (IsFunction && !isFuncOrArgAttr(A.getKindAsEnum())) {
1518  CheckFailed("Attribute '" + A.getAsString() +
1519  "' does not apply to functions!",
1520  V);
1521  return;
1522  }
1523  }
1524 }
1525 
1526 // VerifyParameterAttrs - Check the given attributes for an argument or return
1527 // value of the specified type. The value V is printed in error messages.
1528 void Verifier::verifyParameterAttrs(AttributeSet Attrs, Type *Ty,
1529  const Value *V) {
1530  if (!Attrs.hasAttributes())
1531  return;
1532 
1533  verifyAttributeTypes(Attrs, /*IsFunction=*/false, V);
1534 
1535  // Check for mutually incompatible attributes. Only inreg is compatible with
1536  // sret.
1537  unsigned AttrCount = 0;
1538  AttrCount += Attrs.hasAttribute(Attribute::ByVal);
1539  AttrCount += Attrs.hasAttribute(Attribute::InAlloca);
1540  AttrCount += Attrs.hasAttribute(Attribute::StructRet) ||
1541  Attrs.hasAttribute(Attribute::InReg);
1542  AttrCount += Attrs.hasAttribute(Attribute::Nest);
1543  Assert(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', "
1544  "and 'sret' are incompatible!",
1545  V);
1546 
1547  Assert(!(Attrs.hasAttribute(Attribute::InAlloca) &&
1548  Attrs.hasAttribute(Attribute::ReadOnly)),
1549  "Attributes "
1550  "'inalloca and readonly' are incompatible!",
1551  V);
1552 
1553  Assert(!(Attrs.hasAttribute(Attribute::StructRet) &&
1554  Attrs.hasAttribute(Attribute::Returned)),
1555  "Attributes "
1556  "'sret and returned' are incompatible!",
1557  V);
1558 
1559  Assert(!(Attrs.hasAttribute(Attribute::ZExt) &&
1560  Attrs.hasAttribute(Attribute::SExt)),
1561  "Attributes "
1562  "'zeroext and signext' are incompatible!",
1563  V);
1564 
1565  Assert(!(Attrs.hasAttribute(Attribute::ReadNone) &&
1566  Attrs.hasAttribute(Attribute::ReadOnly)),
1567  "Attributes "
1568  "'readnone and readonly' are incompatible!",
1569  V);
1570 
1571  Assert(!(Attrs.hasAttribute(Attribute::ReadNone) &&
1572  Attrs.hasAttribute(Attribute::WriteOnly)),
1573  "Attributes "
1574  "'readnone and writeonly' are incompatible!",
1575  V);
1576 
1577  Assert(!(Attrs.hasAttribute(Attribute::ReadOnly) &&
1578  Attrs.hasAttribute(Attribute::WriteOnly)),
1579  "Attributes "
1580  "'readonly and writeonly' are incompatible!",
1581  V);
1582 
1583  Assert(!(Attrs.hasAttribute(Attribute::NoInline) &&
1584  Attrs.hasAttribute(Attribute::AlwaysInline)),
1585  "Attributes "
1586  "'noinline and alwaysinline' are incompatible!",
1587  V);
1588 
1589  AttrBuilder IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty);
1590  Assert(!AttrBuilder(Attrs).overlaps(IncompatibleAttrs),
1591  "Wrong types for attribute: " +
1592  AttributeSet::get(Context, IncompatibleAttrs).getAsString(),
1593  V);
1594 
1595  if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1596  SmallPtrSet<Type*, 4> Visited;
1597  if (!PTy->getElementType()->isSized(&Visited)) {
1598  Assert(!Attrs.hasAttribute(Attribute::ByVal) &&
1599  !Attrs.hasAttribute(Attribute::InAlloca),
1600  "Attributes 'byval' and 'inalloca' do not support unsized types!",
1601  V);
1602  }
1603  if (!isa<PointerType>(PTy->getElementType()))
1604  Assert(!Attrs.hasAttribute(Attribute::SwiftError),
1605  "Attribute 'swifterror' only applies to parameters "
1606  "with pointer to pointer type!",
1607  V);
1608  } else {
1609  Assert(!Attrs.hasAttribute(Attribute::ByVal),
1610  "Attribute 'byval' only applies to parameters with pointer type!",
1611  V);
1612  Assert(!Attrs.hasAttribute(Attribute::SwiftError),
1613  "Attribute 'swifterror' only applies to parameters "
1614  "with pointer type!",
1615  V);
1616  }
1617 }
1618 
1619 // Check parameter attributes against a function type.
1620 // The value V is printed in error messages.
1621 void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
1622  const Value *V) {
1623  if (Attrs.isEmpty())
1624  return;
1625 
1626  bool SawNest = false;
1627  bool SawReturned = false;
1628  bool SawSRet = false;
1629  bool SawSwiftSelf = false;
1630  bool SawSwiftError = false;
1631 
1632  // Verify return value attributes.
1633  AttributeSet RetAttrs = Attrs.getRetAttributes();
1634  Assert((!RetAttrs.hasAttribute(Attribute::ByVal) &&
1635  !RetAttrs.hasAttribute(Attribute::Nest) &&
1636  !RetAttrs.hasAttribute(Attribute::StructRet) &&
1637  !RetAttrs.hasAttribute(Attribute::NoCapture) &&
1638  !RetAttrs.hasAttribute(Attribute::Returned) &&
1639  !RetAttrs.hasAttribute(Attribute::InAlloca) &&
1640  !RetAttrs.hasAttribute(Attribute::SwiftSelf) &&
1641  !RetAttrs.hasAttribute(Attribute::SwiftError)),
1642  "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', "
1643  "'returned', 'swiftself', and 'swifterror' do not apply to return "
1644  "values!",
1645  V);
1646  Assert((!RetAttrs.hasAttribute(Attribute::ReadOnly) &&
1647  !RetAttrs.hasAttribute(Attribute::WriteOnly) &&
1648  !RetAttrs.hasAttribute(Attribute::ReadNone)),
1649  "Attribute '" + RetAttrs.getAsString() +
1650  "' does not apply to function returns",
1651  V);
1652  verifyParameterAttrs(RetAttrs, FT->getReturnType(), V);
1653 
1654  // Verify parameter attributes.
1655  for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1656  Type *Ty = FT->getParamType(i);
1657  AttributeSet ArgAttrs = Attrs.getParamAttributes(i);
1658 
1659  verifyParameterAttrs(ArgAttrs, Ty, V);
1660 
1661  if (ArgAttrs.hasAttribute(Attribute::Nest)) {
1662  Assert(!SawNest, "More than one parameter has attribute nest!", V);
1663  SawNest = true;
1664  }
1665 
1666  if (ArgAttrs.hasAttribute(Attribute::Returned)) {
1667  Assert(!SawReturned, "More than one parameter has attribute returned!",
1668  V);
1670  "Incompatible argument and return types for 'returned' attribute",
1671  V);
1672  SawReturned = true;
1673  }
1674 
1675  if (ArgAttrs.hasAttribute(Attribute::StructRet)) {
1676  Assert(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
1677  Assert(i == 0 || i == 1,
1678  "Attribute 'sret' is not on first or second parameter!", V);
1679  SawSRet = true;
1680  }
1681 
1682  if (ArgAttrs.hasAttribute(Attribute::SwiftSelf)) {
1683  Assert(!SawSwiftSelf, "Cannot have multiple 'swiftself' parameters!", V);
1684  SawSwiftSelf = true;
1685  }
1686 
1687  if (ArgAttrs.hasAttribute(Attribute::SwiftError)) {
1688  Assert(!SawSwiftError, "Cannot have multiple 'swifterror' parameters!",
1689  V);
1690  SawSwiftError = true;
1691  }
1692 
1693  if (ArgAttrs.hasAttribute(Attribute::InAlloca)) {
1694  Assert(i == FT->getNumParams() - 1,
1695  "inalloca isn't on the last parameter!", V);
1696  }
1697  }
1698 
1700  return;
1701 
1702  verifyAttributeTypes(Attrs.getFnAttributes(), /*IsFunction=*/true, V);
1703 
1704  Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
1705  Attrs.hasFnAttribute(Attribute::ReadOnly)),
1706  "Attributes 'readnone and readonly' are incompatible!", V);
1707 
1708  Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
1709  Attrs.hasFnAttribute(Attribute::WriteOnly)),
1710  "Attributes 'readnone and writeonly' are incompatible!", V);
1711 
1712  Assert(!(Attrs.hasFnAttribute(Attribute::ReadOnly) &&
1713  Attrs.hasFnAttribute(Attribute::WriteOnly)),
1714  "Attributes 'readonly and writeonly' are incompatible!", V);
1715 
1716  Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
1717  Attrs.hasFnAttribute(Attribute::InaccessibleMemOrArgMemOnly)),
1718  "Attributes 'readnone and inaccessiblemem_or_argmemonly' are "
1719  "incompatible!",
1720  V);
1721 
1722  Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
1723  Attrs.hasFnAttribute(Attribute::InaccessibleMemOnly)),
1724  "Attributes 'readnone and inaccessiblememonly' are incompatible!", V);
1725 
1726  Assert(!(Attrs.hasFnAttribute(Attribute::NoInline) &&
1727  Attrs.hasFnAttribute(Attribute::AlwaysInline)),
1728  "Attributes 'noinline and alwaysinline' are incompatible!", V);
1729 
1730  if (Attrs.hasFnAttribute(Attribute::OptimizeNone)) {
1731  Assert(Attrs.hasFnAttribute(Attribute::NoInline),
1732  "Attribute 'optnone' requires 'noinline'!", V);
1733 
1734  Assert(!Attrs.hasFnAttribute(Attribute::OptimizeForSize),
1735  "Attributes 'optsize and optnone' are incompatible!", V);
1736 
1737  Assert(!Attrs.hasFnAttribute(Attribute::MinSize),
1738  "Attributes 'minsize and optnone' are incompatible!", V);
1739  }
1740 
1741  if (Attrs.hasFnAttribute(Attribute::JumpTable)) {
1742  const GlobalValue *GV = cast<GlobalValue>(V);
1744  "Attribute 'jumptable' requires 'unnamed_addr'", V);
1745  }
1746 
1747  if (Attrs.hasFnAttribute(Attribute::AllocSize)) {
1748  std::pair<unsigned, Optional<unsigned>> Args =
1750 
1751  auto CheckParam = [&](StringRef Name, unsigned ParamNo) {
1752  if (ParamNo >= FT->getNumParams()) {
1753  CheckFailed("'allocsize' " + Name + " argument is out of bounds", V);
1754  return false;
1755  }
1756 
1757  if (!FT->getParamType(ParamNo)->isIntegerTy()) {
1758  CheckFailed("'allocsize' " + Name +
1759  " argument must refer to an integer parameter",
1760  V);
1761  return false;
1762  }
1763 
1764  return true;
1765  };
1766 
1767  if (!CheckParam("element size", Args.first))
1768  return;
1769 
1770  if (Args.second && !CheckParam("number of elements", *Args.second))
1771  return;
1772  }
1773 }
1774 
1775 void Verifier::verifyFunctionMetadata(
1776  ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
1777  for (const auto &Pair : MDs) {
1778  if (Pair.first == LLVMContext::MD_prof) {
1779  MDNode *MD = Pair.second;
1780  Assert(MD->getNumOperands() >= 2,
1781  "!prof annotations should have no less than 2 operands", MD);
1782 
1783  // Check first operand.
1784  Assert(MD->getOperand(0) != nullptr, "first operand should not be null",
1785  MD);
1786  Assert(isa<MDString>(MD->getOperand(0)),
1787  "expected string with name of the !prof annotation", MD);
1788  MDString *MDS = cast<MDString>(MD->getOperand(0));
1789  StringRef ProfName = MDS->getString();
1790  Assert(ProfName.equals("function_entry_count") ||
1791  ProfName.equals("synthetic_function_entry_count"),
1792  "first operand should be 'function_entry_count'"
1793  " or 'synthetic_function_entry_count'",
1794  MD);
1795 
1796  // Check second operand.
1797  Assert(MD->getOperand(1) != nullptr, "second operand should not be null",
1798  MD);
1799  Assert(isa<ConstantAsMetadata>(MD->getOperand(1)),
1800  "expected integer argument to function_entry_count", MD);
1801  }
1802  }
1803 }
1804 
1805 void Verifier::visitConstantExprsRecursively(const Constant *EntryC) {
1806  if (!ConstantExprVisited.insert(EntryC).second)
1807  return;
1808 
1810  Stack.push_back(EntryC);
1811 
1812  while (!Stack.empty()) {
1813  const Constant *C = Stack.pop_back_val();
1814 
1815  // Check this constant expression.
1816  if (const auto *CE = dyn_cast<ConstantExpr>(C))
1817  visitConstantExpr(CE);
1818 
1819  if (const auto *GV = dyn_cast<GlobalValue>(C)) {
1820  // Global Values get visited separately, but we do need to make sure
1821  // that the global value is in the correct module
1822  Assert(GV->getParent() == &M, "Referencing global in another module!",
1823  EntryC, &M, GV, GV->getParent());
1824  continue;
1825  }
1826 
1827  // Visit all sub-expressions.
1828  for (const Use &U : C->operands()) {
1829  const auto *OpC = dyn_cast<Constant>(U);
1830  if (!OpC)
1831  continue;
1832  if (!ConstantExprVisited.insert(OpC).second)
1833  continue;
1834  Stack.push_back(OpC);
1835  }
1836  }
1837 }
1838 
1839 void Verifier::visitConstantExpr(const ConstantExpr *CE) {
1840  if (CE->getOpcode() == Instruction::BitCast)
1841  Assert(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
1842  CE->getType()),
1843  "Invalid bitcast", CE);
1844 
1845  if (CE->getOpcode() == Instruction::IntToPtr ||
1846  CE->getOpcode() == Instruction::PtrToInt) {
1847  auto *PtrTy = CE->getOpcode() == Instruction::IntToPtr
1848  ? CE->getType()
1849  : CE->getOperand(0)->getType();
1850  StringRef Msg = CE->getOpcode() == Instruction::IntToPtr
1851  ? "inttoptr not supported for non-integral pointers"
1852  : "ptrtoint not supported for non-integral pointers";
1853  Assert(
1854  !DL.isNonIntegralPointerType(cast<PointerType>(PtrTy->getScalarType())),
1855  Msg);
1856  }
1857 }
1858 
1859 bool Verifier::verifyAttributeCount(AttributeList Attrs, unsigned Params) {
1860  // There shouldn't be more attribute sets than there are parameters plus the
1861  // function and return value.
1862  return Attrs.getNumAttrSets() <= Params + 2;
1863 }
1864 
1865 /// Verify that statepoint intrinsic is well formed.
1866 void Verifier::verifyStatepoint(ImmutableCallSite CS) {
1867  assert(CS.getCalledFunction() &&
1869  Intrinsic::experimental_gc_statepoint);
1870 
1871  const Instruction &CI = *CS.getInstruction();
1872 
1873  Assert(!CS.doesNotAccessMemory() && !CS.onlyReadsMemory() &&
1874  !CS.onlyAccessesArgMemory(),
1875  "gc.statepoint must read and write all memory to preserve "
1876  "reordering restrictions required by safepoint semantics",
1877  &CI);
1878 
1879  const Value *IDV = CS.getArgument(0);
1880  Assert(isa<ConstantInt>(IDV), "gc.statepoint ID must be a constant integer",
1881  &CI);
1882 
1883  const Value *NumPatchBytesV = CS.getArgument(1);
1884  Assert(isa<ConstantInt>(NumPatchBytesV),
1885  "gc.statepoint number of patchable bytes must be a constant integer",
1886  &CI);
1887  const int64_t NumPatchBytes =
1888  cast<ConstantInt>(NumPatchBytesV)->getSExtValue();
1889  assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!");
1890  Assert(NumPatchBytes >= 0, "gc.statepoint number of patchable bytes must be "
1891  "positive",
1892  &CI);
1893 
1894  const Value *Target = CS.getArgument(2);
1895  auto *PT = dyn_cast<PointerType>(Target->getType());
1896  Assert(PT && PT->getElementType()->isFunctionTy(),
1897  "gc.statepoint callee must be of function pointer type", &CI, Target);
1898  FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType());
1899 
1900  const Value *NumCallArgsV = CS.getArgument(3);
1901  Assert(isa<ConstantInt>(NumCallArgsV),
1902  "gc.statepoint number of arguments to underlying call "
1903  "must be constant integer",
1904  &CI);
1905  const int NumCallArgs = cast<ConstantInt>(NumCallArgsV)->getZExtValue();
1906  Assert(NumCallArgs >= 0,
1907  "gc.statepoint number of arguments to underlying call "
1908  "must be positive",
1909  &CI);
1910  const int NumParams = (int)TargetFuncType->getNumParams();
1911  if (TargetFuncType->isVarArg()) {
1912  Assert(NumCallArgs >= NumParams,
1913  "gc.statepoint mismatch in number of vararg call args", &CI);
1914 
1915  // TODO: Remove this limitation
1916  Assert(TargetFuncType->getReturnType()->isVoidTy(),
1917  "gc.statepoint doesn't support wrapping non-void "
1918  "vararg functions yet",
1919  &CI);
1920  } else
1921  Assert(NumCallArgs == NumParams,
1922  "gc.statepoint mismatch in number of call args", &CI);
1923 
1924  const Value *FlagsV = CS.getArgument(4);
1925  Assert(isa<ConstantInt>(FlagsV),
1926  "gc.statepoint flags must be constant integer", &CI);
1927  const uint64_t Flags = cast<ConstantInt>(FlagsV)->getZExtValue();
1928  Assert((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
1929  "unknown flag used in gc.statepoint flags argument", &CI);
1930 
1931  // Verify that the types of the call parameter arguments match
1932  // the type of the wrapped callee.
1933  AttributeList Attrs = CS.getAttributes();
1934  for (int i = 0; i < NumParams; i++) {
1935  Type *ParamType = TargetFuncType->getParamType(i);
1936  Type *ArgType = CS.getArgument(5 + i)->getType();
1937  Assert(ArgType == ParamType,
1938  "gc.statepoint call argument does not match wrapped "
1939  "function type",
1940  &CI);
1941 
1942  if (TargetFuncType->isVarArg()) {
1943  AttributeSet ArgAttrs = Attrs.getParamAttributes(5 + i);
1944  Assert(!ArgAttrs.hasAttribute(Attribute::StructRet),
1945  "Attribute 'sret' cannot be used for vararg call arguments!", &CI);
1946  }
1947  }
1948 
1949  const int EndCallArgsInx = 4 + NumCallArgs;
1950 
1951  const Value *NumTransitionArgsV = CS.getArgument(EndCallArgsInx+1);
1952  Assert(isa<ConstantInt>(NumTransitionArgsV),
1953  "gc.statepoint number of transition arguments "
1954  "must be constant integer",
1955  &CI);
1956  const int NumTransitionArgs =
1957  cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
1958  Assert(NumTransitionArgs >= 0,
1959  "gc.statepoint number of transition arguments must be positive", &CI);
1960  const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
1961 
1962  const Value *NumDeoptArgsV = CS.getArgument(EndTransitionArgsInx+1);
1963  Assert(isa<ConstantInt>(NumDeoptArgsV),
1964  "gc.statepoint number of deoptimization arguments "
1965  "must be constant integer",
1966  &CI);
1967  const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
1968  Assert(NumDeoptArgs >= 0, "gc.statepoint number of deoptimization arguments "
1969  "must be positive",
1970  &CI);
1971 
1972  const int ExpectedNumArgs =
1973  7 + NumCallArgs + NumTransitionArgs + NumDeoptArgs;
1974  Assert(ExpectedNumArgs <= (int)CS.arg_size(),
1975  "gc.statepoint too few arguments according to length fields", &CI);
1976 
1977  // Check that the only uses of this gc.statepoint are gc.result or
1978  // gc.relocate calls which are tied to this statepoint and thus part
1979  // of the same statepoint sequence
1980  for (const User *U : CI.users()) {
1981  const CallInst *Call = dyn_cast<const CallInst>(U);
1982  Assert(Call, "illegal use of statepoint token", &CI, U);
1983  if (!Call) continue;
1984  Assert(isa<GCRelocateInst>(Call) || isa<GCResultInst>(Call),
1985  "gc.result or gc.relocate are the only value uses "
1986  "of a gc.statepoint",
1987  &CI, U);
1988  if (isa<GCResultInst>(Call)) {
1989  Assert(Call->getArgOperand(0) == &CI,
1990  "gc.result connected to wrong gc.statepoint", &CI, Call);
1991  } else if (isa<GCRelocateInst>(Call)) {
1992  Assert(Call->getArgOperand(0) == &CI,
1993  "gc.relocate connected to wrong gc.statepoint", &CI, Call);
1994  }
1995  }
1996 
1997  // Note: It is legal for a single derived pointer to be listed multiple
1998  // times. It's non-optimal, but it is legal. It can also happen after
1999  // insertion if we strip a bitcast away.
2000  // Note: It is really tempting to check that each base is relocated and
2001  // that a derived pointer is never reused as a base pointer. This turns
2002  // out to be problematic since optimizations run after safepoint insertion
2003  // can recognize equality properties that the insertion logic doesn't know
2004  // about. See example statepoint.ll in the verifier subdirectory
2005 }
2006 
2007 void Verifier::verifyFrameRecoverIndices() {
2008  for (auto &Counts : FrameEscapeInfo) {
2009  Function *F = Counts.first;
2010  unsigned EscapedObjectCount = Counts.second.first;
2011  unsigned MaxRecoveredIndex = Counts.second.second;
2012  Assert(MaxRecoveredIndex <= EscapedObjectCount,
2013  "all indices passed to llvm.localrecover must be less than the "
2014  "number of arguments passed ot llvm.localescape in the parent "
2015  "function",
2016  F);
2017  }
2018 }
2019 
2021  BasicBlock *UnwindDest;
2022  if (auto *II = dyn_cast<InvokeInst>(Terminator))
2023  UnwindDest = II->getUnwindDest();
2024  else if (auto *CSI = dyn_cast<CatchSwitchInst>(Terminator))
2025  UnwindDest = CSI->getUnwindDest();
2026  else
2027  UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest();
2028  return UnwindDest->getFirstNonPHI();
2029 }
2030 
2031 void Verifier::verifySiblingFuncletUnwinds() {
2034  for (const auto &Pair : SiblingFuncletInfo) {
2035  Instruction *PredPad = Pair.first;
2036  if (Visited.count(PredPad))
2037  continue;
2038  Active.insert(PredPad);
2039  Instruction *Terminator = Pair.second;
2040  do {
2041  Instruction *SuccPad = getSuccPad(Terminator);
2042  if (Active.count(SuccPad)) {
2043  // Found a cycle; report error
2044  Instruction *CyclePad = SuccPad;
2045  SmallVector<Instruction *, 8> CycleNodes;
2046  do {
2047  CycleNodes.push_back(CyclePad);
2048  Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
2049  if (CycleTerminator != CyclePad)
2050  CycleNodes.push_back(CycleTerminator);
2051  CyclePad = getSuccPad(CycleTerminator);
2052  } while (CyclePad != SuccPad);
2053  Assert(false, "EH pads can't handle each other's exceptions",
2054  ArrayRef<Instruction *>(CycleNodes));
2055  }
2056  // Don't re-walk a node we've already checked
2057  if (!Visited.insert(SuccPad).second)
2058  break;
2059  // Walk to this successor if it has a map entry.
2060  PredPad = SuccPad;
2061  auto TermI = SiblingFuncletInfo.find(PredPad);
2062  if (TermI == SiblingFuncletInfo.end())
2063  break;
2064  Terminator = TermI->second;
2065  Active.insert(PredPad);
2066  } while (true);
2067  // Each node only has one successor, so we've walked all the active
2068  // nodes' successors.
2069  Active.clear();
2070  }
2071 }
2072 
2073 // visitFunction - Verify that a function is ok.
2074 //
2075 void Verifier::visitFunction(const Function &F) {
2076  visitGlobalValue(F);
2077 
2078  // Check function arguments.
2079  FunctionType *FT = F.getFunctionType();
2080  unsigned NumArgs = F.arg_size();
2081 
2082  Assert(&Context == &F.getContext(),
2083  "Function context does not match Module context!", &F);
2084 
2085  Assert(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
2086  Assert(FT->getNumParams() == NumArgs,
2087  "# formal arguments must match # of arguments for function type!", &F,
2088  FT);
2089  Assert(F.getReturnType()->isFirstClassType() ||
2090  F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
2091  "Functions cannot return aggregate values!", &F);
2092 
2093  Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
2094  "Invalid struct return type!", &F);
2095 
2096  AttributeList Attrs = F.getAttributes();
2097 
2098  Assert(verifyAttributeCount(Attrs, FT->getNumParams()),
2099  "Attribute after last parameter!", &F);
2100 
2101  // Check function attributes.
2102  verifyFunctionAttrs(FT, Attrs, &F);
2103 
2104  // On function declarations/definitions, we do not support the builtin
2105  // attribute. We do not check this in VerifyFunctionAttrs since that is
2106  // checking for Attributes that can/can not ever be on functions.
2107  Assert(!Attrs.hasFnAttribute(Attribute::Builtin),
2108  "Attribute 'builtin' can only be applied to a callsite.", &F);
2109 
2110  // Check that this function meets the restrictions on this calling convention.
2111  // Sometimes varargs is used for perfectly forwarding thunks, so some of these
2112  // restrictions can be lifted.
2113  switch (F.getCallingConv()) {
2114  default:
2115  case CallingConv::C:
2116  break;
2119  Assert(F.getReturnType()->isVoidTy(),
2120  "Calling convention requires void return type", &F);
2127  Assert(!F.hasStructRetAttr(),
2128  "Calling convention does not allow sret", &F);
2130  case CallingConv::Fast:
2131  case CallingConv::Cold:
2135  Assert(!F.isVarArg(), "Calling convention does not support varargs or "
2136  "perfect forwarding!",
2137  &F);
2138  break;
2139  }
2140 
2141  bool isLLVMdotName = F.getName().size() >= 5 &&
2142  F.getName().substr(0, 5) == "llvm.";
2143 
2144  // Check that the argument values match the function type for this function...
2145  unsigned i = 0;
2146  for (const Argument &Arg : F.args()) {
2147  Assert(Arg.getType() == FT->getParamType(i),
2148  "Argument value does not match function argument type!", &Arg,
2149  FT->getParamType(i));
2151  "Function arguments must have first-class types!", &Arg);
2152  if (!isLLVMdotName) {
2154  "Function takes metadata but isn't an intrinsic", &Arg, &F);
2155  Assert(!Arg.getType()->isTokenTy(),
2156  "Function takes token but isn't an intrinsic", &Arg, &F);
2157  }
2158 
2159  // Check that swifterror argument is only used by loads and stores.
2160  if (Attrs.hasParamAttribute(i, Attribute::SwiftError)) {
2161  verifySwiftErrorValue(&Arg);
2162  }
2163  ++i;
2164  }
2165 
2166  if (!isLLVMdotName)
2167  Assert(!F.getReturnType()->isTokenTy(),
2168  "Functions returns a token but isn't an intrinsic", &F);
2169 
2170  // Get the function metadata attachments.
2172  F.getAllMetadata(MDs);
2173  assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync");
2174  verifyFunctionMetadata(MDs);
2175 
2176  // Check validity of the personality function
2177  if (F.hasPersonalityFn()) {
2178  auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
2179  if (Per)
2180  Assert(Per->getParent() == F.getParent(),
2181  "Referencing personality function in another module!",
2182  &F, F.getParent(), Per, Per->getParent());
2183  }
2184 
2185  if (F.isMaterializable()) {
2186  // Function has a body somewhere we can't see.
2187  Assert(MDs.empty(), "unmaterialized function cannot have metadata", &F,
2188  MDs.empty() ? nullptr : MDs.front().second);
2189  } else if (F.isDeclaration()) {
2190  for (const auto &I : MDs) {
2191  AssertDI(I.first != LLVMContext::MD_dbg,
2192  "function declaration may not have a !dbg attachment", &F);
2193  Assert(I.first != LLVMContext::MD_prof,
2194  "function declaration may not have a !prof attachment", &F);
2195 
2196  // Verify the metadata itself.
2197  visitMDNode(*I.second);
2198  }
2199  Assert(!F.hasPersonalityFn(),
2200  "Function declaration shouldn't have a personality routine", &F);
2201  } else {
2202  // Verify that this function (which has a body) is not named "llvm.*". It
2203  // is not legal to define intrinsics.
2204  Assert(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
2205 
2206  // Check the entry node
2207  const BasicBlock *Entry = &F.getEntryBlock();
2208  Assert(pred_empty(Entry),
2209  "Entry block to function must not have predecessors!", Entry);
2210 
2211  // The address of the entry block cannot be taken, unless it is dead.
2212  if (Entry->hasAddressTaken()) {
2213  Assert(!BlockAddress::lookup(Entry)->isConstantUsed(),
2214  "blockaddress may not be used with the entry block!", Entry);
2215  }
2216 
2217  unsigned NumDebugAttachments = 0, NumProfAttachments = 0;
2218  // Visit metadata attachments.
2219  for (const auto &I : MDs) {
2220  // Verify that the attachment is legal.
2221  switch (I.first) {
2222  default:
2223  break;
2224  case LLVMContext::MD_dbg: {
2225  ++NumDebugAttachments;
2226  AssertDI(NumDebugAttachments == 1,
2227  "function must have a single !dbg attachment", &F, I.second);
2228  AssertDI(isa<DISubprogram>(I.second),
2229  "function !dbg attachment must be a subprogram", &F, I.second);
2230  auto *SP = cast<DISubprogram>(I.second);
2231  const Function *&AttachedTo = DISubprogramAttachments[SP];
2232  AssertDI(!AttachedTo || AttachedTo == &F,
2233  "DISubprogram attached to more than one function", SP, &F);
2234  AttachedTo = &F;
2235  break;
2236  }
2237  case LLVMContext::MD_prof:
2238  ++NumProfAttachments;
2239  Assert(NumProfAttachments == 1,
2240  "function must have a single !prof attachment", &F, I.second);
2241  break;
2242  }
2243 
2244  // Verify the metadata itself.
2245  visitMDNode(*I.second);
2246  }
2247  }
2248 
2249  // If this function is actually an intrinsic, verify that it is only used in
2250  // direct call/invokes, never having its "address taken".
2251  // Only do this if the module is materialized, otherwise we don't have all the
2252  // uses.
2253  if (F.getIntrinsicID() && F.getParent()->isMaterialized()) {
2254  const User *U;
2255  if (F.hasAddressTaken(&U))
2256  Assert(false, "Invalid user of intrinsic instruction!", U);
2257  }
2258 
2259  auto *N = F.getSubprogram();
2260  HasDebugInfo = (N != nullptr);
2261  if (!HasDebugInfo)
2262  return;
2263 
2264  // Check that all !dbg attachments lead to back to N (or, at least, another
2265  // subprogram that describes the same function).
2266  //
2267  // FIXME: Check this incrementally while visiting !dbg attachments.
2268  // FIXME: Only check when N is the canonical subprogram for F.
2270  for (auto &BB : F)
2271  for (auto &I : BB) {
2272  // Be careful about using DILocation here since we might be dealing with
2273  // broken code (this is the Verifier after all).
2274  DILocation *DL =
2275  dyn_cast_or_null<DILocation>(I.getDebugLoc().getAsMDNode());
2276  if (!DL)
2277  continue;
2278  if (!Seen.insert(DL).second)
2279  continue;
2280 
2281  Metadata *Parent = DL->getRawScope();
2282  AssertDI(Parent && isa<DILocalScope>(Parent),
2283  "DILocation's scope must be a DILocalScope", N, &F, &I, DL,
2284  Parent);
2285  DILocalScope *Scope = DL->getInlinedAtScope();
2286  if (Scope && !Seen.insert(Scope).second)
2287  continue;
2288 
2289  DISubprogram *SP = Scope ? Scope->getSubprogram() : nullptr;
2290 
2291  // Scope and SP could be the same MDNode and we don't want to skip
2292  // validation in that case
2293  if (SP && ((Scope != SP) && !Seen.insert(SP).second))
2294  continue;
2295 
2296  // FIXME: Once N is canonical, check "SP == &N".
2297  AssertDI(SP->describes(&F),
2298  "!dbg attachment points at wrong subprogram for function", N, &F,
2299  &I, DL, Scope, SP);
2300  }
2301 }
2302 
2303 // verifyBasicBlock - Verify that a basic block is well formed...
2304 //
2305 void Verifier::visitBasicBlock(BasicBlock &BB) {
2306  InstsInThisBlock.clear();
2307 
2308  // Ensure that basic blocks have terminators!
2309  Assert(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
2310 
2311  // Check constraints that this basic block imposes on all of the PHI nodes in
2312  // it.
2313  if (isa<PHINode>(BB.front())) {
2316  llvm::sort(Preds);
2317  for (const PHINode &PN : BB.phis()) {
2318  // Ensure that PHI nodes have at least one entry!
2319  Assert(PN.getNumIncomingValues() != 0,
2320  "PHI nodes must have at least one entry. If the block is dead, "
2321  "the PHI should be removed!",
2322  &PN);
2323  Assert(PN.getNumIncomingValues() == Preds.size(),
2324  "PHINode should have one entry for each predecessor of its "
2325  "parent basic block!",
2326  &PN);
2327 
2328  // Get and sort all incoming values in the PHI node...
2329  Values.clear();
2330  Values.reserve(PN.getNumIncomingValues());
2331  for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
2332  Values.push_back(
2333  std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
2334  llvm::sort(Values);
2335 
2336  for (unsigned i = 0, e = Values.size(); i != e; ++i) {
2337  // Check to make sure that if there is more than one entry for a
2338  // particular basic block in this PHI node, that the incoming values are
2339  // all identical.
2340  //
2341  Assert(i == 0 || Values[i].first != Values[i - 1].first ||
2342  Values[i].second == Values[i - 1].second,
2343  "PHI node has multiple entries for the same basic block with "
2344  "different incoming values!",
2345  &PN, Values[i].first, Values[i].second, Values[i - 1].second);
2346 
2347  // Check to make sure that the predecessors and PHI node entries are
2348  // matched up.
2349  Assert(Values[i].first == Preds[i],
2350  "PHI node entries do not match predecessors!", &PN,
2351  Values[i].first, Preds[i]);
2352  }
2353  }
2354  }
2355 
2356  // Check that all instructions have their parent pointers set up correctly.
2357  for (auto &I : BB)
2358  {
2359  Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!");
2360  }
2361 }
2362 
2363 void Verifier::visitTerminator(Instruction &I) {
2364  // Ensure that terminators only exist at the end of the basic block.
2365  Assert(&I == I.getParent()->getTerminator(),
2366  "Terminator found in the middle of a basic block!", I.getParent());
2367  visitInstruction(I);
2368 }
2369 
2370 void Verifier::visitBranchInst(BranchInst &BI) {
2371  if (BI.isConditional()) {
2372  Assert(BI.getCondition()->getType()->isIntegerTy(1),
2373  "Branch condition is not 'i1' type!", &BI, BI.getCondition());
2374  }
2375  visitTerminator(BI);
2376 }
2377 
2378 void Verifier::visitReturnInst(ReturnInst &RI) {
2379  Function *F = RI.getParent()->getParent();
2380  unsigned N = RI.getNumOperands();
2381  if (F->getReturnType()->isVoidTy())
2382  Assert(N == 0,
2383  "Found return instr that returns non-void in Function of void "
2384  "return type!",
2385  &RI, F->getReturnType());
2386  else
2387  Assert(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
2388  "Function return type does not match operand "
2389  "type of return inst!",
2390  &RI, F->getReturnType());
2391 
2392  // Check to make sure that the return value has necessary properties for
2393  // terminators...
2394  visitTerminator(RI);
2395 }
2396 
2397 void Verifier::visitSwitchInst(SwitchInst &SI) {
2398  // Check to make sure that all of the constants in the switch instruction
2399  // have the same type as the switched-on value.
2400  Type *SwitchTy = SI.getCondition()->getType();
2402  for (auto &Case : SI.cases()) {
2403  Assert(Case.getCaseValue()->getType() == SwitchTy,
2404  "Switch constants must all be same type as switch value!", &SI);
2405  Assert(Constants.insert(Case.getCaseValue()).second,
2406  "Duplicate integer as switch case", &SI, Case.getCaseValue());
2407  }
2408 
2409  visitTerminator(SI);
2410 }
2411 
2412 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
2413  Assert(BI.getAddress()->getType()->isPointerTy(),
2414  "Indirectbr operand must have pointer type!", &BI);
2415  for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
2416  Assert(BI.getDestination(i)->getType()->isLabelTy(),
2417  "Indirectbr destinations must all have pointer type!", &BI);
2418 
2419  visitTerminator(BI);
2420 }
2421 
2422 void Verifier::visitSelectInst(SelectInst &SI) {
2424  SI.getOperand(2)),
2425  "Invalid operands for select instruction!", &SI);
2426 
2427  Assert(SI.getTrueValue()->getType() == SI.getType(),
2428  "Select values must have same type as select instruction!", &SI);
2429  visitInstruction(SI);
2430 }
2431 
2432 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
2433 /// a pass, if any exist, it's an error.
2434 ///
2435 void Verifier::visitUserOp1(Instruction &I) {
2436  Assert(false, "User-defined operators should not live outside of a pass!", &I);
2437 }
2438 
2439 void Verifier::visitTruncInst(TruncInst &I) {
2440  // Get the source and destination types
2441  Type *SrcTy = I.getOperand(0)->getType();
2442  Type *DestTy = I.getType();
2443 
2444  // Get the size of the types in bits, we'll need this later
2445  unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2446  unsigned DestBitSize = DestTy->getScalarSizeInBits();
2447 
2448  Assert(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
2449  Assert(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
2450  Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2451  "trunc source and destination must both be a vector or neither", &I);
2452  Assert(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
2453 
2454  visitInstruction(I);
2455 }
2456 
2457 void Verifier::visitZExtInst(ZExtInst &I) {
2458  // Get the source and destination types
2459  Type *SrcTy = I.getOperand(0)->getType();
2460  Type *DestTy = I.getType();
2461 
2462  // Get the size of the types in bits, we'll need this later
2463  Assert(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
2464  Assert(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
2465  Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2466  "zext source and destination must both be a vector or neither", &I);
2467  unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2468  unsigned DestBitSize = DestTy->getScalarSizeInBits();
2469 
2470  Assert(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
2471 
2472  visitInstruction(I);
2473 }
2474 
2475 void Verifier::visitSExtInst(SExtInst &I) {
2476  // Get the source and destination types
2477  Type *SrcTy = I.getOperand(0)->getType();
2478  Type *DestTy = I.getType();
2479 
2480  // Get the size of the types in bits, we'll need this later
2481  unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2482  unsigned DestBitSize = DestTy->getScalarSizeInBits();
2483 
2484  Assert(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
2485  Assert(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
2486  Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2487  "sext source and destination must both be a vector or neither", &I);
2488  Assert(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
2489 
2490  visitInstruction(I);
2491 }
2492 
2493 void Verifier::visitFPTruncInst(FPTruncInst &I) {
2494  // Get the source and destination types
2495  Type *SrcTy = I.getOperand(0)->getType();
2496  Type *DestTy = I.getType();
2497  // Get the size of the types in bits, we'll need this later
2498  unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2499  unsigned DestBitSize = DestTy->getScalarSizeInBits();
2500 
2501  Assert(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
2502  Assert(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
2503  Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2504  "fptrunc source and destination must both be a vector or neither", &I);
2505  Assert(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
2506 
2507  visitInstruction(I);
2508 }
2509 
2510 void Verifier::visitFPExtInst(FPExtInst &I) {
2511  // Get the source and destination types
2512  Type *SrcTy = I.getOperand(0)->getType();
2513  Type *DestTy = I.getType();
2514 
2515  // Get the size of the types in bits, we'll need this later
2516  unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2517  unsigned DestBitSize = DestTy->getScalarSizeInBits();
2518 
2519  Assert(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
2520  Assert(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
2521  Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2522  "fpext source and destination must both be a vector or neither", &I);
2523  Assert(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
2524 
2525  visitInstruction(I);
2526 }
2527 
2528 void Verifier::visitUIToFPInst(UIToFPInst &I) {
2529  // Get the source and destination types
2530  Type *SrcTy = I.getOperand(0)->getType();
2531  Type *DestTy = I.getType();
2532 
2533  bool SrcVec = SrcTy->isVectorTy();
2534  bool DstVec = DestTy->isVectorTy();
2535 
2536  Assert(SrcVec == DstVec,
2537  "UIToFP source and dest must both be vector or scalar", &I);
2538  Assert(SrcTy->isIntOrIntVectorTy(),
2539  "UIToFP source must be integer or integer vector", &I);
2540  Assert(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
2541  &I);
2542 
2543  if (SrcVec && DstVec)
2544  Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2545  cast<VectorType>(DestTy)->getNumElements(),
2546  "UIToFP source and dest vector length mismatch", &I);
2547 
2548  visitInstruction(I);
2549 }
2550 
2551 void Verifier::visitSIToFPInst(SIToFPInst &I) {
2552  // Get the source and destination types
2553  Type *SrcTy = I.getOperand(0)->getType();
2554  Type *DestTy = I.getType();
2555 
2556  bool SrcVec = SrcTy->isVectorTy();
2557  bool DstVec = DestTy->isVectorTy();
2558 
2559  Assert(SrcVec == DstVec,
2560  "SIToFP source and dest must both be vector or scalar", &I);
2561  Assert(SrcTy->isIntOrIntVectorTy(),
2562  "SIToFP source must be integer or integer vector", &I);
2563  Assert(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
2564  &I);
2565 
2566  if (SrcVec && DstVec)
2567  Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2568  cast<VectorType>(DestTy)->getNumElements(),
2569  "SIToFP source and dest vector length mismatch", &I);
2570 
2571  visitInstruction(I);
2572 }
2573 
2574 void Verifier::visitFPToUIInst(FPToUIInst &I) {
2575  // Get the source and destination types
2576  Type *SrcTy = I.getOperand(0)->getType();
2577  Type *DestTy = I.getType();
2578 
2579  bool SrcVec = SrcTy->isVectorTy();
2580  bool DstVec = DestTy->isVectorTy();
2581 
2582  Assert(SrcVec == DstVec,
2583  "FPToUI source and dest must both be vector or scalar", &I);
2584  Assert(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
2585  &I);
2586  Assert(DestTy->isIntOrIntVectorTy(),
2587  "FPToUI result must be integer or integer vector", &I);
2588 
2589  if (SrcVec && DstVec)
2590  Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2591  cast<VectorType>(DestTy)->getNumElements(),
2592  "FPToUI source and dest vector length mismatch", &I);
2593 
2594  visitInstruction(I);
2595 }
2596 
2597 void Verifier::visitFPToSIInst(FPToSIInst &I) {
2598  // Get the source and destination types
2599  Type *SrcTy = I.getOperand(0)->getType();
2600  Type *DestTy = I.getType();
2601 
2602  bool SrcVec = SrcTy->isVectorTy();
2603  bool DstVec = DestTy->isVectorTy();
2604 
2605  Assert(SrcVec == DstVec,
2606  "FPToSI source and dest must both be vector or scalar", &I);
2607  Assert(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector",
2608  &I);
2609  Assert(DestTy->isIntOrIntVectorTy(),
2610  "FPToSI result must be integer or integer vector", &I);
2611 
2612  if (SrcVec && DstVec)
2613  Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2614  cast<VectorType>(DestTy)->getNumElements(),
2615  "FPToSI source and dest vector length mismatch", &I);
2616 
2617  visitInstruction(I);
2618 }
2619 
2620 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
2621  // Get the source and destination types
2622  Type *SrcTy = I.getOperand(0)->getType();
2623  Type *DestTy = I.getType();
2624 
2625  Assert(SrcTy->isPtrOrPtrVectorTy(), "PtrToInt source must be pointer", &I);
2626 
2627  if (auto *PTy = dyn_cast<PointerType>(SrcTy->getScalarType()))
2629  "ptrtoint not supported for non-integral pointers");
2630 
2631  Assert(DestTy->isIntOrIntVectorTy(), "PtrToInt result must be integral", &I);
2632  Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
2633  &I);
2634 
2635  if (SrcTy->isVectorTy()) {
2636  VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
2637  VectorType *VDest = dyn_cast<VectorType>(DestTy);
2638  Assert(VSrc->getNumElements() == VDest->getNumElements(),
2639  "PtrToInt Vector width mismatch", &I);
2640  }
2641 
2642  visitInstruction(I);
2643 }
2644 
2645 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
2646  // Get the source and destination types
2647  Type *SrcTy = I.getOperand(0)->getType();
2648  Type *DestTy = I.getType();
2649 
2650  Assert(SrcTy->isIntOrIntVectorTy(),
2651  "IntToPtr source must be an integral", &I);
2652  Assert(DestTy->isPtrOrPtrVectorTy(), "IntToPtr result must be a pointer", &I);
2653 
2654  if (auto *PTy = dyn_cast<PointerType>(DestTy->getScalarType()))
2656  "inttoptr not supported for non-integral pointers");
2657 
2658  Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
2659  &I);
2660  if (SrcTy->isVectorTy()) {
2661  VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
2662  VectorType *VDest = dyn_cast<VectorType>(DestTy);
2663  Assert(VSrc->getNumElements() == VDest->getNumElements(),
2664  "IntToPtr Vector width mismatch", &I);
2665  }
2666  visitInstruction(I);
2667 }
2668 
2669 void Verifier::visitBitCastInst(BitCastInst &I) {
2670  Assert(
2671  CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
2672  "Invalid bitcast", &I);
2673  visitInstruction(I);
2674 }
2675 
2676 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
2677  Type *SrcTy = I.getOperand(0)->getType();
2678  Type *DestTy = I.getType();
2679 
2680  Assert(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
2681  &I);
2682  Assert(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
2683  &I);
2685  "AddrSpaceCast must be between different address spaces", &I);
2686  if (SrcTy->isVectorTy())
2687  Assert(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(),
2688  "AddrSpaceCast vector pointer number of elements mismatch", &I);
2689  visitInstruction(I);
2690 }
2691 
2692 /// visitPHINode - Ensure that a PHI node is well formed.
2693 ///
2694 void Verifier::visitPHINode(PHINode &PN) {
2695  // Ensure that the PHI nodes are all grouped together at the top of the block.
2696  // This can be tested by checking whether the instruction before this is
2697  // either nonexistent (because this is begin()) or is a PHI node. If not,
2698  // then there is some other instruction before a PHI.
2699  Assert(&PN == &PN.getParent()->front() ||
2700  isa<PHINode>(--BasicBlock::iterator(&PN)),
2701  "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
2702 
2703  // Check that a PHI doesn't yield a Token.
2704  Assert(!PN.getType()->isTokenTy(), "PHI nodes cannot have token type!");
2705 
2706  // Check that all of the values of the PHI node have the same type as the
2707  // result, and that the incoming blocks are really basic blocks.
2708  for (Value *IncValue : PN.incoming_values()) {
2709  Assert(PN.getType() == IncValue->getType(),
2710  "PHI node operands are not the same type as the result!", &PN);
2711  }
2712 
2713  // All other PHI node constraints are checked in the visitBasicBlock method.
2714 
2715  visitInstruction(PN);
2716 }
2717 
2718 void Verifier::verifyCallSite(CallSite CS) {
2719  Instruction *I = CS.getInstruction();
2720 
2722  "Called function must be a pointer!", I);
2723  PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
2724 
2725  Assert(FPTy->getElementType()->isFunctionTy(),
2726  "Called function is not pointer to function type!", I);
2727 
2728  Assert(FPTy->getElementType() == CS.getFunctionType(),
2729  "Called function is not the same type as the call!", I);
2730 
2731  FunctionType *FTy = CS.getFunctionType();
2732 
2733  // Verify that the correct number of arguments are being passed
2734  if (FTy->isVarArg())
2735  Assert(CS.arg_size() >= FTy->getNumParams(),
2736  "Called function requires more parameters than were provided!", I);
2737  else
2738  Assert(CS.arg_size() == FTy->getNumParams(),
2739  "Incorrect number of arguments passed to called function!", I);
2740 
2741  // Verify that all arguments to the call match the function type.
2742  for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2743  Assert(CS.getArgument(i)->getType() == FTy->getParamType(i),
2744  "Call parameter type does not match function signature!",
2745  CS.getArgument(i), FTy->getParamType(i), I);
2746 
2747  AttributeList Attrs = CS.getAttributes();
2748 
2749  Assert(verifyAttributeCount(Attrs, CS.arg_size()),
2750  "Attribute after last parameter!", I);
2751 
2752  if (Attrs.hasAttribute(AttributeList::FunctionIndex, Attribute::Speculatable)) {
2753  // Don't allow speculatable on call sites, unless the underlying function
2754  // declaration is also speculatable.
2755  Function *Callee
2757  Assert(Callee && Callee->isSpeculatable(),
2758  "speculatable attribute may not apply to call sites", I);
2759  }
2760 
2761  // Verify call attributes.
2762  verifyFunctionAttrs(FTy, Attrs, I);
2763 
2764  // Conservatively check the inalloca argument.
2765  // We have a bug if we can find that there is an underlying alloca without
2766  // inalloca.
2767  if (CS.hasInAllocaArgument()) {
2768  Value *InAllocaArg = CS.getArgument(FTy->getNumParams() - 1);
2769  if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
2770  Assert(AI->isUsedWithInAlloca(),
2771  "inalloca argument for call has mismatched alloca", AI, I);
2772  }
2773 
2774  // For each argument of the callsite, if it has the swifterror argument,
2775  // make sure the underlying alloca/parameter it comes from has a swifterror as
2776  // well.
2777  for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2778  if (CS.paramHasAttr(i, Attribute::SwiftError)) {
2779  Value *SwiftErrorArg = CS.getArgument(i);
2780  if (auto AI = dyn_cast<AllocaInst>(SwiftErrorArg->stripInBoundsOffsets())) {
2781  Assert(AI->isSwiftError(),
2782  "swifterror argument for call has mismatched alloca", AI, I);
2783  continue;
2784  }
2785  auto ArgI = dyn_cast<Argument>(SwiftErrorArg);
2786  Assert(ArgI, "swifterror argument should come from an alloca or parameter", SwiftErrorArg, I);
2787  Assert(ArgI->hasSwiftErrorAttr(),
2788  "swifterror argument for call has mismatched parameter", ArgI, I);
2789  }
2790 
2791  if (FTy->isVarArg()) {
2792  // FIXME? is 'nest' even legal here?
2793  bool SawNest = false;
2794  bool SawReturned = false;
2795 
2796  for (unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) {
2797  if (Attrs.hasParamAttribute(Idx, Attribute::Nest))
2798  SawNest = true;
2799  if (Attrs.hasParamAttribute(Idx, Attribute::Returned))
2800  SawReturned = true;
2801  }
2802 
2803  // Check attributes on the varargs part.
2804  for (unsigned Idx = FTy->getNumParams(); Idx < CS.arg_size(); ++Idx) {
2805  Type *Ty = CS.getArgument(Idx)->getType();
2806  AttributeSet ArgAttrs = Attrs.getParamAttributes(Idx);
2807  verifyParameterAttrs(ArgAttrs, Ty, I);
2808 
2809  if (ArgAttrs.hasAttribute(Attribute::Nest)) {
2810  Assert(!SawNest, "More than one parameter has attribute nest!", I);
2811  SawNest = true;
2812  }
2813 
2814  if (ArgAttrs.hasAttribute(Attribute::Returned)) {
2815  Assert(!SawReturned, "More than one parameter has attribute returned!",
2816  I);
2817  Assert(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
2818  "Incompatible argument and return types for 'returned' "
2819  "attribute",
2820  I);
2821  SawReturned = true;
2822  }
2823 
2824  // Statepoint intrinsic is vararg but the wrapped function may be not.
2825  // Allow sret here and check the wrapped function in verifyStatepoint.
2826  if (CS.getCalledFunction() == nullptr ||
2828  Intrinsic::experimental_gc_statepoint)
2829  Assert(!ArgAttrs.hasAttribute(Attribute::StructRet),
2830  "Attribute 'sret' cannot be used for vararg call arguments!", I);
2831 
2832  if (ArgAttrs.hasAttribute(Attribute::InAlloca))
2833  Assert(Idx == CS.arg_size() - 1, "inalloca isn't on the last argument!",
2834  I);
2835  }
2836  }
2837 
2838  // Verify that there's no metadata unless it's a direct call to an intrinsic.
2839  if (CS.getCalledFunction() == nullptr ||
2840  !CS.getCalledFunction()->getName().startswith("llvm.")) {
2841  for (Type *ParamTy : FTy->params()) {
2842  Assert(!ParamTy->isMetadataTy(),
2843  "Function has metadata parameter but isn't an intrinsic", I);
2844  Assert(!ParamTy->isTokenTy(),
2845  "Function has token parameter but isn't an intrinsic", I);
2846  }
2847  }
2848 
2849  // Verify that indirect calls don't return tokens.
2850  if (CS.getCalledFunction() == nullptr)
2851  Assert(!FTy->getReturnType()->isTokenTy(),
2852  "Return type cannot be token for indirect call!");
2853 
2854  if (Function *F = CS.getCalledFunction())
2856  visitIntrinsicCallSite(ID, CS);
2857 
2858  // Verify that a callsite has at most one "deopt", at most one "funclet" and
2859  // at most one "gc-transition" operand bundle.
2860  bool FoundDeoptBundle = false, FoundFuncletBundle = false,
2861  FoundGCTransitionBundle = false;
2862  for (unsigned i = 0, e = CS.getNumOperandBundles(); i < e; ++i) {
2864  uint32_t Tag = BU.getTagID();
2865  if (Tag == LLVMContext::OB_deopt) {
2866  Assert(!FoundDeoptBundle, "Multiple deopt operand bundles", I);
2867  FoundDeoptBundle = true;
2868  } else if (Tag == LLVMContext::OB_gc_transition) {
2869  Assert(!FoundGCTransitionBundle, "Multiple gc-transition operand bundles",
2870  I);
2871  FoundGCTransitionBundle = true;
2872  } else if (Tag == LLVMContext::OB_funclet) {
2873  Assert(!FoundFuncletBundle, "Multiple funclet operand bundles", I);
2874  FoundFuncletBundle = true;
2875  Assert(BU.Inputs.size() == 1,
2876  "Expected exactly one funclet bundle operand", I);
2877  Assert(isa<FuncletPadInst>(BU.Inputs.front()),
2878  "Funclet bundle operands should correspond to a FuncletPadInst",
2879  I);
2880  }
2881  }
2882 
2883  // Verify that each inlinable callsite of a debug-info-bearing function in a
2884  // debug-info-bearing function has a debug location attached to it. Failure to
2885  // do so causes assertion failures when the inliner sets up inline scope info.
2886  if (I->getFunction()->getSubprogram() && CS.getCalledFunction() &&
2888  AssertDI(I->getDebugLoc(), "inlinable function call in a function with "
2889  "debug info must have a !dbg location",
2890  I);
2891 
2892  visitInstruction(*I);
2893 }
2894 
2895 /// Two types are "congruent" if they are identical, or if they are both pointer
2896 /// types with different pointee types and the same address space.
2897 static bool isTypeCongruent(Type *L, Type *R) {
2898  if (L == R)
2899  return true;
2902  if (!PL || !PR)
2903  return false;
2904  return PL->getAddressSpace() == PR->getAddressSpace();
2905 }
2906 
2908  static const Attribute::AttrKind ABIAttrs[] = {
2909  Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
2910  Attribute::InReg, Attribute::Returned, Attribute::SwiftSelf,
2911  Attribute::SwiftError};
2912  AttrBuilder Copy;
2913  for (auto AK : ABIAttrs) {
2914  if (Attrs.hasParamAttribute(I, AK))
2915  Copy.addAttribute(AK);
2916  }
2917  if (Attrs.hasParamAttribute(I, Attribute::Alignment))
2918  Copy.addAlignmentAttr(Attrs.getParamAlignment(I));
2919  return Copy;
2920 }
2921 
2922 void Verifier::verifyMustTailCall(CallInst &CI) {
2923  Assert(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
2924 
2925  // - The caller and callee prototypes must match. Pointer types of
2926  // parameters or return types may differ in pointee type, but not
2927  // address space.
2928  Function *F = CI.getParent()->getParent();
2929  FunctionType *CallerTy = F->getFunctionType();
2930  FunctionType *CalleeTy = CI.getFunctionType();
2931  if (!CI.getCalledFunction() || !CI.getCalledFunction()->isIntrinsic()) {
2932  Assert(CallerTy->getNumParams() == CalleeTy->getNumParams(),
2933  "cannot guarantee tail call due to mismatched parameter counts",
2934  &CI);
2935  for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
2936  Assert(
2937  isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
2938  "cannot guarantee tail call due to mismatched parameter types", &CI);
2939  }
2940  }
2941  Assert(CallerTy->isVarArg() == CalleeTy->isVarArg(),
2942  "cannot guarantee tail call due to mismatched varargs", &CI);
2943  Assert(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
2944  "cannot guarantee tail call due to mismatched return types", &CI);
2945 
2946  // - The calling conventions of the caller and callee must match.
2947  Assert(F->getCallingConv() == CI.getCallingConv(),
2948  "cannot guarantee tail call due to mismatched calling conv", &CI);
2949 
2950  // - All ABI-impacting function attributes, such as sret, byval, inreg,
2951  // returned, and inalloca, must match.
2952  AttributeList CallerAttrs = F->getAttributes();
2953  AttributeList CalleeAttrs = CI.getAttributes();
2954  for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
2955  AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs);
2956  AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs);
2957  Assert(CallerABIAttrs == CalleeABIAttrs,
2958  "cannot guarantee tail call due to mismatched ABI impacting "
2959  "function attributes",
2960  &CI, CI.getOperand(I));
2961  }
2962 
2963  // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
2964  // or a pointer bitcast followed by a ret instruction.
2965  // - The ret instruction must return the (possibly bitcasted) value
2966  // produced by the call or void.
2967  Value *RetVal = &CI;
2968  Instruction *Next = CI.getNextNode();
2969 
2970  // Handle the optional bitcast.
2971  if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
2972  Assert(BI->getOperand(0) == RetVal,
2973  "bitcast following musttail call must use the call", BI);
2974  RetVal = BI;
2975  Next = BI->getNextNode();
2976  }
2977 
2978  // Check the return.
2979  ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
2980  Assert(Ret, "musttail call must precede a ret with an optional bitcast",
2981  &CI);
2982  Assert(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal,
2983  "musttail call result must be returned", Ret);
2984 }
2985 
2986 void Verifier::visitCallInst(CallInst &CI) {
2987  verifyCallSite(&CI);
2988 
2989  if (CI.isMustTailCall())
2990  verifyMustTailCall(CI);
2991 }
2992 
2993 void Verifier::visitInvokeInst(InvokeInst &II) {
2994  verifyCallSite(&II);
2995 
2996  // Verify that the first non-PHI instruction of the unwind destination is an
2997  // exception handling instruction.
2998  Assert(
2999  II.getUnwindDest()->isEHPad(),
3000  "The unwind destination does not have an exception handling instruction!",
3001  &II);
3002 
3003  visitTerminator(II);
3004 }
3005 
3006 /// visitUnaryOperator - Check the argument to the unary operator.
3007 ///
3008 void Verifier::visitUnaryOperator(UnaryOperator &U) {
3009  Assert(U.getType() == U.getOperand(0)->getType(),
3010  "Unary operators must have same type for"
3011  "operands and result!",
3012  &U);
3013 
3014  switch (U.getOpcode()) {
3015  // Check that floating-point arithmetic operators are only used with
3016  // floating-point operands.
3017  case Instruction::FNeg:
3019  "FNeg operator only works with float types!", &U);
3020  break;
3021  default:
3022  llvm_unreachable("Unknown UnaryOperator opcode!");
3023  }
3024 
3025  visitInstruction(U);
3026 }
3027 
3028 /// visitBinaryOperator - Check that both arguments to the binary operator are
3029 /// of the same type!
3030 ///
3031 void Verifier::visitBinaryOperator(BinaryOperator &B) {
3032  Assert(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
3033  "Both operands to a binary operator are not of the same type!", &B);
3034 
3035  switch (B.getOpcode()) {
3036  // Check that integer arithmetic operators are only used with
3037  // integral operands.
3038  case Instruction::Add:
3039  case Instruction::Sub:
3040  case Instruction::Mul:
3041  case Instruction::SDiv:
3042  case Instruction::UDiv:
3043  case Instruction::SRem:
3044  case Instruction::URem:
3046  "Integer arithmetic operators only work with integral types!", &B);
3047  Assert(B.getType() == B.getOperand(0)->getType(),
3048  "Integer arithmetic operators must have same type "
3049  "for operands and result!",
3050  &B);
3051  break;
3052  // Check that floating-point arithmetic operators are only used with
3053  // floating-point operands.
3054  case Instruction::FAdd:
3055  case Instruction::FSub:
3056  case Instruction::FMul:
3057  case Instruction::FDiv:
3058  case Instruction::FRem:
3060  "Floating-point arithmetic operators only work with "
3061  "floating-point types!",
3062  &B);
3063  Assert(B.getType() == B.getOperand(0)->getType(),
3064  "Floating-point arithmetic operators must have same type "
3065  "for operands and result!",
3066  &B);
3067  break;
3068  // Check that logical operators are only used with integral operands.
3069  case Instruction::And:
3070  case Instruction::Or:
3071  case Instruction::Xor:
3073  "Logical operators only work with integral types!", &B);
3074  Assert(B.getType() == B.getOperand(0)->getType(),
3075  "Logical operators must have same type for operands and result!",
3076  &B);
3077  break;
3078  case Instruction::Shl:
3079  case Instruction::LShr:
3080  case Instruction::AShr:
3082  "Shifts only work with integral types!", &B);
3083  Assert(B.getType() == B.getOperand(0)->getType(),
3084  "Shift return type must be same as operands!", &B);
3085  break;
3086  default:
3087  llvm_unreachable("Unknown BinaryOperator opcode!");
3088  }
3089 
3090  visitInstruction(B);
3091 }
3092 
3093 void Verifier::visitICmpInst(ICmpInst &IC) {
3094  // Check that the operands are the same type
3095  Type *Op0Ty = IC.getOperand(0)->getType();
3096  Type *Op1Ty = IC.getOperand(1)->getType();
3097  Assert(Op0Ty == Op1Ty,
3098  "Both operands to ICmp instruction are not of the same type!", &IC);
3099  // Check that the operands are the right type
3100  Assert(Op0Ty->isIntOrIntVectorTy() || Op0Ty->isPtrOrPtrVectorTy(),
3101  "Invalid operand types for ICmp instruction", &IC);
3102  // Check that the predicate is valid.
3103  Assert(IC.isIntPredicate(),
3104  "Invalid predicate in ICmp instruction!", &IC);
3105 
3106  visitInstruction(IC);
3107 }
3108 
3109 void Verifier::visitFCmpInst(FCmpInst &FC) {
3110  // Check that the operands are the same type
3111  Type *Op0Ty = FC.getOperand(0)->getType();
3112  Type *Op1Ty = FC.getOperand(1)->getType();
3113  Assert(Op0Ty == Op1Ty,
3114  "Both operands to FCmp instruction are not of the same type!", &FC);
3115  // Check that the operands are the right type
3116  Assert(Op0Ty->isFPOrFPVectorTy(),
3117  "Invalid operand types for FCmp instruction", &FC);
3118  // Check that the predicate is valid.
3119  Assert(FC.isFPPredicate(),
3120  "Invalid predicate in FCmp instruction!", &FC);
3121 
3122  visitInstruction(FC);
3123 }
3124 
3125 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
3126  Assert(
3128  "Invalid extractelement operands!", &EI);
3129  visitInstruction(EI);
3130 }
3131 
3132 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
3134  IE.getOperand(2)),
3135  "Invalid insertelement operands!", &IE);
3136  visitInstruction(IE);
3137 }
3138 
3139 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
3141  SV.getOperand(2)),
3142  "Invalid shufflevector operands!", &SV);
3143  visitInstruction(SV);
3144 }
3145 
3146 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
3147  Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
3148 
3149  Assert(isa<PointerType>(TargetTy),
3150  "GEP base pointer is not a vector or a vector of pointers", &GEP);
3151  Assert(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP);
3152 
3153  SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
3154  Assert(all_of(
3155  Idxs, [](Value* V) { return V->getType()->isIntOrIntVectorTy(); }),
3156  "GEP indexes must be integers", &GEP);
3157  Type *ElTy =
3159  Assert(ElTy, "Invalid indices for GEP pointer type!", &GEP);
3160 
3161  Assert(GEP.getType()->isPtrOrPtrVectorTy() &&
3162  GEP.getResultElementType() == ElTy,
3163  "GEP is not of right type for indices!", &GEP, ElTy);
3164 
3165  if (GEP.getType()->isVectorTy()) {
3166  // Additional checks for vector GEPs.
3167  unsigned GEPWidth = GEP.getType()->getVectorNumElements();
3168  if (GEP.getPointerOperandType()->isVectorTy())
3169  Assert(GEPWidth == GEP.getPointerOperandType()->getVectorNumElements(),
3170  "Vector GEP result width doesn't match operand's", &GEP);
3171  for (Value *Idx : Idxs) {
3172  Type *IndexTy = Idx->getType();
3173  if (IndexTy->isVectorTy()) {
3174  unsigned IndexWidth = IndexTy->getVectorNumElements();
3175  Assert(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP);
3176  }
3177  Assert(IndexTy->isIntOrIntVectorTy(),
3178  "All GEP indices should be of integer type");
3179  }
3180  }
3181 
3182  if (auto *PTy = dyn_cast<PointerType>(GEP.getType())) {
3183  Assert(GEP.getAddressSpace() == PTy->getAddressSpace(),
3184  "GEP address space doesn't match type", &GEP);
3185  }
3186 
3187  visitInstruction(GEP);
3188 }
3189 
3190 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
3191  return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
3192 }
3193 
3194 void Verifier::visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty) {
3195  assert(Range && Range == I.getMetadata(LLVMContext::MD_range) &&
3196  "precondition violation");
3197 
3198  unsigned NumOperands = Range->getNumOperands();
3199  Assert(NumOperands % 2 == 0, "Unfinished range!", Range);
3200  unsigned NumRanges = NumOperands / 2;
3201  Assert(NumRanges >= 1, "It should have at least one range!", Range);
3202 
3203  ConstantRange LastRange(1); // Dummy initial value
3204  for (unsigned i = 0; i < NumRanges; ++i) {
3205  ConstantInt *Low =
3206  mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
3207  Assert(Low, "The lower limit must be an integer!", Low);
3208  ConstantInt *High =
3209  mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
3210  Assert(High, "The upper limit must be an integer!", High);
3211  Assert(High->getType() == Low->getType() && High->getType() == Ty,
3212  "Range types must match instruction type!", &I);
3213 
3214  APInt HighV = High->getValue();
3215  APInt LowV = Low->getValue();
3216  ConstantRange CurRange(LowV, HighV);
3217  Assert(!CurRange.isEmptySet() && !CurRange.isFullSet(),
3218  "Range must not be empty!", Range);
3219  if (i != 0) {
3220  Assert(CurRange.intersectWith(LastRange).isEmptySet(),
3221  "Intervals are overlapping", Range);
3222  Assert(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
3223  Range);
3224  Assert(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
3225  Range);
3226  }
3227  LastRange = ConstantRange(LowV, HighV);
3228  }
3229  if (NumRanges > 2) {
3230  APInt FirstLow =
3231  mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
3232  APInt FirstHigh =
3233  mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
3234  ConstantRange FirstRange(FirstLow, FirstHigh);
3235  Assert(FirstRange.intersectWith(LastRange).isEmptySet(),
3236  "Intervals are overlapping", Range);
3237  Assert(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
3238  Range);
3239  }
3240 }
3241 
3242 void Verifier::checkAtomicMemAccessSize(Type *Ty, const Instruction *I) {
3243  unsigned Size = DL.getTypeSizeInBits(Ty);
3244  Assert(Size >= 8, "atomic memory access' size must be byte-sized", Ty, I);
3245  Assert(!(Size & (Size - 1)),
3246  "atomic memory access' operand must have a power-of-two size", Ty, I);
3247 }
3248 
3249 void Verifier::visitLoadInst(LoadInst &LI) {
3251  Assert(PTy, "Load operand must be a pointer.", &LI);
3252  Type *ElTy = LI.getType();
3254  "huge alignment values are unsupported", &LI);
3255  Assert(ElTy->isSized(), "loading unsized types is not allowed", &LI);
3256  if (LI.isAtomic()) {
3259  "Load cannot have Release ordering", &LI);
3260  Assert(LI.getAlignment() != 0,
3261  "Atomic load must specify explicit alignment", &LI);
3262  Assert(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(),
3263  "atomic load operand must have integer, pointer, or floating point "
3264  "type!",
3265  ElTy, &LI);
3266  checkAtomicMemAccessSize(ElTy, &LI);
3267  } else {
3269  "Non-atomic load cannot have SynchronizationScope specified", &LI);
3270  }
3271 
3272  visitInstruction(LI);
3273 }
3274 
3275 void Verifier::visitStoreInst(StoreInst &SI) {
3277  Assert(PTy, "Store operand must be a pointer.", &SI);
3278  Type *ElTy = PTy->getElementType();
3279  Assert(ElTy == SI.getOperand(0)->getType(),
3280  "Stored value type does not match pointer operand type!", &SI, ElTy);
3282  "huge alignment values are unsupported", &SI);
3283  Assert(ElTy->isSized(), "storing unsized types is not allowed", &SI);
3284  if (SI.isAtomic()) {
3287  "Store cannot have Acquire ordering", &SI);
3288  Assert(SI.getAlignment() != 0,
3289  "Atomic store must specify explicit alignment", &SI);
3290  Assert(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(),
3291  "atomic store operand must have integer, pointer, or floating point "
3292  "type!",
3293  ElTy, &SI);
3294  checkAtomicMemAccessSize(ElTy, &SI);
3295  } else {
3297  "Non-atomic store cannot have SynchronizationScope specified", &SI);
3298  }
3299  visitInstruction(SI);
3300 }
3301 
3302 /// Check that SwiftErrorVal is used as a swifterror argument in CS.
3303 void Verifier::verifySwiftErrorCallSite(CallSite CS,
3304  const Value *SwiftErrorVal) {
3305  unsigned Idx = 0;
3306  for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
3307  I != E; ++I, ++Idx) {
3308  if (*I == SwiftErrorVal) {
3309  Assert(CS.paramHasAttr(Idx, Attribute::SwiftError),
3310  "swifterror value when used in a callsite should be marked "
3311  "with swifterror attribute",
3312  SwiftErrorVal, CS);
3313  }
3314  }
3315 }
3316 
3317 void Verifier::verifySwiftErrorValue(const Value *SwiftErrorVal) {
3318  // Check that swifterror value is only used by loads, stores, or as
3319  // a swifterror argument.
3320  for (const User *U : SwiftErrorVal->users()) {
3321  Assert(isa<LoadInst>(U) || isa<StoreInst>(U) || isa<CallInst>(U) ||
3322  isa<InvokeInst>(U),
3323  "swifterror value can only be loaded and stored from, or "
3324  "as a swifterror argument!",
3325  SwiftErrorVal, U);
3326  // If it is used by a store, check it is the second operand.
3327  if (auto StoreI = dyn_cast<StoreInst>(U))
3328  Assert(StoreI->getOperand(1) == SwiftErrorVal,
3329  "swifterror value should be the second operand when used "
3330  "by stores", SwiftErrorVal, U);
3331  if (auto CallI = dyn_cast<CallInst>(U))
3332  verifySwiftErrorCallSite(const_cast<CallInst*>(CallI), SwiftErrorVal);
3333  if (auto II = dyn_cast<InvokeInst>(U))
3334  verifySwiftErrorCallSite(const_cast<InvokeInst*>(II), SwiftErrorVal);
3335  }
3336 }
3337 
3338 void Verifier::visitAllocaInst(AllocaInst &AI) {
3339  SmallPtrSet<Type*, 4> Visited;
3340  PointerType *PTy = AI.getType();
3341  // TODO: Relax this restriction?
3343  "Allocation instruction pointer not in the stack address space!",
3344  &AI);
3345  Assert(AI.getAllocatedType()->isSized(&Visited),
3346  "Cannot allocate unsized type", &AI);
3348  "Alloca array size must have integer type", &AI);
3350  "huge alignment values are unsupported", &AI);
3351 
3352  if (AI.isSwiftError()) {
3353  verifySwiftErrorValue(&AI);
3354  }
3355 
3356  visitInstruction(AI);
3357 }
3358 
3359 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
3360 
3361  // FIXME: more conditions???
3363  "cmpxchg instructions must be atomic.", &CXI);
3365  "cmpxchg instructions must be atomic.", &CXI);
3367  "cmpxchg instructions cannot be unordered.", &CXI);
3369  "cmpxchg instructions cannot be unordered.", &CXI);
3371  "cmpxchg instructions failure argument shall be no stronger than the "
3372  "success argument",
3373  &CXI);
3376  "cmpxchg failure ordering cannot include release semantics", &CXI);
3377 
3378  PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
3379  Assert(PTy, "First cmpxchg operand must be a pointer.", &CXI);
3380  Type *ElTy = PTy->getElementType();
3381  Assert(ElTy->isIntOrPtrTy(),
3382  "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
3383  checkAtomicMemAccessSize(ElTy, &CXI);
3384  Assert(ElTy == CXI.getOperand(1)->getType(),
3385  "Expected value type does not match pointer operand type!", &CXI,
3386  ElTy);
3387  Assert(ElTy == CXI.getOperand(2)->getType(),
3388  "Stored value type does not match pointer operand type!", &CXI, ElTy);
3389  visitInstruction(CXI);
3390 }
3391 
3392 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
3394  "atomicrmw instructions must be atomic.", &RMWI);
3396  "atomicrmw instructions cannot be unordered.", &RMWI);
3397  auto Op = RMWI.getOperation();
3398  PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
3399  Assert(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
3400  Type *ElTy = PTy->getElementType();
3401  Assert(ElTy->isIntegerTy(), "atomicrmw " +
3403  " operand must have integer type!",
3404  &RMWI, ElTy);
3405  checkAtomicMemAccessSize(ElTy, &RMWI);
3406  Assert(ElTy == RMWI.getOperand(1)->getType(),
3407  "Argument value type does not match pointer operand type!", &RMWI,
3408  ElTy);
3410  "Invalid binary operation!", &RMWI);
3411  visitInstruction(RMWI);
3412 }
3413 
3414 void Verifier::visitFenceInst(FenceInst &FI) {
3415  const AtomicOrdering Ordering = FI.getOrdering();
3416  Assert(Ordering == AtomicOrdering::Acquire ||
3417  Ordering == AtomicOrdering::Release ||
3418  Ordering == AtomicOrdering::AcquireRelease ||
3420  "fence instructions may only have acquire, release, acq_rel, or "
3421  "seq_cst ordering.",
3422  &FI);
3423  visitInstruction(FI);
3424 }
3425 
3426 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
3428  EVI.getIndices()) == EVI.getType(),
3429  "Invalid ExtractValueInst operands!", &EVI);
3430 
3431  visitInstruction(EVI);
3432 }
3433 
3434 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
3436  IVI.getIndices()) ==
3437  IVI.getOperand(1)->getType(),
3438  "Invalid InsertValueInst operands!", &IVI);
3439 
3440  visitInstruction(IVI);
3441 }
3442 
3443 static Value *getParentPad(Value *EHPad) {
3444  if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
3445  return FPI->getParentPad();
3446 
3447  return cast<CatchSwitchInst>(EHPad)->getParentPad();
3448 }
3449 
3450 void Verifier::visitEHPadPredecessors(Instruction &I) {
3451  assert(I.isEHPad());
3452 
3453  BasicBlock *BB = I.getParent();
3454  Function *F = BB->getParent();
3455 
3456  Assert(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I);
3457 
3458  if (auto *LPI = dyn_cast<LandingPadInst>(&I)) {
3459  // The landingpad instruction defines its parent as a landing pad block. The
3460  // landing pad block may be branched to only by the unwind edge of an
3461  // invoke.
3462  for (BasicBlock *PredBB : predecessors(BB)) {
3463  const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator());
3464  Assert(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
3465  "Block containing LandingPadInst must be jumped to "
3466  "only by the unwind edge of an invoke.",
3467  LPI);
3468  }
3469  return;
3470  }
3471  if (auto *CPI = dyn_cast<CatchPadInst>(&I)) {
3472  if (!pred_empty(BB))
3473  Assert(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(),
3474  "Block containg CatchPadInst must be jumped to "
3475  "only by its catchswitch.",
3476  CPI);
3477  Assert(BB != CPI->getCatchSwitch()->getUnwindDest(),
3478  "Catchswitch cannot unwind to one of its catchpads",
3479  CPI->getCatchSwitch(), CPI);
3480  return;
3481  }
3482 
3483  // Verify that each pred has a legal terminator with a legal to/from EH
3484  // pad relationship.
3485  Instruction *ToPad = &I;
3486  Value *ToPadParent = getParentPad(ToPad);
3487  for (BasicBlock *PredBB : predecessors(BB)) {
3488  Instruction *TI = PredBB->getTerminator();
3489  Value *FromPad;
3490  if (auto *II = dyn_cast<InvokeInst>(TI)) {
3491  Assert(II->getUnwindDest() == BB && II->getNormalDest() != BB,
3492  "EH pad must be jumped to via an unwind edge", ToPad, II);
3493  if (auto Bundle = II->getOperandBundle(LLVMContext::OB_funclet))
3494  FromPad = Bundle->Inputs[0];
3495  else
3496  FromPad = ConstantTokenNone::get(II->getContext());
3497  } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
3498  FromPad = CRI->getOperand(0);
3499  Assert(FromPad != ToPadParent, "A cleanupret must exit its cleanup", CRI);
3500  } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
3501  FromPad = CSI;
3502  } else {
3503  Assert(false, "EH pad must be jumped to via an unwind edge", ToPad, TI);
3504  }
3505 
3506  // The edge may exit from zero or more nested pads.
3507  SmallSet<Value *, 8> Seen;
3508  for (;; FromPad = getParentPad(FromPad)) {
3509  Assert(FromPad != ToPad,
3510  "EH pad cannot handle exceptions raised within it", FromPad, TI);
3511  if (FromPad == ToPadParent) {
3512  // This is a legal unwind edge.
3513  break;
3514  }
3515  Assert(!isa<ConstantTokenNone>(FromPad),
3516  "A single unwind edge may only enter one EH pad", TI);
3517  Assert(Seen.insert(FromPad).second,
3518  "EH pad jumps through a cycle of pads", FromPad);
3519  }
3520  }
3521 }
3522 
3523 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
3524  // The landingpad instruction is ill-formed if it doesn't have any clauses and
3525  // isn't a cleanup.
3526  Assert(LPI.getNumClauses() > 0 || LPI.isCleanup(),
3527  "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
3528 
3529  visitEHPadPredecessors(LPI);
3530 
3531  if (!LandingPadResultTy)
3532  LandingPadResultTy = LPI.getType();
3533  else
3534  Assert(LandingPadResultTy == LPI.getType(),
3535  "The landingpad instruction should have a consistent result type "
3536  "inside a function.",
3537  &LPI);
3538 
3539  Function *F = LPI.getParent()->getParent();
3540  Assert(F->hasPersonalityFn(),
3541  "LandingPadInst needs to be in a function with a personality.", &LPI);
3542 
3543  // The landingpad instruction must be the first non-PHI instruction in the
3544  // block.
3545  Assert(LPI.getParent()->getLandingPadInst() == &LPI,
3546  "LandingPadInst not the first non-PHI instruction in the block.",
3547  &LPI);
3548 
3549  for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
3550  Constant *Clause = LPI.getClause(i);
3551  if (LPI.isCatch(i)) {
3552  Assert(isa<PointerType>(Clause->getType()),
3553  "Catch operand does not have pointer type!", &LPI);
3554  } else {
3555  Assert(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
3556  Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
3557  "Filter operand is not an array of constants!", &LPI);
3558  }
3559  }
3560 
3561  visitInstruction(LPI);
3562 }
3563 
3564 void Verifier::visitResumeInst(ResumeInst &RI) {
3566  "ResumeInst needs to be in a function with a personality.", &RI);
3567 
3568  if (!LandingPadResultTy)
3569  LandingPadResultTy = RI.getValue()->getType();
3570  else
3571  Assert(LandingPadResultTy == RI.getValue()->getType(),
3572  "The resume instruction should have a consistent result type "
3573  "inside a function.",
3574  &RI);
3575 
3576  visitTerminator(RI);
3577 }
3578 
3579 void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
3580  BasicBlock *BB = CPI.getParent();
3581 
3582  Function *F = BB->getParent();
3583  Assert(F->hasPersonalityFn(),
3584  "CatchPadInst needs to be in a function with a personality.", &CPI);
3585 
3586  Assert(isa<CatchSwitchInst>(CPI.getParentPad()),
3587  "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
3588  CPI.getParentPad());
3589 
3590  // The catchpad instruction must be the first non-PHI instruction in the
3591  // block.
3592  Assert(BB->getFirstNonPHI() == &CPI,
3593  "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
3594 
3595  visitEHPadPredecessors(CPI);
3596  visitFuncletPadInst(CPI);
3597 }
3598 
3599 void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
3600  Assert(isa<CatchPadInst>(CatchReturn.getOperand(0)),
3601  "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
3602  CatchReturn.getOperand(0));
3603 
3604  visitTerminator(CatchReturn);
3605 }
3606 
3607 void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
3608  BasicBlock *BB = CPI.getParent();
3609 
3610  Function *F = BB->getParent();
3611  Assert(F->hasPersonalityFn(),
3612  "CleanupPadInst needs to be in a function with a personality.", &CPI);
3613 
3614  // The cleanuppad instruction must be the first non-PHI instruction in the
3615  // block.
3616  Assert(BB->getFirstNonPHI() == &CPI,
3617  "CleanupPadInst not the first non-PHI instruction in the block.",
3618  &CPI);
3619 
3620  auto *ParentPad = CPI.getParentPad();
3621  Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
3622  "CleanupPadInst has an invalid parent.", &CPI);
3623 
3624  visitEHPadPredecessors(CPI);
3625  visitFuncletPadInst(CPI);
3626 }
3627 
3628 void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
3629  User *FirstUser = nullptr;
3630  Value *FirstUnwindPad = nullptr;
3631  SmallVector<FuncletPadInst *, 8> Worklist({&FPI});
3633 
3634  while (!Worklist.empty()) {
3635  FuncletPadInst *CurrentPad = Worklist.pop_back_val();
3636  Assert(Seen.insert(CurrentPad).second,
3637  "FuncletPadInst must not be nested within itself", CurrentPad);
3638  Value *UnresolvedAncestorPad = nullptr;
3639  for (User *U : CurrentPad->users()) {
3640  BasicBlock *UnwindDest;
3641  if (auto *CRI = dyn_cast<CleanupReturnInst>(U)) {
3642  UnwindDest = CRI->getUnwindDest();
3643  } else if (auto *CSI = dyn_cast<CatchSwitchInst>(U)) {
3644  // We allow catchswitch unwind to caller to nest
3645  // within an outer pad that unwinds somewhere else,
3646  // because catchswitch doesn't have a nounwind variant.
3647  // See e.g. SimplifyCFGOpt::SimplifyUnreachable.
3648  if (CSI->unwindsToCaller())
3649  continue;
3650  UnwindDest = CSI->getUnwindDest();
3651  } else if (auto *II = dyn_cast<InvokeInst>(U)) {
3652  UnwindDest = II->getUnwindDest();
3653  } else if (isa<CallInst>(U)) {
3654  // Calls which don't unwind may be found inside funclet
3655  // pads that unwind somewhere else. We don't *require*
3656  // such calls to be annotated nounwind.
3657  continue;
3658  } else if (auto *CPI = dyn_cast<CleanupPadInst>(U)) {
3659  // The unwind dest for a cleanup can only be found by
3660  // recursive search. Add it to the worklist, and we'll
3661  // search for its first use that determines where it unwinds.
3662  Worklist.push_back(CPI);
3663  continue;
3664  } else {
3665  Assert(isa<CatchReturnInst>(U), "Bogus funclet pad use", U);
3666  continue;
3667  }
3668 
3669  Value *UnwindPad;
3670  bool ExitsFPI;
3671  if (UnwindDest) {
3672  UnwindPad = UnwindDest->getFirstNonPHI();
3673  if (!cast<Instruction>(UnwindPad)->isEHPad())
3674  continue;
3675  Value *UnwindParent = getParentPad(UnwindPad);
3676  // Ignore unwind edges that don't exit CurrentPad.
3677  if (UnwindParent == CurrentPad)
3678  continue;
3679  // Determine whether the original funclet pad is exited,
3680  // and if we are scanning nested pads determine how many
3681  // of them are exited so we can stop searching their
3682  // children.
3683  Value *ExitedPad = CurrentPad;
3684  ExitsFPI = false;
3685  do {
3686  if (ExitedPad == &FPI) {
3687  ExitsFPI = true;
3688  // Now we can resolve any ancestors of CurrentPad up to
3689  // FPI, but not including FPI since we need to make sure
3690  // to check all direct users of FPI for consistency.
3691  UnresolvedAncestorPad = &FPI;
3692  break;
3693  }
3694  Value *ExitedParent = getParentPad(ExitedPad);
3695  if (ExitedParent == UnwindParent) {
3696  // ExitedPad is the ancestor-most pad which this unwind
3697  // edge exits, so we can resolve up to it, meaning that
3698  // ExitedParent is the first ancestor still unresolved.
3699  UnresolvedAncestorPad = ExitedParent;
3700  break;
3701  }
3702  ExitedPad = ExitedParent;
3703  } while (!isa<ConstantTokenNone>(ExitedPad));
3704  } else {
3705  // Unwinding to caller exits all pads.
3706  UnwindPad = ConstantTokenNone::get(FPI.getContext());
3707  ExitsFPI = true;
3708  UnresolvedAncestorPad = &FPI;
3709  }
3710 
3711  if (ExitsFPI) {
3712  // This unwind edge exits FPI. Make sure it agrees with other
3713  // such edges.
3714  if (FirstUser) {
3715  Assert(UnwindPad == FirstUnwindPad, "Unwind edges out of a funclet "
3716  "pad must have the same unwind "
3717  "dest",
3718  &FPI, U, FirstUser);
3719  } else {
3720  FirstUser = U;
3721  FirstUnwindPad = UnwindPad;
3722  // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds
3723  if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) &&
3724  getParentPad(UnwindPad) == getParentPad(&FPI))
3725  SiblingFuncletInfo[&FPI] = cast<Instruction>(U);
3726  }
3727  }
3728  // Make sure we visit all uses of FPI, but for nested pads stop as
3729  // soon as we know where they unwind to.
3730  if (CurrentPad != &FPI)
3731  break;
3732  }
3733  if (UnresolvedAncestorPad) {
3734  if (CurrentPad == UnresolvedAncestorPad) {
3735  // When CurrentPad is FPI itself, we don't mark it as resolved even if
3736  // we've found an unwind edge that exits it, because we need to verify
3737  // all direct uses of FPI.
3738  assert(CurrentPad == &FPI);
3739  continue;
3740  }
3741  // Pop off the worklist any nested pads that we've found an unwind
3742  // destination for. The pads on the worklist are the uncles,
3743  // great-uncles, etc. of CurrentPad. We've found an unwind destination
3744  // for all ancestors of CurrentPad up to but not including
3745  // UnresolvedAncestorPad.
3746  Value *ResolvedPad = CurrentPad;
3747  while (!Worklist.empty()) {
3748  Value *UnclePad = Worklist.back();
3749  Value *AncestorPad = getParentPad(UnclePad);
3750  // Walk ResolvedPad up the ancestor list until we either find the
3751  // uncle's parent or the last resolved ancestor.
3752  while (ResolvedPad != AncestorPad) {
3753  Value *ResolvedParent = getParentPad(ResolvedPad);
3754  if (ResolvedParent == UnresolvedAncestorPad) {
3755  break;
3756  }
3757  ResolvedPad = ResolvedParent;
3758  }
3759  // If the resolved ancestor search didn't find the uncle's parent,
3760  // then the uncle is not yet resolved.
3761  if (ResolvedPad != AncestorPad)
3762  break;
3763  // This uncle is resolved, so pop it from the worklist.
3764  Worklist.pop_back();
3765  }
3766  }
3767  }
3768 
3769  if (FirstUnwindPad) {
3770  if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.getParentPad())) {
3771  BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
3772  Value *SwitchUnwindPad;
3773  if (SwitchUnwindDest)
3774  SwitchUnwindPad = SwitchUnwindDest->getFirstNonPHI();
3775  else
3776  SwitchUnwindPad = ConstantTokenNone::get(FPI.getContext());
3777  Assert(SwitchUnwindPad == FirstUnwindPad,
3778  "Unwind edges out of a catch must have the same unwind dest as "
3779  "the parent catchswitch",
3780  &FPI, FirstUser, CatchSwitch);
3781  }
3782  }
3783 
3784  visitInstruction(FPI);
3785 }
3786 
3787 void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
3788  BasicBlock *BB = CatchSwitch.getParent();
3789 
3790  Function *F = BB->getParent();
3791  Assert(F->hasPersonalityFn(),
3792  "CatchSwitchInst needs to be in a function with a personality.",
3793  &CatchSwitch);
3794 
3795  // The catchswitch instruction must be the first non-PHI instruction in the
3796  // block.
3797  Assert(BB->getFirstNonPHI() == &CatchSwitch,
3798  "CatchSwitchInst not the first non-PHI instruction in the block.",
3799  &CatchSwitch);
3800 
3801  auto *ParentPad = CatchSwitch.getParentPad();
3802  Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
3803  "CatchSwitchInst has an invalid parent.", ParentPad);
3804 
3805  if (BasicBlock *UnwindDest = CatchSwitch.getUnwindDest()) {
3806  Instruction *I = UnwindDest->getFirstNonPHI();
3807  Assert(I->isEHPad() && !isa<LandingPadInst>(I),
3808  "CatchSwitchInst must unwind to an EH block which is not a "
3809  "landingpad.",
3810  &CatchSwitch);
3811 
3812  // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds
3813  if (getParentPad(I) == ParentPad)
3814  SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
3815  }
3816 
3817  Assert(CatchSwitch.getNumHandlers() != 0,
3818  "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
3819 
3820  for (BasicBlock *Handler : CatchSwitch.handlers()) {
3821  Assert(isa<CatchPadInst>(Handler->getFirstNonPHI()),
3822  "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
3823  }
3824 
3825  visitEHPadPredecessors(CatchSwitch);
3826  visitTerminator(CatchSwitch);
3827 }
3828 
3829 void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
3830  Assert(isa<CleanupPadInst>(CRI.getOperand(0)),
3831  "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
3832  CRI.getOperand(0));
3833 
3834  if (BasicBlock *UnwindDest = CRI.getUnwindDest()) {
3835  Instruction *I = UnwindDest->getFirstNonPHI();
3836  Assert(I->isEHPad() && !isa<LandingPadInst>(I),
3837  "CleanupReturnInst must unwind to an EH block which is not a "
3838  "landingpad.",
3839  &CRI);
3840  }
3841 
3842  visitTerminator(CRI);
3843 }
3844 
3845 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
3846  Instruction *Op = cast<Instruction>(I.getOperand(i));
3847  // If the we have an invalid invoke, don't try to compute the dominance.
3848  // We already reject it in the invoke specific checks and the dominance
3849  // computation doesn't handle multiple edges.
3850  if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
3851  if (II->getNormalDest() == II->getUnwindDest())
3852  return;
3853  }
3854 
3855  // Quick check whether the def has already been encountered in the same block.
3856  // PHI nodes are not checked to prevent accepting preceeding PHIs, because PHI
3857  // uses are defined to happen on the incoming edge, not at the instruction.
3858  //
3859  // FIXME: If this operand is a MetadataAsValue (wrapping a LocalAsMetadata)
3860  // wrapping an SSA value, assert that we've already encountered it. See
3861  // related FIXME in Mapper::mapLocalAsMetadata in ValueMapper.cpp.
3862  if (!isa<PHINode>(I) && InstsInThisBlock.count(Op))
3863  return;
3864 
3865  const Use &U = I.getOperandUse(i);
3866  Assert(DT.dominates(Op, U),
3867  "Instruction does not dominate all uses!", Op, &I);
3868 }
3869 
3870 void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) {
3871  Assert(I.getType()->isPointerTy(), "dereferenceable, dereferenceable_or_null "
3872  "apply only to pointer types", &I);
3873  Assert(isa<LoadInst>(I),
3874  "dereferenceable, dereferenceable_or_null apply only to load"
3875  " instructions, use attributes for calls or invokes", &I);
3876  Assert(MD->getNumOperands() == 1, "dereferenceable, dereferenceable_or_null "
3877  "take one operand!", &I);
3878  ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
3879  Assert(CI && CI->getType()->isIntegerTy(64), "dereferenceable, "
3880  "dereferenceable_or_null metadata value must be an i64!", &I);
3881 }
3882 
3883 /// verifyInstruction - Verify that an instruction is well formed.
3884 ///
3885 void Verifier::visitInstruction(Instruction &I) {
3886  BasicBlock *BB = I.getParent();
3887  Assert(BB, "Instruction not embedded in basic block!", &I);
3888 
3889  if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
3890  for (User *U : I.users()) {
3891  Assert(U != (User *)&I || !DT.isReachableFromEntry(BB),
3892  "Only PHI nodes may reference their own value!", &I);
3893  }
3894  }
3895 
3896  // Check that void typed values don't have names
3897  Assert(!I.getType()->isVoidTy() || !I.hasName(),
3898  "Instruction has a name, but provides a void value!", &I);
3899 
3900  // Check that the return value of the instruction is either void or a legal
3901  // value type.
3902  Assert(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
3903  "Instruction returns a non-scalar type!", &I);
3904 
3905  // Check that the instruction doesn't produce metadata. Calls are already
3906  // checked against the callee type.
3907  Assert(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
3908  "Invalid use of metadata!", &I);
3909 
3910  // Check that all uses of the instruction, if they are instructions
3911  // themselves, actually have parent basic blocks. If the use is not an
3912  // instruction, it is an error!
3913  for (Use &U : I.uses()) {
3914  if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
3915  Assert(Used->getParent() != nullptr,
3916  "Instruction referencing"
3917  " instruction not embedded in a basic block!",
3918  &I, Used);
3919  else {
3920  CheckFailed("Use of instruction is not an instruction!", U);
3921  return;
3922  }
3923  }
3924 
3925  for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
3926  Assert(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
3927 
3928  // Check to make sure that only first-class-values are operands to
3929  // instructions.
3930  if (!I.getOperand(i)->getType()->isFirstClassType()) {
3931  Assert(false, "Instruction operands must be first-class values!", &I);
3932  }
3933 
3934  if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
3935  // Check to make sure that the "address of" an intrinsic function is never
3936  // taken.
3937  Assert(
3938  !F->isIntrinsic() ||
3939  i == (isa<CallInst>(I) ? e - 1 : isa<InvokeInst>(I) ? e - 3 : 0),
3940  "Cannot take the address of an intrinsic!", &I);
3941  Assert(
3942  !F->isIntrinsic() || isa<CallInst>(I) ||
3943  F->getIntrinsicID() == Intrinsic::donothing ||
3944  F->getIntrinsicID() == Intrinsic::coro_resume ||
3945  F->getIntrinsicID() == Intrinsic::coro_destroy ||
3946  F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void ||
3947  F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 ||
3948  F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint,
3949  "Cannot invoke an intrinsic other than donothing, patchpoint, "
3950  "statepoint, coro_resume or coro_destroy",
3951  &I);
3952  Assert(F->getParent() == &M, "Referencing function in another module!",
3953  &I, &M, F, F->getParent());
3954  } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
3955  Assert(OpBB->getParent() == BB->getParent(),
3956  "Referring to a basic block in another function!", &I);
3957  } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
3958  Assert(OpArg->getParent() == BB->getParent(),
3959  "Referring to an argument in another function!", &I);
3960  } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
3961  Assert(GV->getParent() == &M, "Referencing global in another module!", &I,
3962  &M, GV, GV->getParent());
3963  } else if (isa<Instruction>(I.getOperand(i))) {
3964  verifyDominatesUse(I, i);
3965  } else if (isa<InlineAsm>(I.getOperand(i))) {
3966  Assert((i + 1 == e && isa<CallInst>(I)) ||
3967  (i + 3 == e && isa<InvokeInst>(I)),
3968  "Cannot take the address of an inline asm!", &I);
3969  } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
3970  if (CE->getType()->isPtrOrPtrVectorTy() ||
3972  // If we have a ConstantExpr pointer, we need to see if it came from an
3973  // illegal bitcast. If the datalayout string specifies non-integral
3974  // address spaces then we also need to check for illegal ptrtoint and
3975  // inttoptr expressions.
3976  visitConstantExprsRecursively(CE);
3977  }
3978  }
3979  }
3980 
3981  if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
3983  "fpmath requires a floating point result!", &I);
3984  Assert(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
3985  if (ConstantFP *CFP0 =
3986  mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) {
3987  const APFloat &Accuracy = CFP0->getValueAPF();
3988  Assert(&Accuracy.getSemantics() == &APFloat::IEEEsingle(),
3989  "fpmath accuracy must have float type", &I);
3990  Assert(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
3991  "fpmath accuracy not a positive number!", &I);
3992  } else {
3993  Assert(false, "invalid fpmath accuracy!", &I);
3994  }
3995  }
3996 
3997  if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
3998  Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),
3999  "Ranges are only for loads, calls and invokes!", &I);
4000  visitRangeMetadata(I, Range, I.getType());
4001  }
4002 
4004  Assert(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
4005  &I);
4006  Assert(isa<LoadInst>(I),
4007  "nonnull applies only to load instructions, use attributes"
4008  " for calls or invokes",
4009  &I);
4010  }
4011 
4013  visitDereferenceableMetadata(I, MD);
4014 
4016  visitDereferenceableMetadata(I, MD);
4017 
4018  if (MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa))
4019  TBAAVerifyHelper.visitTBAAMetadata(I, TBAA);
4020 
4021  if (MDNode *AlignMD = I.getMetadata(LLVMContext::MD_align)) {
4022  Assert(I.getType()->isPointerTy(), "align applies only to pointer types",
4023  &I);
4024  Assert(isa<LoadInst>(I), "align applies only to load instructions, "
4025  "use attributes for calls or invokes", &I);
4026  Assert(AlignMD->getNumOperands() == 1, "align takes one operand!", &I);
4027  ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0));
4028  Assert(CI && CI->getType()->isIntegerTy(64),
4029  "align metadata value must be an i64!", &I);
4030  uint64_t Align = CI->getZExtValue();
4031  Assert(isPowerOf2_64(Align),
4032  "align metadata value must be a power of 2!", &I);
4034  "alignment is larger that implementation defined limit", &I);
4035  }
4036 
4037  if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
4038  AssertDI(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N);
4039  visitMDNode(*N);
4040  }
4041 
4042  if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&I))
4043  verifyFragmentExpression(*DII);
4044 
4045  InstsInThisBlock.insert(&I);
4046 }
4047 
4048 /// Allow intrinsics to be verified in different ways.
4049 void Verifier::visitIntrinsicCallSite(Intrinsic::ID ID, CallSite CS) {
4050  Function *IF = CS.getCalledFunction();
4051  Assert(IF->isDeclaration(), "Intrinsic functions should never be defined!",
4052  IF);
4053 
4054  // Verify that the intrinsic prototype lines up with what the .td files
4055  // describe.
4056  FunctionType *IFTy = IF->getFunctionType();
4057  bool IsVarArg = IFTy->isVarArg();
4058 
4060  getIntrinsicInfoTableEntries(ID, Table);
4062 
4063  SmallVector<Type *, 4> ArgTys;
4064  Assert(!Intrinsic::matchIntrinsicType(IFTy->getReturnType(),
4065  TableRef, ArgTys),
4066  "Intrinsic has incorrect return type!", IF);
4067  for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
4068  Assert(!Intrinsic::matchIntrinsicType(IFTy->getParamType(i),
4069  TableRef, ArgTys),
4070  "Intrinsic has incorrect argument type!", IF);
4071 
4072  // Verify if the intrinsic call matches the vararg property.
4073  if (IsVarArg)
4074  Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef),
4075  "Intrinsic was not defined with variable arguments!", IF);
4076  else
4077  Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef),
4078  "Callsite was not defined with variable arguments!", IF);
4079 
4080  // All descriptors should be absorbed by now.
4081  Assert(TableRef.empty(), "Intrinsic has too few arguments!", IF);
4082 
4083  // Now that we have the intrinsic ID and the actual argument types (and we
4084  // know they are legal for the intrinsic!) get the intrinsic name through the
4085  // usual means. This allows us to verify the mangling of argument types into
4086  // the name.
4087  const std::string ExpectedName = Intrinsic::getName(ID, ArgTys);
4088  Assert(ExpectedName == IF->getName(),
4089  "Intrinsic name not mangled correctly for type arguments! "
4090  "Should be: " +
4091  ExpectedName,
4092  IF);
4093 
4094  // If the intrinsic takes MDNode arguments, verify that they are either global
4095  // or are local to *this* function.
4096  for (Value *V : CS.args())
4097  if (auto *MD = dyn_cast<MetadataAsValue>(V))
4098  visitMetadataAsValue(*MD, CS.getCaller());
4099 
4100  switch (ID) {
4101  default:
4102  break;
4103  case Intrinsic::coro_id: {
4104  auto *InfoArg = CS.getArgOperand(3)->stripPointerCasts();
4105  if (isa<ConstantPointerNull>(InfoArg))
4106  break;
4107  auto *GV = dyn_cast<GlobalVariable>(InfoArg);
4108  Assert(GV && GV->isConstant() && GV->hasDefinitiveInitializer(),
4109  "info argument of llvm.coro.begin must refer to an initialized "
4110  "constant");
4111  Constant *Init = GV->getInitializer();
4112  Assert(isa<ConstantStruct>(Init) || isa<ConstantArray>(Init),
4113  "info argument of llvm.coro.begin must refer to either a struct or "
4114  "an array");
4115  break;
4116  }
4117  case Intrinsic::ctlz: // llvm.ctlz
4118  case Intrinsic::cttz: // llvm.cttz
4119  Assert(isa<ConstantInt>(CS.getArgOperand(1)),
4120  "is_zero_undef argument of bit counting intrinsics must be a "
4121  "constant int",
4122  CS);
4123  break;
4124  case Intrinsic::experimental_constrained_fadd:
4125  case Intrinsic::experimental_constrained_fsub:
4126  case Intrinsic::experimental_constrained_fmul:
4127  case Intrinsic::experimental_constrained_fdiv:
4128  case Intrinsic::experimental_constrained_frem:
4129  case Intrinsic::experimental_constrained_fma:
4130  case Intrinsic::experimental_constrained_sqrt:
4131  case Intrinsic::experimental_constrained_pow:
4132  case Intrinsic::experimental_constrained_powi:
4133  case Intrinsic::experimental_constrained_sin:
4134  case Intrinsic::experimental_constrained_cos:
4135  case Intrinsic::experimental_constrained_exp:
4136  case Intrinsic::experimental_constrained_exp2:
4137  case Intrinsic::experimental_constrained_log:
4138  case Intrinsic::experimental_constrained_log10:
4139  case Intrinsic::experimental_constrained_log2:
4140  case Intrinsic::experimental_constrained_rint:
4141  case Intrinsic::experimental_constrained_nearbyint:
4142  case Intrinsic::experimental_constrained_maxnum:
4143  case Intrinsic::experimental_constrained_minnum:
4144  case Intrinsic::experimental_constrained_ceil:
4145  case Intrinsic::experimental_constrained_floor:
4146  case Intrinsic::experimental_constrained_round:
4147  case Intrinsic::experimental_constrained_trunc:
4148  visitConstrainedFPIntrinsic(
4149  cast<ConstrainedFPIntrinsic>(*CS.getInstruction()));
4150  break;
4151  case Intrinsic::dbg_declare: // llvm.dbg.declare
4152  Assert(isa<MetadataAsValue>(CS.getArgOperand(0)),
4153  "invalid llvm.dbg.declare intrinsic call 1", CS);
4154  visitDbgIntrinsic("declare", cast<DbgVariableIntrinsic>(*CS.getInstruction()));
4155  break;
4156  case Intrinsic::dbg_addr: // llvm.dbg.addr
4157  visitDbgIntrinsic("addr", cast<DbgVariableIntrinsic>(*CS.getInstruction()));
4158  break;
4159  case Intrinsic::dbg_value: // llvm.dbg.value
4160  visitDbgIntrinsic("value", cast<DbgVariableIntrinsic>(*CS.getInstruction()));
4161  break;
4162  case Intrinsic::dbg_label: // llvm.dbg.label
4163  visitDbgLabelIntrinsic("label", cast<DbgLabelInst>(*CS.getInstruction()));
4164  break;
4165  case Intrinsic::memcpy:
4166  case Intrinsic::memmove:
4167  case Intrinsic::memset: {
4168  const auto *MI = cast<MemIntrinsic>(CS.getInstruction());
4169  auto IsValidAlignment = [&](unsigned Alignment) -> bool {
4170  return Alignment == 0 || isPowerOf2_32(Alignment);
4171  };
4172  Assert(IsValidAlignment(MI->getDestAlignment()),
4173  "alignment of arg 0 of memory intrinsic must be 0 or a power of 2",
4174  CS);
4175  if (const auto *MTI = dyn_cast<MemTransferInst>(MI)) {
4176  Assert(IsValidAlignment(MTI->getSourceAlignment()),
4177  "alignment of arg 1 of memory intrinsic must be 0 or a power of 2",
4178  CS);
4179  }
4180  Assert(isa<ConstantInt>(CS.getArgOperand(3)),
4181  "isvolatile argument of memory intrinsics must be a constant int",
4182  CS);
4183  break;
4184  }
4185  case Intrinsic::memcpy_element_unordered_atomic:
4186  case Intrinsic::memmove_element_unordered_atomic:
4187  case Intrinsic::memset_element_unordered_atomic: {
4188  const auto *AMI = cast<AtomicMemIntrinsic>(CS.getInstruction());
4189 
4190  ConstantInt *ElementSizeCI =
4191  dyn_cast<ConstantInt>(AMI->getRawElementSizeInBytes());
4192  Assert(ElementSizeCI,
4193  "element size of the element-wise unordered atomic memory "
4194  "intrinsic must be a constant int",
4195  CS);
4196  const APInt &ElementSizeVal = ElementSizeCI->getValue();
4197  Assert(ElementSizeVal.isPowerOf2(),
4198  "element size of the element-wise atomic memory intrinsic "
4199  "must be a power of 2",
4200  CS);
4201 
4202  if (auto *LengthCI = dyn_cast<ConstantInt>(AMI->getLength())) {
4203  uint64_t Length = LengthCI->getZExtValue();
4204  uint64_t ElementSize = AMI->getElementSizeInBytes();
4205  Assert((Length % ElementSize) == 0,
4206  "constant length must be a multiple of the element size in the "
4207  "element-wise atomic memory intrinsic",
4208  CS);
4209  }
4210 
4211  auto IsValidAlignment = [&](uint64_t Alignment) {
4212  return isPowerOf2_64(Alignment) && ElementSizeVal.ule(Alignment);
4213  };
4214  uint64_t DstAlignment = AMI->getDestAlignment();
4215  Assert(IsValidAlignment(DstAlignment),
4216  "incorrect alignment of the destination argument", CS);
4217  if (const auto *AMT = dyn_cast<AtomicMemTransferInst>(AMI)) {
4218  uint64_t SrcAlignment = AMT->getSourceAlignment();
4219  Assert(IsValidAlignment(SrcAlignment),
4220  "incorrect alignment of the source argument", CS);
4221  }
4222  break;
4223  }
4224  case Intrinsic::gcroot:
4225  case Intrinsic::gcwrite:
4226  case Intrinsic::gcread:
4227  if (ID == Intrinsic::gcroot) {
4228  AllocaInst *AI =
4230  Assert(AI, "llvm.gcroot parameter #1 must be an alloca.", CS);
4231  Assert(isa<Constant>(CS.getArgOperand(1)),
4232  "llvm.gcroot parameter #2 must be a constant.", CS);
4233  if (!AI->getAllocatedType()->isPointerTy()) {
4234  Assert(!isa<ConstantPointerNull>(CS.getArgOperand(1)),
4235  "llvm.gcroot parameter #1 must either be a pointer alloca, "
4236  "or argument #2 must be a non-null constant.",
4237  CS);
4238  }
4239  }
4240 
4241  Assert(CS.getParent()->getParent()->hasGC(),
4242  "Enclosing function does not use GC.", CS);
4243  break;
4244  case Intrinsic::init_trampoline:
4245  Assert(isa<Function>(CS.getArgOperand(1)->stripPointerCasts()),
4246  "llvm.init_trampoline parameter #2 must resolve to a function.",
4247  CS);
4248  break;
4249  case Intrinsic::prefetch:
4250  Assert(isa<ConstantInt>(CS.getArgOperand(1)) &&
4251  isa<ConstantInt>(CS.getArgOperand(2)) &&
4252  cast<ConstantInt>(CS.getArgOperand(1))->getZExtValue() < 2 &&
4253  cast<ConstantInt>(CS.getArgOperand(2))->getZExtValue() < 4,
4254  "invalid arguments to llvm.prefetch", CS);
4255  break;
4256  case Intrinsic::stackprotector:
4257  Assert(isa<AllocaInst>(CS.getArgOperand(1)->stripPointerCasts()),
4258  "llvm.stackprotector parameter #2 must resolve to an alloca.", CS);
4259  break;
4260  case Intrinsic::lifetime_start:
4261  case Intrinsic::lifetime_end:
4262  case Intrinsic::invariant_start:
4263  Assert(isa<ConstantInt>(CS.getArgOperand(0)),
4264  "size argument of memory use markers must be a constant integer",
4265  CS);
4266  break;
4267  case Intrinsic::invariant_end:
4268  Assert(isa<ConstantInt>(CS.getArgOperand(1)),
4269  "llvm.invariant.end parameter #2 must be a constant integer", CS);
4270  break;
4271 
4272  case Intrinsic::localescape: {
4273  BasicBlock *BB = CS.getParent();
4274  Assert(BB == &BB->getParent()->front(),
4275  "llvm.localescape used outside of entry block", CS);
4276  Assert(!SawFrameEscape,
4277  "multiple calls to llvm.localescape in one function", CS);
4278  for (Value *Arg : CS.args()) {
4279  if (isa<ConstantPointerNull>(Arg))
4280  continue; // Null values are allowed as placeholders.
4281  auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
4282  Assert(AI && AI->isStaticAlloca(),
4283  "llvm.localescape only accepts static allocas", CS);
4284  }
4285  FrameEscapeInfo[BB->getParent()].first = CS.getNumArgOperands();
4286  SawFrameEscape = true;
4287  break;
4288  }
4289  case Intrinsic::localrecover: {
4290  Value *FnArg = CS.getArgOperand(0)->stripPointerCasts();
4291  Function *Fn = dyn_cast<Function>(FnArg);
4292  Assert(Fn && !Fn->isDeclaration(),
4293  "llvm.localrecover first "
4294  "argument must be function defined in this module",
4295  CS);
4296  auto *IdxArg = dyn_cast<ConstantInt>(CS.getArgOperand(2));
4297  Assert(IdxArg, "idx argument of llvm.localrecover must be a constant int",
4298  CS);
4299  auto &Entry = FrameEscapeInfo[Fn];
4300  Entry.second = unsigned(
4301  std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
4302  break;
4303  }
4304 
4305  case Intrinsic::experimental_gc_statepoint:
4306  Assert(!CS.isInlineAsm(),
4307  "gc.statepoint support for inline assembly unimplemented", CS);
4308  Assert(CS.getParent()->getParent()->hasGC(),
4309  "Enclosing function does not use GC.", CS);
4310 
4311  verifyStatepoint(CS);
4312  break;
4313  case Intrinsic::experimental_gc_result: {
4314  Assert(CS.getParent()->getParent()->hasGC(),
4315  "Enclosing function does not use GC.", CS);
4316  // Are we tied to a statepoint properly?
4317  CallSite StatepointCS(CS.getArgOperand(0));
4318  const Function *StatepointFn =
4319  StatepointCS.getInstruction() ? StatepointCS.getCalledFunction() : nullptr;
4320  Assert(StatepointFn && StatepointFn->isDeclaration() &&
4321  StatepointFn->getIntrinsicID() ==
4322  Intrinsic::experimental_gc_statepoint,
4323  "gc.result operand #1 must be from a statepoint", CS,
4324  CS.getArgOperand(0));
4325 
4326  // Assert that result type matches wrapped callee.
4327  const Value *Target = StatepointCS.getArgument(2);
4328  auto *PT = cast<PointerType>(Target->getType());
4329  auto *TargetFuncType = cast<FunctionType>(PT->getElementType());
4330  Assert(CS.getType() == TargetFuncType->getReturnType(),
4331  "gc.result result type does not match wrapped callee", CS);
4332  break;
4333  }
4334  case Intrinsic::experimental_gc_relocate: {
4335  Assert(CS.getNumArgOperands() == 3, "wrong number of arguments", CS);
4336 
4337  Assert(isa<PointerType>(CS.getType()->getScalarType()),
4338  "gc.relocate must return a pointer or a vector of pointers", CS);
4339 
4340  // Check that this relocate is correctly tied to the statepoint
4341 
4342  // This is case for relocate on the unwinding path of an invoke statepoint
4343  if (LandingPadInst *LandingPad =
4344  dyn_cast<LandingPadInst>(CS.getArgOperand(0))) {
4345 
4346  const BasicBlock *InvokeBB =
4347  LandingPad->getParent()->getUniquePredecessor();
4348 
4349  // Landingpad relocates should have only one predecessor with invoke
4350  // statepoint terminator
4351  Assert(InvokeBB, "safepoints should have unique landingpads",
4352  LandingPad->getParent());
4353  Assert(InvokeBB->getTerminator(), "safepoint block should be well formed",
4354  InvokeBB);
4355  Assert(isStatepoint(InvokeBB->getTerminator()),
4356  "gc relocate should be linked to a statepoint", InvokeBB);
4357  }
4358  else {
4359  // In all other cases relocate should be tied to the statepoint directly.
4360  // This covers relocates on a normal return path of invoke statepoint and
4361  // relocates of a call statepoint.
4362  auto Token = CS.getArgOperand(0);
4363  Assert(isa<Instruction>(Token) && isStatepoint(cast<Instruction>(Token)),
4364  "gc relocate is incorrectly tied to the statepoint", CS, Token);
4365  }
4366 
4367  // Verify rest of the relocate arguments.
4368 
4369  ImmutableCallSite StatepointCS(
4370  cast<GCRelocateInst>(*CS.getInstruction()).getStatepoint());
4371 
4372  // Both the base and derived must be piped through the safepoint.
4373  Value* Base = CS.getArgOperand(1);
4374  Assert(isa<ConstantInt>(Base),
4375  "gc.relocate operand #2 must be integer offset", CS);
4376 
4377  Value* Derived = CS.getArgOperand(2);
4378  Assert(isa<ConstantInt>(Derived),
4379  "gc.relocate operand #3 must be integer offset", CS);
4380 
4381  const int BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
4382  const int DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
4383  // Check the bounds
4384  Assert(0 <= BaseIndex && BaseIndex < (int)StatepointCS.arg_size(),
4385  "gc.relocate: statepoint base index out of bounds", CS);
4386  Assert(0 <= DerivedIndex && DerivedIndex < (int)StatepointCS.arg_size(),
4387  "gc.relocate: statepoint derived index out of bounds", CS);
4388 
4389  // Check that BaseIndex and DerivedIndex fall within the 'gc parameters'
4390  // section of the statepoint's argument.
4391  Assert(StatepointCS.arg_size() > 0,
4392  "gc.statepoint: insufficient arguments");
4393  Assert(isa<ConstantInt>(StatepointCS.getArgument(3)),
4394  "gc.statement: number of call arguments must be constant integer");
4395  const unsigned NumCallArgs =
4396  cast<ConstantInt>(StatepointCS.getArgument(3))->getZExtValue();
4397  Assert(StatepointCS.arg_size() > NumCallArgs + 5,
4398  "gc.statepoint: mismatch in number of call arguments");
4399  Assert(isa<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 5)),
4400  "gc.statepoint: number of transition arguments must be "
4401  "a constant integer");
4402  const int NumTransitionArgs =
4403  cast<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 5))
4404  ->getZExtValue();
4405  const int DeoptArgsStart = 4 + NumCallArgs + 1 + NumTransitionArgs + 1;
4406  Assert(isa<ConstantInt>(StatepointCS.getArgument(DeoptArgsStart)),
4407  "gc.statepoint: number of deoptimization arguments must be "
4408  "a constant integer");
4409  const int NumDeoptArgs =
4410  cast<ConstantInt>(StatepointCS.getArgument(DeoptArgsStart))
4411  ->getZExtValue();
4412  const int GCParamArgsStart = DeoptArgsStart + 1 + NumDeoptArgs;
4413  const int GCParamArgsEnd = StatepointCS.arg_size();
4414  Assert(GCParamArgsStart <= BaseIndex && BaseIndex < GCParamArgsEnd,
4415  "gc.relocate: statepoint base index doesn't fall within the "
4416  "'gc parameters' section of the statepoint call",
4417  CS);
4418  Assert(GCParamArgsStart <= DerivedIndex && DerivedIndex < GCParamArgsEnd,
4419  "gc.relocate: statepoint derived index doesn't fall within the "
4420  "'gc parameters' section of the statepoint call",
4421  CS);
4422 
4423  // Relocated value must be either a pointer type or vector-of-pointer type,
4424  // but gc_relocate does not need to return the same pointer type as the
4425  // relocated pointer. It can be casted to the correct type later if it's
4426  // desired. However, they must have the same address space and 'vectorness'
4427  GCRelocateInst &Relocate = cast<GCRelocateInst>(*CS.getInstruction());
4429  "gc.relocate: relocated value must be a gc pointer", CS);
4430 
4431  auto ResultType = CS.getType();
4432  auto DerivedType = Relocate.getDerivedPtr()->getType();
4433  Assert(ResultType->isVectorTy() == DerivedType->isVectorTy(),
4434  "gc.relocate: vector relocates to vector and pointer to pointer",
4435  CS);
4436  Assert(
4437  ResultType->getPointerAddressSpace() ==
4438  DerivedType->getPointerAddressSpace(),
4439  "gc.relocate: relocating a pointer shouldn't change its address space",
4440  CS);
4441  break;
4442  }
4443  case Intrinsic::eh_exceptioncode:
4444  case Intrinsic::eh_exceptionpointer: {
4445  Assert(isa<CatchPadInst>(CS.getArgOperand(0)),
4446  "eh.exceptionpointer argument must be a catchpad", CS);
4447  break;
4448  }
4449  case Intrinsic::masked_load: {
4450  Assert(CS.getType()->isVectorTy(), "masked_load: must return a vector", CS);
4451 
4452  Value *Ptr = CS.getArgOperand(0);
4453  //Value *Alignment = CS.getArgOperand(1);
4454  Value *Mask = CS.getArgOperand(2);
4455  Value *PassThru = CS.getArgOperand(3);
4456  Assert(Mask->getType()->isVectorTy(),
4457  "masked_load: mask must be vector", CS);
4458 
4459  // DataTy is the overloaded type
4460  Type *DataTy = cast<PointerType>(Ptr->getType())->getElementType();
4461  Assert(DataTy == CS.getType(),
4462  "masked_load: return must match pointer type", CS);
4463  Assert(PassThru->getType() == DataTy,
4464  "masked_load: pass through and data type must match", CS);
4465  Assert(Mask->getType()->getVectorNumElements() ==
4466  DataTy->getVectorNumElements(),
4467  "masked_load: vector mask must be same length as data", CS);
4468  break;
4469  }
4470  case Intrinsic::masked_store: {
4471  Value *Val = CS.getArgOperand(0);
4472  Value *Ptr = CS.getArgOperand(1);
4473  //Value *Alignment = CS.getArgOperand(2);
4474  Value *Mask = CS.getArgOperand(3);
4475  Assert(Mask->getType()->isVectorTy(),
4476  "masked_store: mask must be vector", CS);
4477 
4478  // DataTy is the overloaded type
4479  Type *DataTy = cast<PointerType>(Ptr->getType())->getElementType();
4480  Assert(DataTy == Val->getType(),
4481  "masked_store: storee must match pointer type", CS);
4482  Assert(Mask->getType()->getVectorNumElements() ==
4483  DataTy->getVectorNumElements(),
4484  "masked_store: vector mask must be same length as data", CS);
4485  break;
4486  }
4487 
4488  case Intrinsic::experimental_guard: {
4489  Assert(CS.isCall(), "experimental_guard cannot be invoked", CS);
4491  "experimental_guard must have exactly one "
4492  "\"deopt\" operand bundle");
4493  break;
4494  }
4495 
4496  case Intrinsic::experimental_deoptimize: {
4497  Assert(CS.isCall(), "experimental_deoptimize cannot be invoked", CS);
4499  "experimental_deoptimize must have exactly one "
4500  "\"deopt\" operand bundle");
4502  "experimental_deoptimize return type must match caller return type");
4503 
4504  if (CS.isCall()) {
4505  auto *DeoptCI = CS.getInstruction();
4506  auto *RI = dyn_cast<ReturnInst>(DeoptCI->getNextNode());
4507  Assert(RI,
4508  "calls to experimental_deoptimize must be followed by a return");
4509 
4510  if (!CS.getType()->isVoidTy() && RI)
4511  Assert(RI->getReturnValue() == DeoptCI,
4512  "calls to experimental_deoptimize must be followed by a return "
4513  "of the value computed by experimental_deoptimize");
4514  }
4515 
4516  break;
4517  }
4518  case Intrinsic::sadd_sat:
4519  case Intrinsic::uadd_sat:
4520  case Intrinsic::ssub_sat:
4521  case Intrinsic::usub_sat: {
4522  Value *Op1 = CS.getArgOperand(0);
4523  Value *Op2 = CS.getArgOperand(1);
4524  Assert(Op1->getType()->isIntOrIntVectorTy(),
4525  "first operand of [us][add|sub]_sat must be an int type or vector "
4526  "of ints");
4527  Assert(Op2->getType()->isIntOrIntVectorTy(),
4528  "second operand of [us][add|sub]_sat must be an int type or vector "
4529  "of ints");
4530  break;
4531  }
4532  };
4533 }
4534 
4535 /// Carefully grab the subprogram from a local scope.
4536 ///
4537 /// This carefully grabs the subprogram from a local scope, avoiding the
4538 /// built-in assertions that would typically fire.
4539 static DISubprogram *getSubprogram(Metadata *LocalScope) {
4540  if (!LocalScope)
4541  return nullptr;
4542 
4543  if (auto *SP = dyn_cast<DISubprogram>(LocalScope))
4544  return SP;
4545 
4546  if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope))
4547  return getSubprogram(LB->getRawScope());
4548 
4549  // Just return null; broken scope chains are checked elsewhere.
4550  assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope");
4551  return nullptr;
4552 }
4553 
4554 void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) {
4555  unsigned NumOperands = FPI.getNumArgOperands();
4556  Assert(((NumOperands == 5 && FPI.isTernaryOp()) ||
4557  (NumOperands == 3 && FPI.isUnaryOp()) || (NumOperands == 4)),
4558  "invalid arguments for constrained FP intrinsic", &FPI);
4559  Assert(isa<MetadataAsValue>(FPI.getArgOperand(NumOperands-1)),
4560  "invalid exception behavior argument", &FPI);
4561  Assert(isa<MetadataAsValue>(FPI.getArgOperand(NumOperands-2)),
4562  "invalid rounding mode argument", &FPI);
4564  "invalid rounding mode argument", &FPI);
4566  "invalid exception behavior argument", &FPI);
4567 }
4568 
4569 void Verifier::visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII) {
4570  auto *MD = cast<MetadataAsValue>(DII.getArgOperand(0))->getMetadata();
4571  AssertDI(isa<ValueAsMetadata>(MD) ||
4572  (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()),
4573  "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD);
4574  AssertDI(isa<DILocalVariable>(DII.getRawVariable()),
4575  "invalid llvm.dbg." + Kind + " intrinsic variable", &DII,
4576  DII.getRawVariable());
4577  AssertDI(isa<DIExpression>(DII.getRawExpression()),
4578  "invalid llvm.dbg." + Kind + " intrinsic expression", &DII,
4579  DII.getRawExpression());
4580 
4581  // Ignore broken !dbg attachments; they're checked elsewhere.
4582  if (MDNode *N = DII.getDebugLoc().getAsMDNode())
4583  if (!isa<DILocation>(N))
4584  return;
4585 
4586  BasicBlock *BB = DII.getParent();
4587  Function *F = BB ? BB->getParent() : nullptr;
4588 
4589  // The scopes for variables and !dbg attachments must agree.
4590  DILocalVariable *Var = DII.getVariable();
4591  DILocation *Loc = DII.getDebugLoc();
4592  AssertDI(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment",
4593  &DII, BB, F);
4594 
4595  DISubprogram *VarSP = getSubprogram(Var->getRawScope());
4596  DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
4597  if (!VarSP || !LocSP)
4598  return; // Broken scope chains are checked elsewhere.
4599 
4600  AssertDI(VarSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind +
4601  " variable and !dbg attachment",
4602  &DII, BB, F, Var, Var->getScope()->getSubprogram(), Loc,
4603  Loc->getScope()->getSubprogram());
4604 
4605  // This check is redundant with one in visitLocalVariable().
4606  AssertDI(isType(Var->getRawType()), "invalid type ref", Var,
4607  Var->getRawType());
4608  if (auto *Type = dyn_cast_or_null<DIType>(Var->getRawType()))
4609  if (Type->isBlockByrefStruct())
4611  "BlockByRef variable without complex expression", Var, &DII);
4612 
4613  verifyFnArgs(DII);
4614 }
4615 
4616 void Verifier::visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI) {
4617  AssertDI(isa<DILabel>(DLI.getRawLabel()),
4618  "invalid llvm.dbg." + Kind + " intrinsic variable", &DLI,
4619  DLI.getRawLabel());
4620 
4621  // Ignore broken !dbg attachments; they're checked elsewhere.
4622  if (MDNode *N = DLI.getDebugLoc().getAsMDNode())
4623  if (!isa<DILocation>(N))
4624  return;
4625 
4626  BasicBlock *BB = DLI.getParent();
4627  Function *F = BB ? BB->getParent() : nullptr;
4628 
4629  // The scopes for variables and !dbg attachments must agree.
4630  DILabel *Label = DLI.getLabel();
4631  DILocation *Loc = DLI.getDebugLoc();
4632  Assert(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment",
4633  &DLI, BB, F);
4634 
4635  DISubprogram *LabelSP = getSubprogram(Label->getRawScope());
4636  DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
4637  if (!LabelSP || !LocSP)
4638  return;
4639 
4640  AssertDI(LabelSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind +
4641  " label and !dbg attachment",
4642  &DLI, BB, F, Label, Label->getScope()->getSubprogram(), Loc,
4643  Loc->getScope()->getSubprogram());
4644 }
4645 
4646 void Verifier::verifyFragmentExpression(const DbgVariableIntrinsic &I) {
4647  DILocalVariable *V = dyn_cast_or_null<DILocalVariable>(I.getRawVariable());
4648  DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression());
4649 
4650  // We don't know whether this intrinsic verified correctly.
4651  if (!V || !E || !E->isValid())
4652  return;
4653 
4654  // Nothing to do if this isn't a DW_OP_LLVM_fragment expression.
4655  auto Fragment = E->getFragmentInfo();
4656  if (!Fragment)
4657  return;
4658 
4659  // The frontend helps out GDB by emitting the members of local anonymous
4660  // unions as artificial local variables with shared storage. When SROA splits
4661  // the storage for artificial local variables that are smaller than the entire
4662  // union, the overhang piece will be outside of the allotted space for the
4663  // variable and this check fails.
4664  // FIXME: Remove this check as soon as clang stops doing this; it hides bugs.
4665  if (V->isArtificial())
4666  return;
4667 
4668  verifyFragmentExpression(*V, *Fragment, &I);
4669 }
4670 
4671 template <typename ValueOrMetadata>
4672 void Verifier::verifyFragmentExpression(const DIVariable &V,
4673  DIExpression::FragmentInfo Fragment,
4674  ValueOrMetadata *Desc) {
4675  // If there's no size, the type is broken, but that should be checked
4676  // elsewhere.
4677  auto VarSize = V.getSizeInBits();
4678  if (!VarSize)
4679  return;
4680 
4681  unsigned FragSize = Fragment.SizeInBits;
4682  unsigned FragOffset = Fragment.OffsetInBits;
4683  AssertDI(FragSize + FragOffset <= *VarSize,
4684  "fragment is larger than or outside of variable", Desc, &V);
4685  AssertDI(FragSize != *VarSize, "fragment covers entire variable", Desc, &V);
4686 }
4687 
4688 void Verifier::verifyFnArgs(const DbgVariableIntrinsic &I) {
4689  // This function does not take the scope of noninlined function arguments into
4690  // account. Don't run it if current function is nodebug, because it may
4691  // contain inlined debug intrinsics.
4692  if (!HasDebugInfo)
4693  return;
4694 
4695  // For performance reasons only check non-inlined ones.
4696  if (I.getDebugLoc()->getInlinedAt())
4697  return;
4698 
4699  DILocalVariable *Var = I.getVariable();
4700  AssertDI(Var, "dbg intrinsic without variable");
4701 
4702  unsigned ArgNo = Var->getArg();
4703  if (!ArgNo)
4704  return;
4705 
4706  // Verify there are no duplicate function argument debug info entries.
4707  // These will cause hard-to-debug assertions in the DWARF backend.
4708  if (DebugFnArgs.size() < ArgNo)
4709  DebugFnArgs.resize(ArgNo, nullptr);
4710 
4711  auto *Prev = DebugFnArgs[ArgNo - 1];
4712  DebugFnArgs[ArgNo - 1] = Var;
4713  AssertDI(!Prev || (Prev == Var), "conflicting debug info for argument", &I,
4714  Prev, Var);
4715 }
4716 
4717 void Verifier::verifyCompileUnits() {
4718  // When more than one Module is imported into the same context, such as during
4719  // an LTO build before linking the modules, ODR type uniquing may cause types
4720  // to point to a different CU. This check does not make sense in this case.
4722  return;
4723  auto *CUs = M.getNamedMetadata("llvm.dbg.cu");
4725  if (CUs)
4726  Listed.insert(CUs->op_begin(), CUs->op_end());
4727  for (auto *CU : CUVisited)
4728  AssertDI(Listed.count(CU), "DICompileUnit not listed in llvm.dbg.cu", CU);
4729  CUVisited.clear();
4730 }
4731 
4732 void Verifier::verifyDeoptimizeCallingConvs() {
4733  if (DeoptimizeDeclarations.empty())
4734  return;
4735 
4736  const Function *First = DeoptimizeDeclarations[0];
4737  for (auto *F : makeArrayRef(DeoptimizeDeclarations).slice(1)) {
4738  Assert(First->getCallingConv() == F->getCallingConv(),
4739  "All llvm.experimental.deoptimize declarations must have the same "
4740  "calling convention",
4741  First, F);
4742  }
4743 }
4744 
4745 //===----------------------------------------------------------------------===//
4746 // Implement the public interfaces to this file...
4747 //===----------------------------------------------------------------------===//
4748 
4750  Function &F = const_cast<Function &>(f);
4751 
4752  // Don't use a raw_null_ostream. Printing IR is expensive.
4753  Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/true, *f.getParent());
4754 
4755  // Note that this function's return value is inverted from what you would
4756  // expect of a function called "verify".
4757  return !V.verify(F);
4758 }
4759 
4761  bool *BrokenDebugInfo) {
4762  // Don't use a raw_null_ostream. Printing IR is expensive.
4763  Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/!BrokenDebugInfo, M);
4764 
4765  bool Broken = false;
4766  for (const Function &F : M)
4767  Broken |= !V.verify(F);
4768 
4769  Broken |= !V.verify();
4770  if (BrokenDebugInfo)
4771  *BrokenDebugInfo = V.hasBrokenDebugInfo();
4772  // Note that this function's return value is inverted from what you would
4773  // expect of a function called "verify".
4774  return Broken;
4775 }
4776 
4777 namespace {
4778 
4779 struct VerifierLegacyPass : public FunctionPass {
4780  static char ID;
4781 
4782  std::unique_ptr<Verifier> V;
4783  bool FatalErrors = true;
4784 
4785  VerifierLegacyPass() : FunctionPass(ID) {
4787  }
4788  explicit VerifierLegacyPass(bool FatalErrors)
4789  : FunctionPass(ID),
4790  FatalErrors(FatalErrors) {
4792  }
4793 
4794  bool doInitialization(Module &M) override {
4795  V = llvm::make_unique<Verifier>(
4796  &dbgs(), /*ShouldTreatBrokenDebugInfoAsError=*/false, M);
4797  return false;
4798  }
4799 
4800  bool runOnFunction(Function &F) override {
4801  if (!V->verify(F) && FatalErrors) {
4802  errs() << "in function " << F.getName() << '\n';
4803  report_fatal_error("Broken function found, compilation aborted!");
4804  }
4805  return false;
4806  }
4807 
4808  bool doFinalization(Module &M) override {
4809  bool HasErrors = false;
4810  for (Function &F : M)
4811  if (F.isDeclaration())
4812  HasErrors |= !V->verify(F);
4813 
4814  HasErrors |= !V->verify();
4815  if (FatalErrors && (HasErrors || V->hasBrokenDebugInfo()))
4816  report_fatal_error("Broken module found, compilation aborted!");
4817  return false;
4818  }
4819 
4820  void getAnalysisUsage(AnalysisUsage &AU) const override {
4821  AU.setPreservesAll();
4822  }
4823 };
4824 
4825 } // end anonymous namespace
4826 
4827 /// Helper to issue failure from the TBAA verification
4828 template <typename... Tys> void TBAAVerifier::CheckFailed(Tys &&... Args) {
4829  if (Diagnostic)
4830  return Diagnostic->CheckFailed(Args...);
4831 }
4832 
4833 #define AssertTBAA(C, ...) \
4834  do { \
4835  if (!(C)) { \
4836  CheckFailed(__VA_ARGS__); \
4837  return false; \
4838  } \
4839  } while (false)
4840 
4841 /// Verify that \p BaseNode can be used as the "base type" in the struct-path
4842 /// TBAA scheme. This means \p BaseNode is either a scalar node, or a
4843 /// struct-type node describing an aggregate data structure (like a struct).
4844 TBAAVerifier::TBAABaseNodeSummary
4845 TBAAVerifier::verifyTBAABaseNode(Instruction &I, const MDNode *BaseNode,
4846  bool IsNewFormat) {
4847  if (BaseNode->getNumOperands() < 2) {
4848  CheckFailed("Base nodes must have at least two operands", &I, BaseNode);
4849  return {true, ~0u};
4850  }
4851 
4852  auto Itr = TBAABaseNodes.find(BaseNode);
4853  if (Itr != TBAABaseNodes.end())
4854  return Itr->second;
4855 
4856  auto Result = verifyTBAABaseNodeImpl(I, BaseNode, IsNewFormat);
4857  auto InsertResult = TBAABaseNodes.insert({BaseNode, Result});
4858  (void)InsertResult;
4859  assert(InsertResult.second && "We just checked!");
4860  return Result;
4861 }
4862 
4863 TBAAVerifier::TBAABaseNodeSummary
4864 TBAAVerifier::verifyTBAABaseNodeImpl(Instruction &I, const MDNode *BaseNode,
4865  bool IsNewFormat) {
4866  const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {true, ~0u};
4867 
4868  if (BaseNode->getNumOperands() == 2) {
4869  // Scalar nodes can only be accessed at offset 0.
4870  return isValidScalarTBAANode(BaseNode)
4871  ? TBAAVerifier::TBAABaseNodeSummary({false, 0})
4872  : InvalidNode;
4873  }
4874 
4875  if (IsNewFormat) {
4876  if (BaseNode->getNumOperands() % 3 != 0) {
4877  CheckFailed("Access tag nodes must have the number of operands that is a "
4878  "multiple of 3!", BaseNode);
4879  return InvalidNode;
4880  }
4881  } else {
4882  if (BaseNode->getNumOperands() % 2 != 1) {
4883  CheckFailed("Struct tag nodes must have an odd number of operands!",
4884  BaseNode);
4885  return InvalidNode;
4886  }
4887  }
4888 
4889  // Check the type size field.
4890  if (IsNewFormat) {
4891  auto *TypeSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
4892  BaseNode->getOperand(1));
4893  if (!TypeSizeNode) {
4894  CheckFailed("Type size nodes must be constants!", &I, BaseNode);
4895  return InvalidNode;
4896  }
4897  }
4898 
4899  // Check the type name field. In the new format it can be anything.
4900  if (!IsNewFormat && !isa<MDString>(BaseNode->getOperand(0))) {
4901  CheckFailed("Struct tag nodes have a string as their first operand",
4902  BaseNode);
4903  return InvalidNode;
4904  }
4905 
4906  bool Failed = false;
4907 
4908  Optional<APInt> PrevOffset;
4909  unsigned BitWidth = ~0u;
4910 
4911  // We've already checked that BaseNode is not a degenerate root node with one
4912  // operand in \c verifyTBAABaseNode, so this loop should run at least once.
4913  unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
4914  unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
4915  for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
4916  Idx += NumOpsPerField) {
4917  const MDOperand &FieldTy = BaseNode->getOperand(Idx);
4918  const MDOperand &FieldOffset = BaseNode->getOperand(Idx + 1);
4919  if (!isa<MDNode>(FieldTy)) {
4920  CheckFailed("Incorrect field entry in struct type node!", &I, BaseNode);
4921  Failed = true;
4922  continue;
4923  }
4924 
4925  auto *OffsetEntryCI =
4926  mdconst::dyn_extract_or_null<ConstantInt>(FieldOffset);
4927  if (!OffsetEntryCI) {
4928  CheckFailed("Offset entries must be constants!", &I, BaseNode);
4929  Failed = true;
4930  continue;
4931  }
4932 
4933  if (BitWidth == ~0u)
4934  BitWidth = OffsetEntryCI->getBitWidth();
4935 
4936  if (OffsetEntryCI->getBitWidth() != BitWidth) {
4937  CheckFailed(
4938  "Bitwidth between the offsets and struct type entries must match", &I,
4939  BaseNode);
4940  Failed = true;
4941  continue;
4942  }
4943 
4944  // NB! As far as I can tell, we generate a non-strictly increasing offset
4945  // sequence only from structs that have zero size bit fields. When
4946  // recursing into a contained struct in \c getFieldNodeFromTBAABaseNode we
4947  // pick the field lexically the latest in struct type metadata node. This
4948  // mirrors the actual behavior of the alias analysis implementation.
4949  bool IsAscending =
4950  !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue());
4951 
4952  if (!IsAscending) {
4953  CheckFailed("Offsets must be increasing!", &I, BaseNode);
4954  Failed = true;
4955  }
4956 
4957  PrevOffset = OffsetEntryCI->getValue();
4958 
4959  if (IsNewFormat) {
4960  auto *MemberSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
4961  BaseNode->getOperand(Idx + 2));
4962  if (!MemberSizeNode) {
4963  CheckFailed("Member size entries must be constants!", &I, BaseNode);
4964  Failed = true;
4965  continue;
4966  }
4967  }
4968  }
4969 
4970  return Failed ? InvalidNode
4971  : TBAAVerifier::TBAABaseNodeSummary(false, BitWidth);
4972 }
4973 
4974 static bool IsRootTBAANode(const MDNode *MD) {
4975  return MD->getNumOperands() < 2;
4976 }
4977 
4978 static bool IsScalarTBAANodeImpl(const MDNode *MD,
4980  if (MD->getNumOperands() != 2 && MD->getNumOperands() != 3)
4981  return false;
4982 
4983  if (!isa<MDString>(MD->getOperand(0)))
4984  return false;
4985 
4986  if (MD->getNumOperands() == 3) {
4987  auto *Offset = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
4988  if (!(Offset && Offset->isZero() && isa<MDString>(MD->getOperand(0))))
4989  return false;
4990  }
4991 
4992  auto *Parent = dyn_cast_or_null<MDNode>(MD->getOperand(1));
4993  return Parent && Visited.insert(Parent).second &&
4994  (IsRootTBAANode(Parent) || IsScalarTBAANodeImpl(Parent, Visited));
4995 }
4996 
4997 bool TBAAVerifier::isValidScalarTBAANode(const MDNode *MD) {
4998  auto ResultIt = TBAAScalarNodes.find(MD);
4999  if (ResultIt != TBAAScalarNodes.end())
5000  return ResultIt->second;
5001 
5003  bool Result = IsScalarTBAANodeImpl(MD, Visited);
5004  auto InsertResult = TBAAScalarNodes.insert({MD, Result});
5005  (void)InsertResult;
5006  assert(InsertResult.second && "Just checked!");
5007 
5008  return Result;
5009 }
5010 
5011 /// Returns the field node at the offset \p Offset in \p BaseNode. Update \p
5012 /// Offset in place to be the offset within the field node returned.
5013 ///
5014 /// We assume we've okayed \p BaseNode via \c verifyTBAABaseNode.
5015 MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(Instruction &I,
5016  const MDNode *BaseNode,
5017  APInt &Offset,
5018  bool IsNewFormat) {
5019  assert(BaseNode->getNumOperands() >= 2 && "Invalid base node!");
5020 
5021  // Scalar nodes have only one possible "field" -- their parent in the access
5022  // hierarchy. Offset must be zero at this point, but our caller is supposed
5023  // to Assert that.
5024  if (BaseNode->getNumOperands() == 2)
5025  return cast<MDNode>(BaseNode->getOperand(1));
5026 
5027  unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
5028  unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
5029  for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
5030  Idx += NumOpsPerField) {
5031  auto *OffsetEntryCI =
5032  mdconst::extract<ConstantInt>(BaseNode->getOperand(Idx + 1));
5033  if (OffsetEntryCI->getValue().ugt(Offset)) {
5034  if (Idx == FirstFieldOpNo) {
5035  CheckFailed("Could not find TBAA parent in struct type node", &I,
5036  BaseNode, &Offset);
5037  return nullptr;
5038  }
5039 
5040  unsigned PrevIdx = Idx - NumOpsPerField;
5041  auto *PrevOffsetEntryCI =
5042  mdconst::extract<ConstantInt>(BaseNode->getOperand(PrevIdx + 1));
5043  Offset -= PrevOffsetEntryCI->getValue();
5044  return cast<MDNode>(BaseNode->getOperand(PrevIdx));
5045  }
5046  }
5047 
5048  unsigned LastIdx = BaseNode->getNumOperands() - NumOpsPerField;
5049  auto *LastOffsetEntryCI = mdconst::extract<ConstantInt>(
5050  BaseNode->getOperand(LastIdx + 1));
5051  Offset -= LastOffsetEntryCI->getValue();
5052  return cast<MDNode>(BaseNode->getOperand(LastIdx));
5053 }
5054 
5056  if (!Type || Type->getNumOperands() < 3)
5057  return false;
5058 
5059  // In the new format type nodes shall have a reference to the parent type as
5060  // its first operand.
5061  MDNode *Parent = dyn_cast_or_null<MDNode>(Type->getOperand(0));
5062  if (!Parent)
5063  return false;
5064 
5065  return true;
5066 }
5067 
5069  AssertTBAA(isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallInst>(I) ||
5070  isa<VAArgInst>(I) || isa<AtomicRMWInst>(I) ||
5071  isa<AtomicCmpXchgInst>(I),
5072  "This instruction shall not have a TBAA access tag!", &I);
5073 
5074  bool IsStructPathTBAA =
5075  isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3;
5076 
5077  AssertTBAA(
5078  IsStructPathTBAA,
5079  "Old-style TBAA is no longer allowed, use struct-path TBAA instead", &I);
5080 
5081  MDNode *BaseNode = dyn_cast_or_null<MDNode>(MD->getOperand(0));
5082  MDNode *AccessType = dyn_cast_or_null<MDNode>(MD->getOperand(1));
5083 
5084  bool IsNewFormat = isNewFormatTBAATypeNode(AccessType);
5085 
5086  if (IsNewFormat) {
5087  AssertTBAA(MD->getNumOperands() == 4 || MD->getNumOperands() == 5,
5088  "Access tag metadata must have either 4 or 5 operands", &I, MD);
5089  } else {
5090  AssertTBAA(MD->getNumOperands() < 5,
5091  "Struct tag metadata must have either 3 or 4 operands", &I, MD);
5092  }
5093 
5094  // Check the access size field.
5095  if (IsNewFormat) {
5096  auto *AccessSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
5097  MD->getOperand(3));
5098  AssertTBAA(AccessSizeNode, "Access size field must be a constant", &I, MD);
5099  }
5100 
5101  // Check the immutability flag.
5102  unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3;
5103  if (MD->getNumOperands() == ImmutabilityFlagOpNo + 1) {
5104  auto *IsImmutableCI = mdconst::dyn_extract_or_null<ConstantInt>(
5105  MD->getOperand(ImmutabilityFlagOpNo));
5106  AssertTBAA(IsImmutableCI,
5107  "Immutability tag on struct tag metadata must be a constant",
5108  &I, MD);
5109  AssertTBAA(
5110  IsImmutableCI->isZero() || IsImmutableCI->isOne(),
5111  "Immutability part of the struct tag metadata must be either 0 or 1",
5112  &I, MD);
5113  }
5114 
5115  AssertTBAA(BaseNode && AccessType,
5116  "Malformed struct tag metadata: base and access-type "
5117  "should be non-null and point to Metadata nodes",
5118  &I, MD, BaseNode, AccessType);
5119 
5120  if (!IsNewFormat) {
5121  AssertTBAA(isValidScalarTBAANode(AccessType),
5122  "Access type node must be a valid scalar type", &I, MD,
5123  AccessType);
5124  }
5125 
5126  auto *OffsetCI = mdconst::dyn_extract_or_null<ConstantInt>(MD->getOperand(2));
5127  AssertTBAA(OffsetCI, "Offset must be constant integer", &I, MD);
5128 
5129  APInt Offset = OffsetCI->getValue();
5130  bool SeenAccessTypeInPath = false;
5131 
5132  SmallPtrSet<MDNode *, 4> StructPath;
5133 
5134  for (/* empty */; BaseNode && !IsRootTBAANode(BaseNode);
5135  BaseNode = getFieldNodeFromTBAABaseNode(I, BaseNode, Offset,
5136  IsNewFormat)) {
5137  if (!StructPath.insert(BaseNode).second) {
5138  CheckFailed("Cycle detected in struct path", &I, MD);
5139  return false;
5140  }
5141 
5142  bool Invalid;
5143  unsigned BaseNodeBitWidth;
5144  std::tie(Invalid, BaseNodeBitWidth) = verifyTBAABaseNode(I, BaseNode,
5145  IsNewFormat);
5146 
5147  // If the base node is invalid in itself, then we've already printed all the
5148  // errors we wanted to print.
5149  if (Invalid)
5150  return false;
5151 
5152  SeenAccessTypeInPath |= BaseNode == AccessType;
5153 
5154  if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType)
5155  AssertTBAA(Offset == 0, "Offset not zero at the point of scalar access",
5156  &I, MD, &Offset);
5157 
5158  AssertTBAA(BaseNodeBitWidth == Offset.getBitWidth() ||
5159  (BaseNodeBitWidth == 0 && Offset == 0) ||
5160  (IsNewFormat && BaseNodeBitWidth == ~0u),
5161  "Access bit-width not the same as description bit-width", &I, MD,
5162  BaseNodeBitWidth, Offset.getBitWidth());
5163 
5164  if (IsNewFormat && SeenAccessTypeInPath)
5165  break;
5166  }
5167 
5168  AssertTBAA(SeenAccessTypeInPath, "Did not see access type in access path!",
5169  &I, MD);
5170  return true;
5171 }
5172 
5173 char VerifierLegacyPass::ID = 0;
5174 INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
5175 
5176 FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
5177  return new VerifierLegacyPass(FatalErrors);
5178 }
5179 
5180 AnalysisKey VerifierAnalysis::Key;
5183  Result Res;
5184  Res.IRBroken = llvm::verifyModule(M, &dbgs(), &Res.DebugInfoBroken);
5185  return Res;
5186 }
5187 
5190  return { llvm::verifyFunction(F, &dbgs()), false };
5191 }
5192 
5194  auto Res = AM.getResult<VerifierAnalysis>(M);
5195  if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken))
5196  report_fatal_error("Broken module found, compilation aborted!");
5197 
5198  return PreservedAnalyses::all();
5199 }
5200 
5202  auto res = AM.getResult<VerifierAnalysis>(F);
5203  if (res.IRBroken && FatalErrors)
5204  report_fatal_error("Broken function found, compilation aborted!");
5205 
5206  return PreservedAnalyses::all();
5207 }
DIFlags getFlags() const
bool isDeclarationForLinker() const
Definition: GlobalValue.h:524
Metadata * getRawRetainedTypes() const
uint64_t CallInst * C
Return a value (possibly void), from a function.
User::op_iterator arg_iterator
The type of iterator to use when looping over actual arguments at this call site. ...
Definition: CallSite.h:213
bool isIntrinsic() const
isIntrinsic - Returns true if the function&#39;s name starts with "llvm.".
Definition: Function.h:199
static bool isScope(const Metadata *MD)
Definition: Verifier.cpp:852
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
Definition: Constants.h:172
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111