c47a0ff1d80dd93fb4e248971c455ad2d78ae63e
[oota-llvm.git] / lib / IR / Verifier.cpp
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 //  * All landingpad instructions must use the same personality function with
43 //    the same function.
44 //  * All other things that are tested by asserts spread about the code...
45 //
46 //===----------------------------------------------------------------------===//
47
48 #include "llvm/IR/Verifier.h"
49 #include "llvm/ADT/STLExtras.h"
50 #include "llvm/ADT/SetVector.h"
51 #include "llvm/ADT/SmallPtrSet.h"
52 #include "llvm/ADT/SmallVector.h"
53 #include "llvm/ADT/StringExtras.h"
54 #include "llvm/IR/CFG.h"
55 #include "llvm/IR/CallSite.h"
56 #include "llvm/IR/CallingConv.h"
57 #include "llvm/IR/ConstantRange.h"
58 #include "llvm/IR/Constants.h"
59 #include "llvm/IR/DataLayout.h"
60 #include "llvm/IR/DebugInfo.h"
61 #include "llvm/IR/DerivedTypes.h"
62 #include "llvm/IR/Dominators.h"
63 #include "llvm/IR/InlineAsm.h"
64 #include "llvm/IR/InstIterator.h"
65 #include "llvm/IR/InstVisitor.h"
66 #include "llvm/IR/IntrinsicInst.h"
67 #include "llvm/IR/LLVMContext.h"
68 #include "llvm/IR/Metadata.h"
69 #include "llvm/IR/Module.h"
70 #include "llvm/IR/PassManager.h"
71 #include "llvm/IR/Statepoint.h"
72 #include "llvm/Pass.h"
73 #include "llvm/Support/CommandLine.h"
74 #include "llvm/Support/Debug.h"
75 #include "llvm/Support/ErrorHandling.h"
76 #include "llvm/Support/raw_ostream.h"
77 #include <algorithm>
78 #include <cstdarg>
79 using namespace llvm;
80
81 static cl::opt<bool> VerifyDebugInfo("verify-debug-info", cl::init(true));
82
83 namespace {
84 struct VerifierSupport {
85   raw_ostream &OS;
86   const Module *M;
87
88   /// \brief Track the brokenness of the module while recursively visiting.
89   bool Broken;
90
91   explicit VerifierSupport(raw_ostream &OS)
92       : OS(OS), M(nullptr), Broken(false) {}
93
94 private:
95   void Write(const Value *V) {
96     if (!V)
97       return;
98     if (isa<Instruction>(V)) {
99       OS << *V << '\n';
100     } else {
101       V->printAsOperand(OS, true, M);
102       OS << '\n';
103     }
104   }
105   void Write(const CallSite *CS) {
106     if (!CS) 
107       return;
108     Write(CS->getInstruction());
109   }
110
111   void Write(const Metadata *MD) {
112     if (!MD)
113       return;
114     MD->print(OS, M);
115     OS << '\n';
116   }
117
118   template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) {
119     Write(MD.get());
120   }
121
122   void Write(const NamedMDNode *NMD) {
123     if (!NMD)
124       return;
125     NMD->print(OS);
126     OS << '\n';
127   }
128
129   void Write(Type *T) {
130     if (!T)
131       return;
132     OS << ' ' << *T;
133   }
134
135   void Write(const Comdat *C) {
136     if (!C)
137       return;
138     OS << *C;
139   }
140
141   template <typename T1, typename... Ts>
142   void WriteTs(const T1 &V1, const Ts &... Vs) {
143     Write(V1);
144     WriteTs(Vs...);
145   }
146
147   template <typename... Ts> void WriteTs() {}
148
149 public:
150   /// \brief A check failed, so printout out the condition and the message.
151   ///
152   /// This provides a nice place to put a breakpoint if you want to see why
153   /// something is not correct.
154   void CheckFailed(const Twine &Message) {
155     OS << Message << '\n';
156     Broken = true;
157   }
158
159   /// \brief A check failed (with values to print).
160   ///
161   /// This calls the Message-only version so that the above is easier to set a
162   /// breakpoint on.
163   template <typename T1, typename... Ts>
164   void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
165     CheckFailed(Message);
166     WriteTs(V1, Vs...);
167   }
168 };
169
170 class Verifier : public InstVisitor<Verifier>, VerifierSupport {
171   friend class InstVisitor<Verifier>;
172
173   LLVMContext *Context;
174   DominatorTree DT;
175
176   /// \brief When verifying a basic block, keep track of all of the
177   /// instructions we have seen so far.
178   ///
179   /// This allows us to do efficient dominance checks for the case when an
180   /// instruction has an operand that is an instruction in the same block.
181   SmallPtrSet<Instruction *, 16> InstsInThisBlock;
182
183   /// \brief Keep track of the metadata nodes that have been checked already.
184   SmallPtrSet<const Metadata *, 32> MDNodes;
185
186   /// \brief Track unresolved string-based type references.
187   SmallDenseMap<const MDString *, const MDNode *, 32> UnresolvedTypeRefs;
188
189   /// \brief Whether we've seen a call to @llvm.frameescape in this function
190   /// already.
191   bool SawFrameEscape;
192
193   /// Stores the count of how many objects were passed to llvm.frameescape for a
194   /// given function and the largest index passed to llvm.framerecover.
195   DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo;
196
197 public:
198   explicit Verifier(raw_ostream &OS)
199       : VerifierSupport(OS), Context(nullptr), SawFrameEscape(false) {}
200
201   bool verify(const Function &F) {
202     M = F.getParent();
203     Context = &M->getContext();
204
205     // First ensure the function is well-enough formed to compute dominance
206     // information.
207     if (F.empty()) {
208       OS << "Function '" << F.getName()
209          << "' does not contain an entry block!\n";
210       return false;
211     }
212     for (Function::const_iterator I = F.begin(), E = F.end(); I != E; ++I) {
213       if (I->empty() || !I->back().isTerminator()) {
214         OS << "Basic Block in function '" << F.getName()
215            << "' does not have terminator!\n";
216         I->printAsOperand(OS, true);
217         OS << "\n";
218         return false;
219       }
220     }
221
222     // Now directly compute a dominance tree. We don't rely on the pass
223     // manager to provide this as it isolates us from a potentially
224     // out-of-date dominator tree and makes it significantly more complex to
225     // run this code outside of a pass manager.
226     // FIXME: It's really gross that we have to cast away constness here.
227     DT.recalculate(const_cast<Function &>(F));
228
229     Broken = false;
230     // FIXME: We strip const here because the inst visitor strips const.
231     visit(const_cast<Function &>(F));
232     InstsInThisBlock.clear();
233     SawFrameEscape = false;
234
235     return !Broken;
236   }
237
238   bool verify(const Module &M) {
239     this->M = &M;
240     Context = &M.getContext();
241     Broken = false;
242
243     // Scan through, checking all of the external function's linkage now...
244     for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
245       visitGlobalValue(*I);
246
247       // Check to make sure function prototypes are okay.
248       if (I->isDeclaration())
249         visitFunction(*I);
250     }
251
252     // Now that we've visited every function, verify that we never asked to
253     // recover a frame index that wasn't escaped.
254     verifyFrameRecoverIndices();
255
256     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
257          I != E; ++I)
258       visitGlobalVariable(*I);
259
260     for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
261          I != E; ++I)
262       visitGlobalAlias(*I);
263
264     for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
265                                                E = M.named_metadata_end();
266          I != E; ++I)
267       visitNamedMDNode(*I);
268
269     for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
270       visitComdat(SMEC.getValue());
271
272     visitModuleFlags(M);
273     visitModuleIdents(M);
274
275     // Verify type referneces last.
276     verifyTypeRefs();
277
278     return !Broken;
279   }
280
281 private:
282   // Verification methods...
283   void visitGlobalValue(const GlobalValue &GV);
284   void visitGlobalVariable(const GlobalVariable &GV);
285   void visitGlobalAlias(const GlobalAlias &GA);
286   void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
287   void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
288                            const GlobalAlias &A, const Constant &C);
289   void visitNamedMDNode(const NamedMDNode &NMD);
290   void visitMDNode(const MDNode &MD);
291   void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
292   void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
293   void visitComdat(const Comdat &C);
294   void visitModuleIdents(const Module &M);
295   void visitModuleFlags(const Module &M);
296   void visitModuleFlag(const MDNode *Op,
297                        DenseMap<const MDString *, const MDNode *> &SeenIDs,
298                        SmallVectorImpl<const MDNode *> &Requirements);
299   void visitFunction(const Function &F);
300   void visitBasicBlock(BasicBlock &BB);
301   void visitRangeMetadata(Instruction& I, MDNode* Range, Type* Ty);
302
303   template <class Ty> bool isValidMetadataArray(const MDTuple &N);
304 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
305 #include "llvm/IR/Metadata.def"
306   void visitDIScope(const DIScope &N);
307   void visitDIDerivedTypeBase(const DIDerivedTypeBase &N);
308   void visitDIVariable(const DIVariable &N);
309   void visitDILexicalBlockBase(const DILexicalBlockBase &N);
310   void visitDITemplateParameter(const DITemplateParameter &N);
311
312   void visitTemplateParams(const MDNode &N, const Metadata &RawParams);
313
314   /// \brief Check for a valid string-based type reference.
315   ///
316   /// Checks if \c MD is a string-based type reference.  If it is, keeps track
317   /// of it (and its user, \c N) for error messages later.
318   bool isValidUUID(const MDNode &N, const Metadata *MD);
319
320   /// \brief Check for a valid type reference.
321   ///
322   /// Checks for subclasses of \a DIType, or \a isValidUUID().
323   bool isTypeRef(const MDNode &N, const Metadata *MD);
324
325   /// \brief Check for a valid scope reference.
326   ///
327   /// Checks for subclasses of \a DIScope, or \a isValidUUID().
328   bool isScopeRef(const MDNode &N, const Metadata *MD);
329
330   /// \brief Check for a valid debug info reference.
331   ///
332   /// Checks for subclasses of \a DINode, or \a isValidUUID().
333   bool isDIRef(const MDNode &N, const Metadata *MD);
334
335   // InstVisitor overrides...
336   using InstVisitor<Verifier>::visit;
337   void visit(Instruction &I);
338
339   void visitTruncInst(TruncInst &I);
340   void visitZExtInst(ZExtInst &I);
341   void visitSExtInst(SExtInst &I);
342   void visitFPTruncInst(FPTruncInst &I);
343   void visitFPExtInst(FPExtInst &I);
344   void visitFPToUIInst(FPToUIInst &I);
345   void visitFPToSIInst(FPToSIInst &I);
346   void visitUIToFPInst(UIToFPInst &I);
347   void visitSIToFPInst(SIToFPInst &I);
348   void visitIntToPtrInst(IntToPtrInst &I);
349   void visitPtrToIntInst(PtrToIntInst &I);
350   void visitBitCastInst(BitCastInst &I);
351   void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
352   void visitPHINode(PHINode &PN);
353   void visitBinaryOperator(BinaryOperator &B);
354   void visitICmpInst(ICmpInst &IC);
355   void visitFCmpInst(FCmpInst &FC);
356   void visitExtractElementInst(ExtractElementInst &EI);
357   void visitInsertElementInst(InsertElementInst &EI);
358   void visitShuffleVectorInst(ShuffleVectorInst &EI);
359   void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
360   void visitCallInst(CallInst &CI);
361   void visitInvokeInst(InvokeInst &II);
362   void visitGetElementPtrInst(GetElementPtrInst &GEP);
363   void visitLoadInst(LoadInst &LI);
364   void visitStoreInst(StoreInst &SI);
365   void verifyDominatesUse(Instruction &I, unsigned i);
366   void visitInstruction(Instruction &I);
367   void visitTerminatorInst(TerminatorInst &I);
368   void visitBranchInst(BranchInst &BI);
369   void visitReturnInst(ReturnInst &RI);
370   void visitSwitchInst(SwitchInst &SI);
371   void visitIndirectBrInst(IndirectBrInst &BI);
372   void visitSelectInst(SelectInst &SI);
373   void visitUserOp1(Instruction &I);
374   void visitUserOp2(Instruction &I) { visitUserOp1(I); }
375   void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallSite CS);
376   template <class DbgIntrinsicTy>
377   void visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII);
378   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
379   void visitAtomicRMWInst(AtomicRMWInst &RMWI);
380   void visitFenceInst(FenceInst &FI);
381   void visitAllocaInst(AllocaInst &AI);
382   void visitExtractValueInst(ExtractValueInst &EVI);
383   void visitInsertValueInst(InsertValueInst &IVI);
384   void visitLandingPadInst(LandingPadInst &LPI);
385
386   void VerifyCallSite(CallSite CS);
387   void verifyMustTailCall(CallInst &CI);
388   bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT,
389                         unsigned ArgNo, std::string &Suffix);
390   bool VerifyIntrinsicType(Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
391                            SmallVectorImpl<Type *> &ArgTys);
392   bool VerifyIntrinsicIsVarArg(bool isVarArg,
393                                ArrayRef<Intrinsic::IITDescriptor> &Infos);
394   bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params);
395   void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx, bool isFunction,
396                             const Value *V);
397   void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
398                             bool isReturnValue, const Value *V);
399   void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
400                            const Value *V);
401   void VerifyFunctionMetadata(
402       const SmallVector<std::pair<unsigned, MDNode *>, 4> MDs);
403
404   void VerifyConstantExprBitcastType(const ConstantExpr *CE);
405   void VerifyStatepoint(ImmutableCallSite CS);
406   void verifyFrameRecoverIndices();
407
408   // Module-level debug info verification...
409   void verifyTypeRefs();
410   template <class MapTy>
411   void verifyBitPieceExpression(const DbgInfoIntrinsic &I,
412                                 const MapTy &TypeRefs);
413   void visitUnresolvedTypeRef(const MDString *S, const MDNode *N);
414 };
415 } // End anonymous namespace
416
417 // Assert - We know that cond should be true, if not print an error message.
418 #define Assert(C, ...) \
419   do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (0)
420
421 void Verifier::visit(Instruction &I) {
422   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
423     Assert(I.getOperand(i) != nullptr, "Operand is null", &I);
424   InstVisitor<Verifier>::visit(I);
425 }
426
427
428 void Verifier::visitGlobalValue(const GlobalValue &GV) {
429   Assert(!GV.isDeclaration() || GV.hasExternalLinkage() ||
430              GV.hasExternalWeakLinkage(),
431          "Global is external, but doesn't have external or weak linkage!", &GV);
432
433   Assert(GV.getAlignment() <= Value::MaximumAlignment,
434          "huge alignment values are unsupported", &GV);
435   Assert(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
436          "Only global variables can have appending linkage!", &GV);
437
438   if (GV.hasAppendingLinkage()) {
439     const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
440     Assert(GVar && GVar->getValueType()->isArrayTy(),
441            "Only global arrays can have appending linkage!", GVar);
442   }
443 }
444
445 void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
446   if (GV.hasInitializer()) {
447     Assert(GV.getInitializer()->getType() == GV.getType()->getElementType(),
448            "Global variable initializer type does not match global "
449            "variable type!",
450            &GV);
451
452     // If the global has common linkage, it must have a zero initializer and
453     // cannot be constant.
454     if (GV.hasCommonLinkage()) {
455       Assert(GV.getInitializer()->isNullValue(),
456              "'common' global must have a zero initializer!", &GV);
457       Assert(!GV.isConstant(), "'common' global may not be marked constant!",
458              &GV);
459       Assert(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
460     }
461   } else {
462     Assert(GV.hasExternalLinkage() || GV.hasExternalWeakLinkage(),
463            "invalid linkage type for global declaration", &GV);
464   }
465
466   if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
467                        GV.getName() == "llvm.global_dtors")) {
468     Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
469            "invalid linkage for intrinsic global variable", &GV);
470     // Don't worry about emitting an error for it not being an array,
471     // visitGlobalValue will complain on appending non-array.
472     if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getValueType())) {
473       StructType *STy = dyn_cast<StructType>(ATy->getElementType());
474       PointerType *FuncPtrTy =
475           FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
476       // FIXME: Reject the 2-field form in LLVM 4.0.
477       Assert(STy &&
478                  (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
479                  STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
480                  STy->getTypeAtIndex(1) == FuncPtrTy,
481              "wrong type for intrinsic global variable", &GV);
482       if (STy->getNumElements() == 3) {
483         Type *ETy = STy->getTypeAtIndex(2);
484         Assert(ETy->isPointerTy() &&
485                    cast<PointerType>(ETy)->getElementType()->isIntegerTy(8),
486                "wrong type for intrinsic global variable", &GV);
487       }
488     }
489   }
490
491   if (GV.hasName() && (GV.getName() == "llvm.used" ||
492                        GV.getName() == "llvm.compiler.used")) {
493     Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
494            "invalid linkage for intrinsic global variable", &GV);
495     Type *GVType = GV.getValueType();
496     if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
497       PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
498       Assert(PTy, "wrong type for intrinsic global variable", &GV);
499       if (GV.hasInitializer()) {
500         const Constant *Init = GV.getInitializer();
501         const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
502         Assert(InitArray, "wrong initalizer for intrinsic global variable",
503                Init);
504         for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) {
505           Value *V = Init->getOperand(i)->stripPointerCastsNoFollowAliases();
506           Assert(isa<GlobalVariable>(V) || isa<Function>(V) ||
507                      isa<GlobalAlias>(V),
508                  "invalid llvm.used member", V);
509           Assert(V->hasName(), "members of llvm.used must be named", V);
510         }
511       }
512     }
513   }
514
515   Assert(!GV.hasDLLImportStorageClass() ||
516              (GV.isDeclaration() && GV.hasExternalLinkage()) ||
517              GV.hasAvailableExternallyLinkage(),
518          "Global is marked as dllimport, but not external", &GV);
519
520   if (!GV.hasInitializer()) {
521     visitGlobalValue(GV);
522     return;
523   }
524
525   // Walk any aggregate initializers looking for bitcasts between address spaces
526   SmallPtrSet<const Value *, 4> Visited;
527   SmallVector<const Value *, 4> WorkStack;
528   WorkStack.push_back(cast<Value>(GV.getInitializer()));
529
530   while (!WorkStack.empty()) {
531     const Value *V = WorkStack.pop_back_val();
532     if (!Visited.insert(V).second)
533       continue;
534
535     if (const User *U = dyn_cast<User>(V)) {
536       WorkStack.append(U->op_begin(), U->op_end());
537     }
538
539     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
540       VerifyConstantExprBitcastType(CE);
541       if (Broken)
542         return;
543     }
544   }
545
546   visitGlobalValue(GV);
547 }
548
549 void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
550   SmallPtrSet<const GlobalAlias*, 4> Visited;
551   Visited.insert(&GA);
552   visitAliaseeSubExpr(Visited, GA, C);
553 }
554
555 void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
556                                    const GlobalAlias &GA, const Constant &C) {
557   if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
558     Assert(!GV->isDeclaration(), "Alias must point to a definition", &GA);
559
560     if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
561       Assert(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
562
563       Assert(!GA2->mayBeOverridden(), "Alias cannot point to a weak alias",
564              &GA);
565     } else {
566       // Only continue verifying subexpressions of GlobalAliases.
567       // Do not recurse into global initializers.
568       return;
569     }
570   }
571
572   if (const auto *CE = dyn_cast<ConstantExpr>(&C))
573     VerifyConstantExprBitcastType(CE);
574
575   for (const Use &U : C.operands()) {
576     Value *V = &*U;
577     if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
578       visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
579     else if (const auto *C2 = dyn_cast<Constant>(V))
580       visitAliaseeSubExpr(Visited, GA, *C2);
581   }
582 }
583
584 void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
585   Assert(GlobalAlias::isValidLinkage(GA.getLinkage()),
586          "Alias should have private, internal, linkonce, weak, linkonce_odr, "
587          "weak_odr, or external linkage!",
588          &GA);
589   const Constant *Aliasee = GA.getAliasee();
590   Assert(Aliasee, "Aliasee cannot be NULL!", &GA);
591   Assert(GA.getType() == Aliasee->getType(),
592          "Alias and aliasee types should match!", &GA);
593
594   Assert(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
595          "Aliasee should be either GlobalValue or ConstantExpr", &GA);
596
597   visitAliaseeSubExpr(GA, *Aliasee);
598
599   visitGlobalValue(GA);
600 }
601
602 void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
603   for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
604     MDNode *MD = NMD.getOperand(i);
605
606     if (NMD.getName() == "llvm.dbg.cu") {
607       Assert(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD);
608     }
609
610     if (!MD)
611       continue;
612
613     visitMDNode(*MD);
614   }
615 }
616
617 void Verifier::visitMDNode(const MDNode &MD) {
618   // Only visit each node once.  Metadata can be mutually recursive, so this
619   // avoids infinite recursion here, as well as being an optimization.
620   if (!MDNodes.insert(&MD).second)
621     return;
622
623   switch (MD.getMetadataID()) {
624   default:
625     llvm_unreachable("Invalid MDNode subclass");
626   case Metadata::MDTupleKind:
627     break;
628 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
629   case Metadata::CLASS##Kind:                                                  \
630     visit##CLASS(cast<CLASS>(MD));                                             \
631     break;
632 #include "llvm/IR/Metadata.def"
633   }
634
635   for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
636     Metadata *Op = MD.getOperand(i);
637     if (!Op)
638       continue;
639     Assert(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
640            &MD, Op);
641     if (auto *N = dyn_cast<MDNode>(Op)) {
642       visitMDNode(*N);
643       continue;
644     }
645     if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
646       visitValueAsMetadata(*V, nullptr);
647       continue;
648     }
649   }
650
651   // Check these last, so we diagnose problems in operands first.
652   Assert(!MD.isTemporary(), "Expected no forward declarations!", &MD);
653   Assert(MD.isResolved(), "All nodes should be resolved!", &MD);
654 }
655
656 void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
657   Assert(MD.getValue(), "Expected valid value", &MD);
658   Assert(!MD.getValue()->getType()->isMetadataTy(),
659          "Unexpected metadata round-trip through values", &MD, MD.getValue());
660
661   auto *L = dyn_cast<LocalAsMetadata>(&MD);
662   if (!L)
663     return;
664
665   Assert(F, "function-local metadata used outside a function", L);
666
667   // If this was an instruction, bb, or argument, verify that it is in the
668   // function that we expect.
669   Function *ActualF = nullptr;
670   if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
671     Assert(I->getParent(), "function-local metadata not in basic block", L, I);
672     ActualF = I->getParent()->getParent();
673   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
674     ActualF = BB->getParent();
675   else if (Argument *A = dyn_cast<Argument>(L->getValue()))
676     ActualF = A->getParent();
677   assert(ActualF && "Unimplemented function local metadata case!");
678
679   Assert(ActualF == F, "function-local metadata used in wrong function", L);
680 }
681
682 void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
683   Metadata *MD = MDV.getMetadata();
684   if (auto *N = dyn_cast<MDNode>(MD)) {
685     visitMDNode(*N);
686     return;
687   }
688
689   // Only visit each node once.  Metadata can be mutually recursive, so this
690   // avoids infinite recursion here, as well as being an optimization.
691   if (!MDNodes.insert(MD).second)
692     return;
693
694   if (auto *V = dyn_cast<ValueAsMetadata>(MD))
695     visitValueAsMetadata(*V, F);
696 }
697
698 bool Verifier::isValidUUID(const MDNode &N, const Metadata *MD) {
699   auto *S = dyn_cast<MDString>(MD);
700   if (!S)
701     return false;
702   if (S->getString().empty())
703     return false;
704
705   // Keep track of names of types referenced via UUID so we can check that they
706   // actually exist.
707   UnresolvedTypeRefs.insert(std::make_pair(S, &N));
708   return true;
709 }
710
711 /// \brief Check if a value can be a reference to a type.
712 bool Verifier::isTypeRef(const MDNode &N, const Metadata *MD) {
713   return !MD || isValidUUID(N, MD) || isa<DIType>(MD);
714 }
715
716 /// \brief Check if a value can be a ScopeRef.
717 bool Verifier::isScopeRef(const MDNode &N, const Metadata *MD) {
718   return !MD || isValidUUID(N, MD) || isa<DIScope>(MD);
719 }
720
721 /// \brief Check if a value can be a debug info ref.
722 bool Verifier::isDIRef(const MDNode &N, const Metadata *MD) {
723   return !MD || isValidUUID(N, MD) || isa<DINode>(MD);
724 }
725
726 template <class Ty>
727 bool isValidMetadataArrayImpl(const MDTuple &N, bool AllowNull) {
728   for (Metadata *MD : N.operands()) {
729     if (MD) {
730       if (!isa<Ty>(MD))
731         return false;
732     } else {
733       if (!AllowNull)
734         return false;
735     }
736   }
737   return true;
738 }
739
740 template <class Ty>
741 bool isValidMetadataArray(const MDTuple &N) {
742   return isValidMetadataArrayImpl<Ty>(N, /* AllowNull */ false);
743 }
744
745 template <class Ty>
746 bool isValidMetadataNullArray(const MDTuple &N) {
747   return isValidMetadataArrayImpl<Ty>(N, /* AllowNull */ true);
748 }
749
750 void Verifier::visitDILocation(const DILocation &N) {
751   Assert(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
752          "location requires a valid scope", &N, N.getRawScope());
753   if (auto *IA = N.getRawInlinedAt())
754     Assert(isa<DILocation>(IA), "inlined-at should be a location", &N, IA);
755 }
756
757 void Verifier::visitGenericDINode(const GenericDINode &N) {
758   Assert(N.getTag(), "invalid tag", &N);
759 }
760
761 void Verifier::visitDIScope(const DIScope &N) {
762   if (auto *F = N.getRawFile())
763     Assert(isa<DIFile>(F), "invalid file", &N, F);
764 }
765
766 void Verifier::visitDISubrange(const DISubrange &N) {
767   Assert(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
768   Assert(N.getCount() >= -1, "invalid subrange count", &N);
769 }
770
771 void Verifier::visitDIEnumerator(const DIEnumerator &N) {
772   Assert(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
773 }
774
775 void Verifier::visitDIBasicType(const DIBasicType &N) {
776   Assert(N.getTag() == dwarf::DW_TAG_base_type ||
777              N.getTag() == dwarf::DW_TAG_unspecified_type,
778          "invalid tag", &N);
779 }
780
781 void Verifier::visitDIDerivedTypeBase(const DIDerivedTypeBase &N) {
782   // Common scope checks.
783   visitDIScope(N);
784
785   Assert(isScopeRef(N, N.getScope()), "invalid scope", &N, N.getScope());
786   Assert(isTypeRef(N, N.getBaseType()), "invalid base type", &N,
787          N.getBaseType());
788
789   // FIXME: Sink this into the subclass verifies.
790   if (!N.getFile() || N.getFile()->getFilename().empty()) {
791     // Check whether the filename is allowed to be empty.
792     uint16_t Tag = N.getTag();
793     Assert(
794         Tag == dwarf::DW_TAG_const_type || Tag == dwarf::DW_TAG_volatile_type ||
795             Tag == dwarf::DW_TAG_pointer_type ||
796             Tag == dwarf::DW_TAG_ptr_to_member_type ||
797             Tag == dwarf::DW_TAG_reference_type ||
798             Tag == dwarf::DW_TAG_rvalue_reference_type ||
799             Tag == dwarf::DW_TAG_restrict_type ||
800             Tag == dwarf::DW_TAG_array_type ||
801             Tag == dwarf::DW_TAG_enumeration_type ||
802             Tag == dwarf::DW_TAG_subroutine_type ||
803             Tag == dwarf::DW_TAG_inheritance || Tag == dwarf::DW_TAG_friend ||
804             Tag == dwarf::DW_TAG_structure_type ||
805             Tag == dwarf::DW_TAG_member || Tag == dwarf::DW_TAG_typedef,
806         "derived/composite type requires a filename", &N, N.getFile());
807   }
808 }
809
810 void Verifier::visitDIDerivedType(const DIDerivedType &N) {
811   // Common derived type checks.
812   visitDIDerivedTypeBase(N);
813
814   Assert(N.getTag() == dwarf::DW_TAG_typedef ||
815              N.getTag() == dwarf::DW_TAG_pointer_type ||
816              N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
817              N.getTag() == dwarf::DW_TAG_reference_type ||
818              N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
819              N.getTag() == dwarf::DW_TAG_const_type ||
820              N.getTag() == dwarf::DW_TAG_volatile_type ||
821              N.getTag() == dwarf::DW_TAG_restrict_type ||
822              N.getTag() == dwarf::DW_TAG_member ||
823              N.getTag() == dwarf::DW_TAG_inheritance ||
824              N.getTag() == dwarf::DW_TAG_friend,
825          "invalid tag", &N);
826   if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
827     Assert(isTypeRef(N, N.getExtraData()), "invalid pointer to member type", &N,
828            N.getExtraData());
829   }
830 }
831
832 static bool hasConflictingReferenceFlags(unsigned Flags) {
833   return (Flags & DINode::FlagLValueReference) &&
834          (Flags & DINode::FlagRValueReference);
835 }
836
837 void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) {
838   auto *Params = dyn_cast<MDTuple>(&RawParams);
839   Assert(Params, "invalid template params", &N, &RawParams);
840   for (Metadata *Op : Params->operands()) {
841     Assert(Op && isa<DITemplateParameter>(Op), "invalid template parameter", &N,
842            Params, Op);
843   }
844 }
845
846 void Verifier::visitDICompositeType(const DICompositeType &N) {
847   // Common derived type checks.
848   visitDIDerivedTypeBase(N);
849
850   Assert(N.getTag() == dwarf::DW_TAG_array_type ||
851              N.getTag() == dwarf::DW_TAG_structure_type ||
852              N.getTag() == dwarf::DW_TAG_union_type ||
853              N.getTag() == dwarf::DW_TAG_enumeration_type ||
854              N.getTag() == dwarf::DW_TAG_subroutine_type ||
855              N.getTag() == dwarf::DW_TAG_class_type,
856          "invalid tag", &N);
857
858   Assert(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
859          "invalid composite elements", &N, N.getRawElements());
860   Assert(isTypeRef(N, N.getRawVTableHolder()), "invalid vtable holder", &N,
861          N.getRawVTableHolder());
862   Assert(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
863          "invalid composite elements", &N, N.getRawElements());
864   Assert(!hasConflictingReferenceFlags(N.getFlags()), "invalid reference flags",
865          &N);
866   if (auto *Params = N.getRawTemplateParams())
867     visitTemplateParams(N, *Params);
868 }
869
870 void Verifier::visitDISubroutineType(const DISubroutineType &N) {
871   Assert(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
872   if (auto *Types = N.getRawTypeArray()) {
873     Assert(isa<MDTuple>(Types), "invalid composite elements", &N, Types);
874     for (Metadata *Ty : N.getTypeArray()->operands()) {
875       Assert(isTypeRef(N, Ty), "invalid subroutine type ref", &N, Types, Ty);
876     }
877   }
878   Assert(!hasConflictingReferenceFlags(N.getFlags()), "invalid reference flags",
879          &N);
880 }
881
882 void Verifier::visitDIFile(const DIFile &N) {
883   Assert(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
884 }
885
886 void Verifier::visitDICompileUnit(const DICompileUnit &N) {
887   Assert(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
888
889   // Don't bother verifying the compilation directory or producer string
890   // as those could be empty.
891   Assert(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N,
892          N.getRawFile());
893   Assert(!N.getFile()->getFilename().empty(), "invalid filename", &N,
894          N.getFile());
895
896   if (auto *Array = N.getRawEnumTypes()) {
897     Assert(isa<MDTuple>(Array), "invalid enum list", &N, Array);
898     for (Metadata *Op : N.getEnumTypes()->operands()) {
899       auto *Enum = dyn_cast_or_null<DICompositeType>(Op);
900       Assert(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
901              "invalid enum type", &N, N.getEnumTypes(), Op);
902     }
903   }
904   if (auto *Array = N.getRawRetainedTypes()) {
905     Assert(isa<MDTuple>(Array), "invalid retained type list", &N, Array);
906     for (Metadata *Op : N.getRetainedTypes()->operands()) {
907       Assert(Op && isa<DIType>(Op), "invalid retained type", &N, Op);
908     }
909   }
910   if (auto *Array = N.getRawSubprograms()) {
911     Assert(isa<MDTuple>(Array), "invalid subprogram list", &N, Array);
912     for (Metadata *Op : N.getSubprograms()->operands()) {
913       Assert(Op && isa<DISubprogram>(Op), "invalid subprogram ref", &N, Op);
914     }
915   }
916   if (auto *Array = N.getRawGlobalVariables()) {
917     Assert(isa<MDTuple>(Array), "invalid global variable list", &N, Array);
918     for (Metadata *Op : N.getGlobalVariables()->operands()) {
919       Assert(Op && isa<DIGlobalVariable>(Op), "invalid global variable ref", &N,
920              Op);
921     }
922   }
923   if (auto *Array = N.getRawImportedEntities()) {
924     Assert(isa<MDTuple>(Array), "invalid imported entity list", &N, Array);
925     for (Metadata *Op : N.getImportedEntities()->operands()) {
926       Assert(Op && isa<DIImportedEntity>(Op), "invalid imported entity ref", &N,
927              Op);
928     }
929   }
930 }
931
932 void Verifier::visitDISubprogram(const DISubprogram &N) {
933   Assert(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
934   Assert(isScopeRef(N, N.getRawScope()), "invalid scope", &N, N.getRawScope());
935   if (auto *T = N.getRawType())
936     Assert(isa<DISubroutineType>(T), "invalid subroutine type", &N, T);
937   Assert(isTypeRef(N, N.getRawContainingType()), "invalid containing type", &N,
938          N.getRawContainingType());
939   if (auto *RawF = N.getRawFunction()) {
940     auto *FMD = dyn_cast<ConstantAsMetadata>(RawF);
941     auto *F = FMD ? FMD->getValue() : nullptr;
942     auto *FT = F ? dyn_cast<PointerType>(F->getType()) : nullptr;
943     Assert(F && FT && isa<FunctionType>(FT->getElementType()),
944            "invalid function", &N, F, FT);
945   }
946   if (auto *Params = N.getRawTemplateParams())
947     visitTemplateParams(N, *Params);
948   if (auto *S = N.getRawDeclaration()) {
949     Assert(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(),
950            "invalid subprogram declaration", &N, S);
951   }
952   if (auto *RawVars = N.getRawVariables()) {
953     auto *Vars = dyn_cast<MDTuple>(RawVars);
954     Assert(Vars, "invalid variable list", &N, RawVars);
955     for (Metadata *Op : Vars->operands()) {
956       Assert(Op && isa<DILocalVariable>(Op), "invalid local variable", &N, Vars,
957              Op);
958     }
959   }
960   Assert(!hasConflictingReferenceFlags(N.getFlags()), "invalid reference flags",
961          &N);
962
963   auto *F = N.getFunction();
964   if (!F)
965     return;
966
967   // Check that all !dbg attachments lead to back to N (or, at least, another
968   // subprogram that describes the same function).
969   //
970   // FIXME: Check this incrementally while visiting !dbg attachments.
971   // FIXME: Only check when N is the canonical subprogram for F.
972   SmallPtrSet<const MDNode *, 32> Seen;
973   for (auto &BB : *F)
974     for (auto &I : BB) {
975       // Be careful about using DILocation here since we might be dealing with
976       // broken code (this is the Verifier after all).
977       DILocation *DL =
978           dyn_cast_or_null<DILocation>(I.getDebugLoc().getAsMDNode());
979       if (!DL)
980         continue;
981       if (!Seen.insert(DL).second)
982         continue;
983
984       DILocalScope *Scope = DL->getInlinedAtScope();
985       if (Scope && !Seen.insert(Scope).second)
986         continue;
987
988       DISubprogram *SP = Scope ? Scope->getSubprogram() : nullptr;
989       if (SP && !Seen.insert(SP).second)
990         continue;
991
992       // FIXME: Once N is canonical, check "SP == &N".
993       Assert(SP->describes(F),
994              "!dbg attachment points at wrong subprogram for function", &N, F,
995              &I, DL, Scope, SP);
996     }
997 }
998
999 void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) {
1000   Assert(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
1001   Assert(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1002          "invalid local scope", &N, N.getRawScope());
1003 }
1004
1005 void Verifier::visitDILexicalBlock(const DILexicalBlock &N) {
1006   visitDILexicalBlockBase(N);
1007
1008   Assert(N.getLine() || !N.getColumn(),
1009          "cannot have column info without line info", &N);
1010 }
1011
1012 void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) {
1013   visitDILexicalBlockBase(N);
1014 }
1015
1016 void Verifier::visitDINamespace(const DINamespace &N) {
1017   Assert(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
1018   if (auto *S = N.getRawScope())
1019     Assert(isa<DIScope>(S), "invalid scope ref", &N, S);
1020 }
1021
1022 void Verifier::visitDITemplateParameter(const DITemplateParameter &N) {
1023   Assert(isTypeRef(N, N.getType()), "invalid type ref", &N, N.getType());
1024 }
1025
1026 void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) {
1027   visitDITemplateParameter(N);
1028
1029   Assert(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
1030          &N);
1031 }
1032
1033 void Verifier::visitDITemplateValueParameter(
1034     const DITemplateValueParameter &N) {
1035   visitDITemplateParameter(N);
1036
1037   Assert(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1038              N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1039              N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1040          "invalid tag", &N);
1041 }
1042
1043 void Verifier::visitDIVariable(const DIVariable &N) {
1044   if (auto *S = N.getRawScope())
1045     Assert(isa<DIScope>(S), "invalid scope", &N, S);
1046   Assert(isTypeRef(N, N.getRawType()), "invalid type ref", &N, N.getRawType());
1047   if (auto *F = N.getRawFile())
1048     Assert(isa<DIFile>(F), "invalid file", &N, F);
1049 }
1050
1051 void Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) {
1052   // Checks common to all variables.
1053   visitDIVariable(N);
1054
1055   Assert(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1056   Assert(!N.getName().empty(), "missing global variable name", &N);
1057   if (auto *V = N.getRawVariable()) {
1058     Assert(isa<ConstantAsMetadata>(V) &&
1059                !isa<Function>(cast<ConstantAsMetadata>(V)->getValue()),
1060            "invalid global varaible ref", &N, V);
1061   }
1062   if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
1063     Assert(isa<DIDerivedType>(Member), "invalid static data member declaration",
1064            &N, Member);
1065   }
1066 }
1067
1068 void Verifier::visitDILocalVariable(const DILocalVariable &N) {
1069   // Checks common to all variables.
1070   visitDIVariable(N);
1071
1072   Assert(N.getTag() == dwarf::DW_TAG_auto_variable ||
1073              N.getTag() == dwarf::DW_TAG_arg_variable,
1074          "invalid tag", &N);
1075   Assert(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1076          "local variable requires a valid scope", &N, N.getRawScope());
1077 }
1078
1079 void Verifier::visitDIExpression(const DIExpression &N) {
1080   Assert(N.isValid(), "invalid expression", &N);
1081 }
1082
1083 void Verifier::visitDIObjCProperty(const DIObjCProperty &N) {
1084   Assert(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
1085   if (auto *T = N.getRawType())
1086     Assert(isTypeRef(N, T), "invalid type ref", &N, T);
1087   if (auto *F = N.getRawFile())
1088     Assert(isa<DIFile>(F), "invalid file", &N, F);
1089 }
1090
1091 void Verifier::visitDIImportedEntity(const DIImportedEntity &N) {
1092   Assert(N.getTag() == dwarf::DW_TAG_imported_module ||
1093              N.getTag() == dwarf::DW_TAG_imported_declaration,
1094          "invalid tag", &N);
1095   if (auto *S = N.getRawScope())
1096     Assert(isa<DIScope>(S), "invalid scope for imported entity", &N, S);
1097   Assert(isDIRef(N, N.getEntity()), "invalid imported entity", &N,
1098          N.getEntity());
1099 }
1100
1101 void Verifier::visitComdat(const Comdat &C) {
1102   // The Module is invalid if the GlobalValue has private linkage.  Entities
1103   // with private linkage don't have entries in the symbol table.
1104   if (const GlobalValue *GV = M->getNamedValue(C.getName()))
1105     Assert(!GV->hasPrivateLinkage(), "comdat global value has private linkage",
1106            GV);
1107 }
1108
1109 void Verifier::visitModuleIdents(const Module &M) {
1110   const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
1111   if (!Idents) 
1112     return;
1113   
1114   // llvm.ident takes a list of metadata entry. Each entry has only one string.
1115   // Scan each llvm.ident entry and make sure that this requirement is met.
1116   for (unsigned i = 0, e = Idents->getNumOperands(); i != e; ++i) {
1117     const MDNode *N = Idents->getOperand(i);
1118     Assert(N->getNumOperands() == 1,
1119            "incorrect number of operands in llvm.ident metadata", N);
1120     Assert(dyn_cast_or_null<MDString>(N->getOperand(0)),
1121            ("invalid value for llvm.ident metadata entry operand"
1122             "(the operand should be a string)"),
1123            N->getOperand(0));
1124   } 
1125 }
1126
1127 void Verifier::visitModuleFlags(const Module &M) {
1128   const NamedMDNode *Flags = M.getModuleFlagsMetadata();
1129   if (!Flags) return;
1130
1131   // Scan each flag, and track the flags and requirements.
1132   DenseMap<const MDString*, const MDNode*> SeenIDs;
1133   SmallVector<const MDNode*, 16> Requirements;
1134   for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) {
1135     visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements);
1136   }
1137
1138   // Validate that the requirements in the module are valid.
1139   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1140     const MDNode *Requirement = Requirements[I];
1141     const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1142     const Metadata *ReqValue = Requirement->getOperand(1);
1143
1144     const MDNode *Op = SeenIDs.lookup(Flag);
1145     if (!Op) {
1146       CheckFailed("invalid requirement on flag, flag is not present in module",
1147                   Flag);
1148       continue;
1149     }
1150
1151     if (Op->getOperand(2) != ReqValue) {
1152       CheckFailed(("invalid requirement on flag, "
1153                    "flag does not have the required value"),
1154                   Flag);
1155       continue;
1156     }
1157   }
1158 }
1159
1160 void
1161 Verifier::visitModuleFlag(const MDNode *Op,
1162                           DenseMap<const MDString *, const MDNode *> &SeenIDs,
1163                           SmallVectorImpl<const MDNode *> &Requirements) {
1164   // Each module flag should have three arguments, the merge behavior (a
1165   // constant int), the flag ID (an MDString), and the value.
1166   Assert(Op->getNumOperands() == 3,
1167          "incorrect number of operands in module flag", Op);
1168   Module::ModFlagBehavior MFB;
1169   if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
1170     Assert(
1171         mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)),
1172         "invalid behavior operand in module flag (expected constant integer)",
1173         Op->getOperand(0));
1174     Assert(false,
1175            "invalid behavior operand in module flag (unexpected constant)",
1176            Op->getOperand(0));
1177   }
1178   MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
1179   Assert(ID, "invalid ID operand in module flag (expected metadata string)",
1180          Op->getOperand(1));
1181
1182   // Sanity check the values for behaviors with additional requirements.
1183   switch (MFB) {
1184   case Module::Error:
1185   case Module::Warning:
1186   case Module::Override:
1187     // These behavior types accept any value.
1188     break;
1189
1190   case Module::Require: {
1191     // The value should itself be an MDNode with two operands, a flag ID (an
1192     // MDString), and a value.
1193     MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
1194     Assert(Value && Value->getNumOperands() == 2,
1195            "invalid value for 'require' module flag (expected metadata pair)",
1196            Op->getOperand(2));
1197     Assert(isa<MDString>(Value->getOperand(0)),
1198            ("invalid value for 'require' module flag "
1199             "(first value operand should be a string)"),
1200            Value->getOperand(0));
1201
1202     // Append it to the list of requirements, to check once all module flags are
1203     // scanned.
1204     Requirements.push_back(Value);
1205     break;
1206   }
1207
1208   case Module::Append:
1209   case Module::AppendUnique: {
1210     // These behavior types require the operand be an MDNode.
1211     Assert(isa<MDNode>(Op->getOperand(2)),
1212            "invalid value for 'append'-type module flag "
1213            "(expected a metadata node)",
1214            Op->getOperand(2));
1215     break;
1216   }
1217   }
1218
1219   // Unless this is a "requires" flag, check the ID is unique.
1220   if (MFB != Module::Require) {
1221     bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
1222     Assert(Inserted,
1223            "module flag identifiers must be unique (or of 'require' type)", ID);
1224   }
1225 }
1226
1227 void Verifier::VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
1228                                     bool isFunction, const Value *V) {
1229   unsigned Slot = ~0U;
1230   for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I)
1231     if (Attrs.getSlotIndex(I) == Idx) {
1232       Slot = I;
1233       break;
1234     }
1235
1236   assert(Slot != ~0U && "Attribute set inconsistency!");
1237
1238   for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot);
1239          I != E; ++I) {
1240     if (I->isStringAttribute())
1241       continue;
1242
1243     if (I->getKindAsEnum() == Attribute::NoReturn ||
1244         I->getKindAsEnum() == Attribute::NoUnwind ||
1245         I->getKindAsEnum() == Attribute::NoInline ||
1246         I->getKindAsEnum() == Attribute::AlwaysInline ||
1247         I->getKindAsEnum() == Attribute::OptimizeForSize ||
1248         I->getKindAsEnum() == Attribute::StackProtect ||
1249         I->getKindAsEnum() == Attribute::StackProtectReq ||
1250         I->getKindAsEnum() == Attribute::StackProtectStrong ||
1251         I->getKindAsEnum() == Attribute::SafeStack ||
1252         I->getKindAsEnum() == Attribute::NoRedZone ||
1253         I->getKindAsEnum() == Attribute::NoImplicitFloat ||
1254         I->getKindAsEnum() == Attribute::Naked ||
1255         I->getKindAsEnum() == Attribute::InlineHint ||
1256         I->getKindAsEnum() == Attribute::StackAlignment ||
1257         I->getKindAsEnum() == Attribute::UWTable ||
1258         I->getKindAsEnum() == Attribute::NonLazyBind ||
1259         I->getKindAsEnum() == Attribute::ReturnsTwice ||
1260         I->getKindAsEnum() == Attribute::SanitizeAddress ||
1261         I->getKindAsEnum() == Attribute::SanitizeThread ||
1262         I->getKindAsEnum() == Attribute::SanitizeMemory ||
1263         I->getKindAsEnum() == Attribute::MinSize ||
1264         I->getKindAsEnum() == Attribute::NoDuplicate ||
1265         I->getKindAsEnum() == Attribute::Builtin ||
1266         I->getKindAsEnum() == Attribute::NoBuiltin ||
1267         I->getKindAsEnum() == Attribute::Cold ||
1268         I->getKindAsEnum() == Attribute::OptimizeNone ||
1269         I->getKindAsEnum() == Attribute::JumpTable ||
1270         I->getKindAsEnum() == Attribute::Convergent) {
1271       if (!isFunction) {
1272         CheckFailed("Attribute '" + I->getAsString() +
1273                     "' only applies to functions!", V);
1274         return;
1275       }
1276     } else if (I->getKindAsEnum() == Attribute::ReadOnly ||
1277                I->getKindAsEnum() == Attribute::ReadNone) {
1278       if (Idx == 0) {
1279         CheckFailed("Attribute '" + I->getAsString() +
1280                     "' does not apply to function returns");
1281         return;
1282       }
1283     } else if (isFunction) {
1284       CheckFailed("Attribute '" + I->getAsString() +
1285                   "' does not apply to functions!", V);
1286       return;
1287     }
1288   }
1289 }
1290
1291 // VerifyParameterAttrs - Check the given attributes for an argument or return
1292 // value of the specified type.  The value V is printed in error messages.
1293 void Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
1294                                     bool isReturnValue, const Value *V) {
1295   if (!Attrs.hasAttributes(Idx))
1296     return;
1297
1298   VerifyAttributeTypes(Attrs, Idx, false, V);
1299
1300   if (isReturnValue)
1301     Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
1302                !Attrs.hasAttribute(Idx, Attribute::Nest) &&
1303                !Attrs.hasAttribute(Idx, Attribute::StructRet) &&
1304                !Attrs.hasAttribute(Idx, Attribute::NoCapture) &&
1305                !Attrs.hasAttribute(Idx, Attribute::Returned) &&
1306                !Attrs.hasAttribute(Idx, Attribute::InAlloca),
1307            "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', and "
1308            "'returned' do not apply to return values!",
1309            V);
1310
1311   // Check for mutually incompatible attributes.  Only inreg is compatible with
1312   // sret.
1313   unsigned AttrCount = 0;
1314   AttrCount += Attrs.hasAttribute(Idx, Attribute::ByVal);
1315   AttrCount += Attrs.hasAttribute(Idx, Attribute::InAlloca);
1316   AttrCount += Attrs.hasAttribute(Idx, Attribute::StructRet) ||
1317                Attrs.hasAttribute(Idx, Attribute::InReg);
1318   AttrCount += Attrs.hasAttribute(Idx, Attribute::Nest);
1319   Assert(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', "
1320                          "and 'sret' are incompatible!",
1321          V);
1322
1323   Assert(!(Attrs.hasAttribute(Idx, Attribute::InAlloca) &&
1324            Attrs.hasAttribute(Idx, Attribute::ReadOnly)),
1325          "Attributes "
1326          "'inalloca and readonly' are incompatible!",
1327          V);
1328
1329   Assert(!(Attrs.hasAttribute(Idx, Attribute::StructRet) &&
1330            Attrs.hasAttribute(Idx, Attribute::Returned)),
1331          "Attributes "
1332          "'sret and returned' are incompatible!",
1333          V);
1334
1335   Assert(!(Attrs.hasAttribute(Idx, Attribute::ZExt) &&
1336            Attrs.hasAttribute(Idx, Attribute::SExt)),
1337          "Attributes "
1338          "'zeroext and signext' are incompatible!",
1339          V);
1340
1341   Assert(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
1342            Attrs.hasAttribute(Idx, Attribute::ReadOnly)),
1343          "Attributes "
1344          "'readnone and readonly' are incompatible!",
1345          V);
1346
1347   Assert(!(Attrs.hasAttribute(Idx, Attribute::NoInline) &&
1348            Attrs.hasAttribute(Idx, Attribute::AlwaysInline)),
1349          "Attributes "
1350          "'noinline and alwaysinline' are incompatible!",
1351          V);
1352
1353   Assert(!AttrBuilder(Attrs, Idx)
1354               .overlaps(AttributeFuncs::typeIncompatible(Ty)),
1355          "Wrong types for attribute: " +
1356          AttributeSet::get(*Context, Idx,
1357                         AttributeFuncs::typeIncompatible(Ty)).getAsString(Idx),
1358          V);
1359
1360   if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1361     SmallPtrSet<const Type*, 4> Visited;
1362     if (!PTy->getElementType()->isSized(&Visited)) {
1363       Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
1364                  !Attrs.hasAttribute(Idx, Attribute::InAlloca),
1365              "Attributes 'byval' and 'inalloca' do not support unsized types!",
1366              V);
1367     }
1368   } else {
1369     Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal),
1370            "Attribute 'byval' only applies to parameters with pointer type!",
1371            V);
1372   }
1373 }
1374
1375 // VerifyFunctionAttrs - Check parameter attributes against a function type.
1376 // The value V is printed in error messages.
1377 void Verifier::VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
1378                                    const Value *V) {
1379   if (Attrs.isEmpty())
1380     return;
1381
1382   bool SawNest = false;
1383   bool SawReturned = false;
1384   bool SawSRet = false;
1385
1386   for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
1387     unsigned Idx = Attrs.getSlotIndex(i);
1388
1389     Type *Ty;
1390     if (Idx == 0)
1391       Ty = FT->getReturnType();
1392     else if (Idx-1 < FT->getNumParams())
1393       Ty = FT->getParamType(Idx-1);
1394     else
1395       break;  // VarArgs attributes, verified elsewhere.
1396
1397     VerifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V);
1398
1399     if (Idx == 0)
1400       continue;
1401
1402     if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
1403       Assert(!SawNest, "More than one parameter has attribute nest!", V);
1404       SawNest = true;
1405     }
1406
1407     if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
1408       Assert(!SawReturned, "More than one parameter has attribute returned!",
1409              V);
1410       Assert(Ty->canLosslesslyBitCastTo(FT->getReturnType()),
1411              "Incompatible "
1412              "argument and return types for 'returned' attribute",
1413              V);
1414       SawReturned = true;
1415     }
1416
1417     if (Attrs.hasAttribute(Idx, Attribute::StructRet)) {
1418       Assert(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
1419       Assert(Idx == 1 || Idx == 2,
1420              "Attribute 'sret' is not on first or second parameter!", V);
1421       SawSRet = true;
1422     }
1423
1424     if (Attrs.hasAttribute(Idx, Attribute::InAlloca)) {
1425       Assert(Idx == FT->getNumParams(), "inalloca isn't on the last parameter!",
1426              V);
1427     }
1428   }
1429
1430   if (!Attrs.hasAttributes(AttributeSet::FunctionIndex))
1431     return;
1432
1433   VerifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V);
1434
1435   Assert(
1436       !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone) &&
1437         Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly)),
1438       "Attributes 'readnone and readonly' are incompatible!", V);
1439
1440   Assert(
1441       !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline) &&
1442         Attrs.hasAttribute(AttributeSet::FunctionIndex,
1443                            Attribute::AlwaysInline)),
1444       "Attributes 'noinline and alwaysinline' are incompatible!", V);
1445
1446   if (Attrs.hasAttribute(AttributeSet::FunctionIndex, 
1447                          Attribute::OptimizeNone)) {
1448     Assert(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline),
1449            "Attribute 'optnone' requires 'noinline'!", V);
1450
1451     Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
1452                                Attribute::OptimizeForSize),
1453            "Attributes 'optsize and optnone' are incompatible!", V);
1454
1455     Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize),
1456            "Attributes 'minsize and optnone' are incompatible!", V);
1457   }
1458
1459   if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
1460                          Attribute::JumpTable)) {
1461     const GlobalValue *GV = cast<GlobalValue>(V);
1462     Assert(GV->hasUnnamedAddr(),
1463            "Attribute 'jumptable' requires 'unnamed_addr'", V);
1464   }
1465 }
1466
1467 void Verifier::VerifyFunctionMetadata(
1468     const SmallVector<std::pair<unsigned, MDNode *>, 4> MDs) {
1469   if (MDs.empty())
1470     return;
1471
1472   for (unsigned i = 0; i < MDs.size(); i++) {
1473     if (MDs[i].first == LLVMContext::MD_prof) {
1474       MDNode *MD = MDs[i].second;
1475       Assert(MD->getNumOperands() == 2,
1476              "!prof annotations should have exactly 2 operands", MD);
1477
1478       // Check first operand.
1479       Assert(MD->getOperand(0) != nullptr, "first operand should not be null",
1480              MD);
1481       Assert(isa<MDString>(MD->getOperand(0)),
1482              "expected string with name of the !prof annotation", MD);
1483       MDString *MDS = cast<MDString>(MD->getOperand(0));
1484       StringRef ProfName = MDS->getString();
1485       Assert(ProfName.equals("function_entry_count"),
1486              "first operand should be 'function_entry_count'", MD);
1487
1488       // Check second operand.
1489       Assert(MD->getOperand(1) != nullptr, "second operand should not be null",
1490              MD);
1491       Assert(isa<ConstantAsMetadata>(MD->getOperand(1)),
1492              "expected integer argument to function_entry_count", MD);
1493     }
1494   }
1495 }
1496
1497 void Verifier::VerifyConstantExprBitcastType(const ConstantExpr *CE) {
1498   if (CE->getOpcode() != Instruction::BitCast)
1499     return;
1500
1501   Assert(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
1502                                CE->getType()),
1503          "Invalid bitcast", CE);
1504 }
1505
1506 bool Verifier::VerifyAttributeCount(AttributeSet Attrs, unsigned Params) {
1507   if (Attrs.getNumSlots() == 0)
1508     return true;
1509
1510   unsigned LastSlot = Attrs.getNumSlots() - 1;
1511   unsigned LastIndex = Attrs.getSlotIndex(LastSlot);
1512   if (LastIndex <= Params
1513       || (LastIndex == AttributeSet::FunctionIndex
1514           && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params)))
1515     return true;
1516
1517   return false;
1518 }
1519
1520 /// \brief Verify that statepoint intrinsic is well formed.
1521 void Verifier::VerifyStatepoint(ImmutableCallSite CS) {
1522   assert(CS.getCalledFunction() &&
1523          CS.getCalledFunction()->getIntrinsicID() ==
1524            Intrinsic::experimental_gc_statepoint);
1525
1526   const Instruction &CI = *CS.getInstruction();
1527
1528   Assert(!CS.doesNotAccessMemory() && !CS.onlyReadsMemory(),
1529          "gc.statepoint must read and write memory to preserve "
1530          "reordering restrictions required by safepoint semantics",
1531          &CI);
1532
1533   const Value *IDV = CS.getArgument(0);
1534   Assert(isa<ConstantInt>(IDV), "gc.statepoint ID must be a constant integer",
1535          &CI);
1536
1537   const Value *NumPatchBytesV = CS.getArgument(1);
1538   Assert(isa<ConstantInt>(NumPatchBytesV),
1539          "gc.statepoint number of patchable bytes must be a constant integer",
1540          &CI);
1541   const int64_t NumPatchBytes =
1542       cast<ConstantInt>(NumPatchBytesV)->getSExtValue();
1543   assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!");
1544   Assert(NumPatchBytes >= 0, "gc.statepoint number of patchable bytes must be "
1545                              "positive",
1546          &CI);
1547
1548   const Value *Target = CS.getArgument(2);
1549   const PointerType *PT = dyn_cast<PointerType>(Target->getType());
1550   Assert(PT && PT->getElementType()->isFunctionTy(),
1551          "gc.statepoint callee must be of function pointer type", &CI, Target);
1552   FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType());
1553
1554   if (NumPatchBytes)
1555     Assert(isa<ConstantPointerNull>(Target->stripPointerCasts()),
1556            "gc.statepoint must have null as call target if number of patchable "
1557            "bytes is non zero",
1558            &CI);
1559
1560   const Value *NumCallArgsV = CS.getArgument(3);
1561   Assert(isa<ConstantInt>(NumCallArgsV),
1562          "gc.statepoint number of arguments to underlying call "
1563          "must be constant integer",
1564          &CI);
1565   const int NumCallArgs = cast<ConstantInt>(NumCallArgsV)->getZExtValue();
1566   Assert(NumCallArgs >= 0,
1567          "gc.statepoint number of arguments to underlying call "
1568          "must be positive",
1569          &CI);
1570   const int NumParams = (int)TargetFuncType->getNumParams();
1571   if (TargetFuncType->isVarArg()) {
1572     Assert(NumCallArgs >= NumParams,
1573            "gc.statepoint mismatch in number of vararg call args", &CI);
1574
1575     // TODO: Remove this limitation
1576     Assert(TargetFuncType->getReturnType()->isVoidTy(),
1577            "gc.statepoint doesn't support wrapping non-void "
1578            "vararg functions yet",
1579            &CI);
1580   } else
1581     Assert(NumCallArgs == NumParams,
1582            "gc.statepoint mismatch in number of call args", &CI);
1583
1584   const Value *FlagsV = CS.getArgument(4);
1585   Assert(isa<ConstantInt>(FlagsV),
1586          "gc.statepoint flags must be constant integer", &CI);
1587   const uint64_t Flags = cast<ConstantInt>(FlagsV)->getZExtValue();
1588   Assert((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
1589          "unknown flag used in gc.statepoint flags argument", &CI);
1590
1591   // Verify that the types of the call parameter arguments match
1592   // the type of the wrapped callee.
1593   for (int i = 0; i < NumParams; i++) {
1594     Type *ParamType = TargetFuncType->getParamType(i);
1595     Type *ArgType = CS.getArgument(5 + i)->getType();
1596     Assert(ArgType == ParamType,
1597            "gc.statepoint call argument does not match wrapped "
1598            "function type",
1599            &CI);
1600   }
1601
1602   const int EndCallArgsInx = 4 + NumCallArgs;
1603
1604   const Value *NumTransitionArgsV = CS.getArgument(EndCallArgsInx+1);
1605   Assert(isa<ConstantInt>(NumTransitionArgsV),
1606          "gc.statepoint number of transition arguments "
1607          "must be constant integer",
1608          &CI);
1609   const int NumTransitionArgs =
1610       cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
1611   Assert(NumTransitionArgs >= 0,
1612          "gc.statepoint number of transition arguments must be positive", &CI);
1613   const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
1614
1615   const Value *NumDeoptArgsV = CS.getArgument(EndTransitionArgsInx+1);
1616   Assert(isa<ConstantInt>(NumDeoptArgsV),
1617          "gc.statepoint number of deoptimization arguments "
1618          "must be constant integer",
1619          &CI);
1620   const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
1621   Assert(NumDeoptArgs >= 0, "gc.statepoint number of deoptimization arguments "
1622                             "must be positive",
1623          &CI);
1624
1625   const int ExpectedNumArgs =
1626       7 + NumCallArgs + NumTransitionArgs + NumDeoptArgs;
1627   Assert(ExpectedNumArgs <= (int)CS.arg_size(),
1628          "gc.statepoint too few arguments according to length fields", &CI);
1629
1630   // Check that the only uses of this gc.statepoint are gc.result or 
1631   // gc.relocate calls which are tied to this statepoint and thus part
1632   // of the same statepoint sequence
1633   for (const User *U : CI.users()) {
1634     const CallInst *Call = dyn_cast<const CallInst>(U);
1635     Assert(Call, "illegal use of statepoint token", &CI, U);
1636     if (!Call) continue;
1637     Assert(isGCRelocate(Call) || isGCResult(Call),
1638            "gc.result or gc.relocate are the only value uses"
1639            "of a gc.statepoint",
1640            &CI, U);
1641     if (isGCResult(Call)) {
1642       Assert(Call->getArgOperand(0) == &CI,
1643              "gc.result connected to wrong gc.statepoint", &CI, Call);
1644     } else if (isGCRelocate(Call)) {
1645       Assert(Call->getArgOperand(0) == &CI,
1646              "gc.relocate connected to wrong gc.statepoint", &CI, Call);
1647     }
1648   }
1649
1650   // Note: It is legal for a single derived pointer to be listed multiple
1651   // times.  It's non-optimal, but it is legal.  It can also happen after
1652   // insertion if we strip a bitcast away.
1653   // Note: It is really tempting to check that each base is relocated and
1654   // that a derived pointer is never reused as a base pointer.  This turns
1655   // out to be problematic since optimizations run after safepoint insertion
1656   // can recognize equality properties that the insertion logic doesn't know
1657   // about.  See example statepoint.ll in the verifier subdirectory
1658 }
1659
1660 void Verifier::verifyFrameRecoverIndices() {
1661   for (auto &Counts : FrameEscapeInfo) {
1662     Function *F = Counts.first;
1663     unsigned EscapedObjectCount = Counts.second.first;
1664     unsigned MaxRecoveredIndex = Counts.second.second;
1665     Assert(MaxRecoveredIndex <= EscapedObjectCount,
1666            "all indices passed to llvm.framerecover must be less than the "
1667            "number of arguments passed ot llvm.frameescape in the parent "
1668            "function",
1669            F);
1670   }
1671 }
1672
1673 // visitFunction - Verify that a function is ok.
1674 //
1675 void Verifier::visitFunction(const Function &F) {
1676   // Check function arguments.
1677   FunctionType *FT = F.getFunctionType();
1678   unsigned NumArgs = F.arg_size();
1679
1680   Assert(Context == &F.getContext(),
1681          "Function context does not match Module context!", &F);
1682
1683   Assert(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
1684   Assert(FT->getNumParams() == NumArgs,
1685          "# formal arguments must match # of arguments for function type!", &F,
1686          FT);
1687   Assert(F.getReturnType()->isFirstClassType() ||
1688              F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
1689          "Functions cannot return aggregate values!", &F);
1690
1691   Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
1692          "Invalid struct return type!", &F);
1693
1694   AttributeSet Attrs = F.getAttributes();
1695
1696   Assert(VerifyAttributeCount(Attrs, FT->getNumParams()),
1697          "Attribute after last parameter!", &F);
1698
1699   // Check function attributes.
1700   VerifyFunctionAttrs(FT, Attrs, &F);
1701
1702   // On function declarations/definitions, we do not support the builtin
1703   // attribute. We do not check this in VerifyFunctionAttrs since that is
1704   // checking for Attributes that can/can not ever be on functions.
1705   Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::Builtin),
1706          "Attribute 'builtin' can only be applied to a callsite.", &F);
1707
1708   // Check that this function meets the restrictions on this calling convention.
1709   // Sometimes varargs is used for perfectly forwarding thunks, so some of these
1710   // restrictions can be lifted.
1711   switch (F.getCallingConv()) {
1712   default:
1713   case CallingConv::C:
1714     break;
1715   case CallingConv::Fast:
1716   case CallingConv::Cold:
1717   case CallingConv::Intel_OCL_BI:
1718   case CallingConv::PTX_Kernel:
1719   case CallingConv::PTX_Device:
1720     Assert(!F.isVarArg(), "Calling convention does not support varargs or "
1721                           "perfect forwarding!",
1722            &F);
1723     break;
1724   }
1725
1726   bool isLLVMdotName = F.getName().size() >= 5 &&
1727                        F.getName().substr(0, 5) == "llvm.";
1728
1729   // Check that the argument values match the function type for this function...
1730   unsigned i = 0;
1731   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
1732        ++I, ++i) {
1733     Assert(I->getType() == FT->getParamType(i),
1734            "Argument value does not match function argument type!", I,
1735            FT->getParamType(i));
1736     Assert(I->getType()->isFirstClassType(),
1737            "Function arguments must have first-class types!", I);
1738     if (!isLLVMdotName)
1739       Assert(!I->getType()->isMetadataTy(),
1740              "Function takes metadata but isn't an intrinsic", I, &F);
1741   }
1742
1743   // Get the function metadata attachments.
1744   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1745   F.getAllMetadata(MDs);
1746   assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync");
1747   VerifyFunctionMetadata(MDs);
1748
1749   if (F.isMaterializable()) {
1750     // Function has a body somewhere we can't see.
1751     Assert(MDs.empty(), "unmaterialized function cannot have metadata", &F,
1752            MDs.empty() ? nullptr : MDs.front().second);
1753   } else if (F.isDeclaration()) {
1754     Assert(F.hasExternalLinkage() || F.hasExternalWeakLinkage(),
1755            "invalid linkage type for function declaration", &F);
1756     Assert(MDs.empty(), "function without a body cannot have metadata", &F,
1757            MDs.empty() ? nullptr : MDs.front().second);
1758     Assert(!F.hasPersonalityFn(),
1759            "Function declaration shouldn't have a personality routine", &F);
1760   } else {
1761     // Verify that this function (which has a body) is not named "llvm.*".  It
1762     // is not legal to define intrinsics.
1763     Assert(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
1764
1765     // Check the entry node
1766     const BasicBlock *Entry = &F.getEntryBlock();
1767     Assert(pred_empty(Entry),
1768            "Entry block to function must not have predecessors!", Entry);
1769
1770     // The address of the entry block cannot be taken, unless it is dead.
1771     if (Entry->hasAddressTaken()) {
1772       Assert(!BlockAddress::lookup(Entry)->isConstantUsed(),
1773              "blockaddress may not be used with the entry block!", Entry);
1774     }
1775
1776     // Visit metadata attachments.
1777     for (const auto &I : MDs)
1778       visitMDNode(*I.second);
1779   }
1780
1781   // If this function is actually an intrinsic, verify that it is only used in
1782   // direct call/invokes, never having its "address taken".
1783   if (F.getIntrinsicID()) {
1784     const User *U;
1785     if (F.hasAddressTaken(&U))
1786       Assert(0, "Invalid user of intrinsic instruction!", U);
1787   }
1788
1789   Assert(!F.hasDLLImportStorageClass() ||
1790              (F.isDeclaration() && F.hasExternalLinkage()) ||
1791              F.hasAvailableExternallyLinkage(),
1792          "Function is marked as dllimport, but not external.", &F);
1793 }
1794
1795 // verifyBasicBlock - Verify that a basic block is well formed...
1796 //
1797 void Verifier::visitBasicBlock(BasicBlock &BB) {
1798   InstsInThisBlock.clear();
1799
1800   // Ensure that basic blocks have terminators!
1801   Assert(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
1802
1803   // Check constraints that this basic block imposes on all of the PHI nodes in
1804   // it.
1805   if (isa<PHINode>(BB.front())) {
1806     SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
1807     SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
1808     std::sort(Preds.begin(), Preds.end());
1809     PHINode *PN;
1810     for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
1811       // Ensure that PHI nodes have at least one entry!
1812       Assert(PN->getNumIncomingValues() != 0,
1813              "PHI nodes must have at least one entry.  If the block is dead, "
1814              "the PHI should be removed!",
1815              PN);
1816       Assert(PN->getNumIncomingValues() == Preds.size(),
1817              "PHINode should have one entry for each predecessor of its "
1818              "parent basic block!",
1819              PN);
1820
1821       // Get and sort all incoming values in the PHI node...
1822       Values.clear();
1823       Values.reserve(PN->getNumIncomingValues());
1824       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1825         Values.push_back(std::make_pair(PN->getIncomingBlock(i),
1826                                         PN->getIncomingValue(i)));
1827       std::sort(Values.begin(), Values.end());
1828
1829       for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1830         // Check to make sure that if there is more than one entry for a
1831         // particular basic block in this PHI node, that the incoming values are
1832         // all identical.
1833         //
1834         Assert(i == 0 || Values[i].first != Values[i - 1].first ||
1835                    Values[i].second == Values[i - 1].second,
1836                "PHI node has multiple entries for the same basic block with "
1837                "different incoming values!",
1838                PN, Values[i].first, Values[i].second, Values[i - 1].second);
1839
1840         // Check to make sure that the predecessors and PHI node entries are
1841         // matched up.
1842         Assert(Values[i].first == Preds[i],
1843                "PHI node entries do not match predecessors!", PN,
1844                Values[i].first, Preds[i]);
1845       }
1846     }
1847   }
1848
1849   // Check that all instructions have their parent pointers set up correctly.
1850   for (auto &I : BB)
1851   {
1852     Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!");
1853   }
1854 }
1855
1856 void Verifier::visitTerminatorInst(TerminatorInst &I) {
1857   // Ensure that terminators only exist at the end of the basic block.
1858   Assert(&I == I.getParent()->getTerminator(),
1859          "Terminator found in the middle of a basic block!", I.getParent());
1860   visitInstruction(I);
1861 }
1862
1863 void Verifier::visitBranchInst(BranchInst &BI) {
1864   if (BI.isConditional()) {
1865     Assert(BI.getCondition()->getType()->isIntegerTy(1),
1866            "Branch condition is not 'i1' type!", &BI, BI.getCondition());
1867   }
1868   visitTerminatorInst(BI);
1869 }
1870
1871 void Verifier::visitReturnInst(ReturnInst &RI) {
1872   Function *F = RI.getParent()->getParent();
1873   unsigned N = RI.getNumOperands();
1874   if (F->getReturnType()->isVoidTy())
1875     Assert(N == 0,
1876            "Found return instr that returns non-void in Function of void "
1877            "return type!",
1878            &RI, F->getReturnType());
1879   else
1880     Assert(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
1881            "Function return type does not match operand "
1882            "type of return inst!",
1883            &RI, F->getReturnType());
1884
1885   // Check to make sure that the return value has necessary properties for
1886   // terminators...
1887   visitTerminatorInst(RI);
1888 }
1889
1890 void Verifier::visitSwitchInst(SwitchInst &SI) {
1891   // Check to make sure that all of the constants in the switch instruction
1892   // have the same type as the switched-on value.
1893   Type *SwitchTy = SI.getCondition()->getType();
1894   SmallPtrSet<ConstantInt*, 32> Constants;
1895   for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
1896     Assert(i.getCaseValue()->getType() == SwitchTy,
1897            "Switch constants must all be same type as switch value!", &SI);
1898     Assert(Constants.insert(i.getCaseValue()).second,
1899            "Duplicate integer as switch case", &SI, i.getCaseValue());
1900   }
1901
1902   visitTerminatorInst(SI);
1903 }
1904
1905 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
1906   Assert(BI.getAddress()->getType()->isPointerTy(),
1907          "Indirectbr operand must have pointer type!", &BI);
1908   for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
1909     Assert(BI.getDestination(i)->getType()->isLabelTy(),
1910            "Indirectbr destinations must all have pointer type!", &BI);
1911
1912   visitTerminatorInst(BI);
1913 }
1914
1915 void Verifier::visitSelectInst(SelectInst &SI) {
1916   Assert(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
1917                                          SI.getOperand(2)),
1918          "Invalid operands for select instruction!", &SI);
1919
1920   Assert(SI.getTrueValue()->getType() == SI.getType(),
1921          "Select values must have same type as select instruction!", &SI);
1922   visitInstruction(SI);
1923 }
1924
1925 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
1926 /// a pass, if any exist, it's an error.
1927 ///
1928 void Verifier::visitUserOp1(Instruction &I) {
1929   Assert(0, "User-defined operators should not live outside of a pass!", &I);
1930 }
1931
1932 void Verifier::visitTruncInst(TruncInst &I) {
1933   // Get the source and destination types
1934   Type *SrcTy = I.getOperand(0)->getType();
1935   Type *DestTy = I.getType();
1936
1937   // Get the size of the types in bits, we'll need this later
1938   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1939   unsigned DestBitSize = DestTy->getScalarSizeInBits();
1940
1941   Assert(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
1942   Assert(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
1943   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1944          "trunc source and destination must both be a vector or neither", &I);
1945   Assert(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
1946
1947   visitInstruction(I);
1948 }
1949
1950 void Verifier::visitZExtInst(ZExtInst &I) {
1951   // Get the source and destination types
1952   Type *SrcTy = I.getOperand(0)->getType();
1953   Type *DestTy = I.getType();
1954
1955   // Get the size of the types in bits, we'll need this later
1956   Assert(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
1957   Assert(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
1958   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1959          "zext source and destination must both be a vector or neither", &I);
1960   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1961   unsigned DestBitSize = DestTy->getScalarSizeInBits();
1962
1963   Assert(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
1964
1965   visitInstruction(I);
1966 }
1967
1968 void Verifier::visitSExtInst(SExtInst &I) {
1969   // Get the source and destination types
1970   Type *SrcTy = I.getOperand(0)->getType();
1971   Type *DestTy = I.getType();
1972
1973   // Get the size of the types in bits, we'll need this later
1974   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1975   unsigned DestBitSize = DestTy->getScalarSizeInBits();
1976
1977   Assert(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
1978   Assert(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
1979   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1980          "sext source and destination must both be a vector or neither", &I);
1981   Assert(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
1982
1983   visitInstruction(I);
1984 }
1985
1986 void Verifier::visitFPTruncInst(FPTruncInst &I) {
1987   // Get the source and destination types
1988   Type *SrcTy = I.getOperand(0)->getType();
1989   Type *DestTy = I.getType();
1990   // Get the size of the types in bits, we'll need this later
1991   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1992   unsigned DestBitSize = DestTy->getScalarSizeInBits();
1993
1994   Assert(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
1995   Assert(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
1996   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1997          "fptrunc source and destination must both be a vector or neither", &I);
1998   Assert(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
1999
2000   visitInstruction(I);
2001 }
2002
2003 void Verifier::visitFPExtInst(FPExtInst &I) {
2004   // Get the source and destination types
2005   Type *SrcTy = I.getOperand(0)->getType();
2006   Type *DestTy = I.getType();
2007
2008   // Get the size of the types in bits, we'll need this later
2009   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2010   unsigned DestBitSize = DestTy->getScalarSizeInBits();
2011
2012   Assert(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
2013   Assert(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
2014   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2015          "fpext source and destination must both be a vector or neither", &I);
2016   Assert(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
2017
2018   visitInstruction(I);
2019 }
2020
2021 void Verifier::visitUIToFPInst(UIToFPInst &I) {
2022   // Get the source and destination types
2023   Type *SrcTy = I.getOperand(0)->getType();
2024   Type *DestTy = I.getType();
2025
2026   bool SrcVec = SrcTy->isVectorTy();
2027   bool DstVec = DestTy->isVectorTy();
2028
2029   Assert(SrcVec == DstVec,
2030          "UIToFP source and dest must both be vector or scalar", &I);
2031   Assert(SrcTy->isIntOrIntVectorTy(),
2032          "UIToFP source must be integer or integer vector", &I);
2033   Assert(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
2034          &I);
2035
2036   if (SrcVec && DstVec)
2037     Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2038                cast<VectorType>(DestTy)->getNumElements(),
2039            "UIToFP source and dest vector length mismatch", &I);
2040
2041   visitInstruction(I);
2042 }
2043
2044 void Verifier::visitSIToFPInst(SIToFPInst &I) {
2045   // Get the source and destination types
2046   Type *SrcTy = I.getOperand(0)->getType();
2047   Type *DestTy = I.getType();
2048
2049   bool SrcVec = SrcTy->isVectorTy();
2050   bool DstVec = DestTy->isVectorTy();
2051
2052   Assert(SrcVec == DstVec,
2053          "SIToFP source and dest must both be vector or scalar", &I);
2054   Assert(SrcTy->isIntOrIntVectorTy(),
2055          "SIToFP source must be integer or integer vector", &I);
2056   Assert(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
2057          &I);
2058
2059   if (SrcVec && DstVec)
2060     Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2061                cast<VectorType>(DestTy)->getNumElements(),
2062            "SIToFP source and dest vector length mismatch", &I);
2063
2064   visitInstruction(I);
2065 }
2066
2067 void Verifier::visitFPToUIInst(FPToUIInst &I) {
2068   // Get the source and destination types
2069   Type *SrcTy = I.getOperand(0)->getType();
2070   Type *DestTy = I.getType();
2071
2072   bool SrcVec = SrcTy->isVectorTy();
2073   bool DstVec = DestTy->isVectorTy();
2074
2075   Assert(SrcVec == DstVec,
2076          "FPToUI source and dest must both be vector or scalar", &I);
2077   Assert(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
2078          &I);
2079   Assert(DestTy->isIntOrIntVectorTy(),
2080          "FPToUI result must be integer or integer vector", &I);
2081
2082   if (SrcVec && DstVec)
2083     Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2084                cast<VectorType>(DestTy)->getNumElements(),
2085            "FPToUI source and dest vector length mismatch", &I);
2086
2087   visitInstruction(I);
2088 }
2089
2090 void Verifier::visitFPToSIInst(FPToSIInst &I) {
2091   // Get the source and destination types
2092   Type *SrcTy = I.getOperand(0)->getType();
2093   Type *DestTy = I.getType();
2094
2095   bool SrcVec = SrcTy->isVectorTy();
2096   bool DstVec = DestTy->isVectorTy();
2097
2098   Assert(SrcVec == DstVec,
2099          "FPToSI source and dest must both be vector or scalar", &I);
2100   Assert(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector",
2101          &I);
2102   Assert(DestTy->isIntOrIntVectorTy(),
2103          "FPToSI result must be integer or integer vector", &I);
2104
2105   if (SrcVec && DstVec)
2106     Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2107                cast<VectorType>(DestTy)->getNumElements(),
2108            "FPToSI source and dest vector length mismatch", &I);
2109
2110   visitInstruction(I);
2111 }
2112
2113 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
2114   // Get the source and destination types
2115   Type *SrcTy = I.getOperand(0)->getType();
2116   Type *DestTy = I.getType();
2117
2118   Assert(SrcTy->getScalarType()->isPointerTy(),
2119          "PtrToInt source must be pointer", &I);
2120   Assert(DestTy->getScalarType()->isIntegerTy(),
2121          "PtrToInt result must be integral", &I);
2122   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
2123          &I);
2124
2125   if (SrcTy->isVectorTy()) {
2126     VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
2127     VectorType *VDest = dyn_cast<VectorType>(DestTy);
2128     Assert(VSrc->getNumElements() == VDest->getNumElements(),
2129            "PtrToInt Vector width mismatch", &I);
2130   }
2131
2132   visitInstruction(I);
2133 }
2134
2135 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
2136   // Get the source and destination types
2137   Type *SrcTy = I.getOperand(0)->getType();
2138   Type *DestTy = I.getType();
2139
2140   Assert(SrcTy->getScalarType()->isIntegerTy(),
2141          "IntToPtr source must be an integral", &I);
2142   Assert(DestTy->getScalarType()->isPointerTy(),
2143          "IntToPtr result must be a pointer", &I);
2144   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
2145          &I);
2146   if (SrcTy->isVectorTy()) {
2147     VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
2148     VectorType *VDest = dyn_cast<VectorType>(DestTy);
2149     Assert(VSrc->getNumElements() == VDest->getNumElements(),
2150            "IntToPtr Vector width mismatch", &I);
2151   }
2152   visitInstruction(I);
2153 }
2154
2155 void Verifier::visitBitCastInst(BitCastInst &I) {
2156   Assert(
2157       CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
2158       "Invalid bitcast", &I);
2159   visitInstruction(I);
2160 }
2161
2162 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
2163   Type *SrcTy = I.getOperand(0)->getType();
2164   Type *DestTy = I.getType();
2165
2166   Assert(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
2167          &I);
2168   Assert(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
2169          &I);
2170   Assert(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
2171          "AddrSpaceCast must be between different address spaces", &I);
2172   if (SrcTy->isVectorTy())
2173     Assert(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(),
2174            "AddrSpaceCast vector pointer number of elements mismatch", &I);
2175   visitInstruction(I);
2176 }
2177
2178 /// visitPHINode - Ensure that a PHI node is well formed.
2179 ///
2180 void Verifier::visitPHINode(PHINode &PN) {
2181   // Ensure that the PHI nodes are all grouped together at the top of the block.
2182   // This can be tested by checking whether the instruction before this is
2183   // either nonexistent (because this is begin()) or is a PHI node.  If not,
2184   // then there is some other instruction before a PHI.
2185   Assert(&PN == &PN.getParent()->front() ||
2186              isa<PHINode>(--BasicBlock::iterator(&PN)),
2187          "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
2188
2189   // Check that all of the values of the PHI node have the same type as the
2190   // result, and that the incoming blocks are really basic blocks.
2191   for (Value *IncValue : PN.incoming_values()) {
2192     Assert(PN.getType() == IncValue->getType(),
2193            "PHI node operands are not the same type as the result!", &PN);
2194   }
2195
2196   // All other PHI node constraints are checked in the visitBasicBlock method.
2197
2198   visitInstruction(PN);
2199 }
2200
2201 void Verifier::VerifyCallSite(CallSite CS) {
2202   Instruction *I = CS.getInstruction();
2203
2204   Assert(CS.getCalledValue()->getType()->isPointerTy(),
2205          "Called function must be a pointer!", I);
2206   PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
2207
2208   Assert(FPTy->getElementType()->isFunctionTy(),
2209          "Called function is not pointer to function type!", I);
2210
2211   Assert(FPTy->getElementType() == CS.getFunctionType(),
2212          "Called function is not the same type as the call!", I);
2213
2214   FunctionType *FTy = CS.getFunctionType();
2215
2216   // Verify that the correct number of arguments are being passed
2217   if (FTy->isVarArg())
2218     Assert(CS.arg_size() >= FTy->getNumParams(),
2219            "Called function requires more parameters than were provided!", I);
2220   else
2221     Assert(CS.arg_size() == FTy->getNumParams(),
2222            "Incorrect number of arguments passed to called function!", I);
2223
2224   // Verify that all arguments to the call match the function type.
2225   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2226     Assert(CS.getArgument(i)->getType() == FTy->getParamType(i),
2227            "Call parameter type does not match function signature!",
2228            CS.getArgument(i), FTy->getParamType(i), I);
2229
2230   AttributeSet Attrs = CS.getAttributes();
2231
2232   Assert(VerifyAttributeCount(Attrs, CS.arg_size()),
2233          "Attribute after last parameter!", I);
2234
2235   // Verify call attributes.
2236   VerifyFunctionAttrs(FTy, Attrs, I);
2237
2238   // Conservatively check the inalloca argument.
2239   // We have a bug if we can find that there is an underlying alloca without
2240   // inalloca.
2241   if (CS.hasInAllocaArgument()) {
2242     Value *InAllocaArg = CS.getArgument(FTy->getNumParams() - 1);
2243     if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
2244       Assert(AI->isUsedWithInAlloca(),
2245              "inalloca argument for call has mismatched alloca", AI, I);
2246   }
2247
2248   if (FTy->isVarArg()) {
2249     // FIXME? is 'nest' even legal here?
2250     bool SawNest = false;
2251     bool SawReturned = false;
2252
2253     for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) {
2254       if (Attrs.hasAttribute(Idx, Attribute::Nest))
2255         SawNest = true;
2256       if (Attrs.hasAttribute(Idx, Attribute::Returned))
2257         SawReturned = true;
2258     }
2259
2260     // Check attributes on the varargs part.
2261     for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
2262       Type *Ty = CS.getArgument(Idx-1)->getType();
2263       VerifyParameterAttrs(Attrs, Idx, Ty, false, I);
2264
2265       if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
2266         Assert(!SawNest, "More than one parameter has attribute nest!", I);
2267         SawNest = true;
2268       }
2269
2270       if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
2271         Assert(!SawReturned, "More than one parameter has attribute returned!",
2272                I);
2273         Assert(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
2274                "Incompatible argument and return types for 'returned' "
2275                "attribute",
2276                I);
2277         SawReturned = true;
2278       }
2279
2280       Assert(!Attrs.hasAttribute(Idx, Attribute::StructRet),
2281              "Attribute 'sret' cannot be used for vararg call arguments!", I);
2282
2283       if (Attrs.hasAttribute(Idx, Attribute::InAlloca))
2284         Assert(Idx == CS.arg_size(), "inalloca isn't on the last argument!", I);
2285     }
2286   }
2287
2288   // Verify that there's no metadata unless it's a direct call to an intrinsic.
2289   if (CS.getCalledFunction() == nullptr ||
2290       !CS.getCalledFunction()->getName().startswith("llvm.")) {
2291     for (FunctionType::param_iterator PI = FTy->param_begin(),
2292            PE = FTy->param_end(); PI != PE; ++PI)
2293       Assert(!(*PI)->isMetadataTy(),
2294              "Function has metadata parameter but isn't an intrinsic", I);
2295   }
2296
2297   if (Function *F = CS.getCalledFunction())
2298     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
2299       visitIntrinsicFunctionCall(ID, CS);
2300
2301   visitInstruction(*I);
2302 }
2303
2304 /// Two types are "congruent" if they are identical, or if they are both pointer
2305 /// types with different pointee types and the same address space.
2306 static bool isTypeCongruent(Type *L, Type *R) {
2307   if (L == R)
2308     return true;
2309   PointerType *PL = dyn_cast<PointerType>(L);
2310   PointerType *PR = dyn_cast<PointerType>(R);
2311   if (!PL || !PR)
2312     return false;
2313   return PL->getAddressSpace() == PR->getAddressSpace();
2314 }
2315
2316 static AttrBuilder getParameterABIAttributes(int I, AttributeSet Attrs) {
2317   static const Attribute::AttrKind ABIAttrs[] = {
2318       Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
2319       Attribute::InReg, Attribute::Returned};
2320   AttrBuilder Copy;
2321   for (auto AK : ABIAttrs) {
2322     if (Attrs.hasAttribute(I + 1, AK))
2323       Copy.addAttribute(AK);
2324   }
2325   if (Attrs.hasAttribute(I + 1, Attribute::Alignment))
2326     Copy.addAlignmentAttr(Attrs.getParamAlignment(I + 1));
2327   return Copy;
2328 }
2329
2330 void Verifier::verifyMustTailCall(CallInst &CI) {
2331   Assert(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
2332
2333   // - The caller and callee prototypes must match.  Pointer types of
2334   //   parameters or return types may differ in pointee type, but not
2335   //   address space.
2336   Function *F = CI.getParent()->getParent();
2337   FunctionType *CallerTy = F->getFunctionType();
2338   FunctionType *CalleeTy = CI.getFunctionType();
2339   Assert(CallerTy->getNumParams() == CalleeTy->getNumParams(),
2340          "cannot guarantee tail call due to mismatched parameter counts", &CI);
2341   Assert(CallerTy->isVarArg() == CalleeTy->isVarArg(),
2342          "cannot guarantee tail call due to mismatched varargs", &CI);
2343   Assert(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
2344          "cannot guarantee tail call due to mismatched return types", &CI);
2345   for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
2346     Assert(
2347         isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
2348         "cannot guarantee tail call due to mismatched parameter types", &CI);
2349   }
2350
2351   // - The calling conventions of the caller and callee must match.
2352   Assert(F->getCallingConv() == CI.getCallingConv(),
2353          "cannot guarantee tail call due to mismatched calling conv", &CI);
2354
2355   // - All ABI-impacting function attributes, such as sret, byval, inreg,
2356   //   returned, and inalloca, must match.
2357   AttributeSet CallerAttrs = F->getAttributes();
2358   AttributeSet CalleeAttrs = CI.getAttributes();
2359   for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
2360     AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs);
2361     AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs);
2362     Assert(CallerABIAttrs == CalleeABIAttrs,
2363            "cannot guarantee tail call due to mismatched ABI impacting "
2364            "function attributes",
2365            &CI, CI.getOperand(I));
2366   }
2367
2368   // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
2369   //   or a pointer bitcast followed by a ret instruction.
2370   // - The ret instruction must return the (possibly bitcasted) value
2371   //   produced by the call or void.
2372   Value *RetVal = &CI;
2373   Instruction *Next = CI.getNextNode();
2374
2375   // Handle the optional bitcast.
2376   if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
2377     Assert(BI->getOperand(0) == RetVal,
2378            "bitcast following musttail call must use the call", BI);
2379     RetVal = BI;
2380     Next = BI->getNextNode();
2381   }
2382
2383   // Check the return.
2384   ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
2385   Assert(Ret, "musttail call must be precede a ret with an optional bitcast",
2386          &CI);
2387   Assert(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal,
2388          "musttail call result must be returned", Ret);
2389 }
2390
2391 void Verifier::visitCallInst(CallInst &CI) {
2392   VerifyCallSite(&CI);
2393
2394   if (CI.isMustTailCall())
2395     verifyMustTailCall(CI);
2396 }
2397
2398 void Verifier::visitInvokeInst(InvokeInst &II) {
2399   VerifyCallSite(&II);
2400
2401   // Verify that there is a landingpad instruction as the first non-PHI
2402   // instruction of the 'unwind' destination.
2403   Assert(II.getUnwindDest()->isLandingPad(),
2404          "The unwind destination does not have a landingpad instruction!", &II);
2405
2406   visitTerminatorInst(II);
2407 }
2408
2409 /// visitBinaryOperator - Check that both arguments to the binary operator are
2410 /// of the same type!
2411 ///
2412 void Verifier::visitBinaryOperator(BinaryOperator &B) {
2413   Assert(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
2414          "Both operands to a binary operator are not of the same type!", &B);
2415
2416   switch (B.getOpcode()) {
2417   // Check that integer arithmetic operators are only used with
2418   // integral operands.
2419   case Instruction::Add:
2420   case Instruction::Sub:
2421   case Instruction::Mul:
2422   case Instruction::SDiv:
2423   case Instruction::UDiv:
2424   case Instruction::SRem:
2425   case Instruction::URem:
2426     Assert(B.getType()->isIntOrIntVectorTy(),
2427            "Integer arithmetic operators only work with integral types!", &B);
2428     Assert(B.getType() == B.getOperand(0)->getType(),
2429            "Integer arithmetic operators must have same type "
2430            "for operands and result!",
2431            &B);
2432     break;
2433   // Check that floating-point arithmetic operators are only used with
2434   // floating-point operands.
2435   case Instruction::FAdd:
2436   case Instruction::FSub:
2437   case Instruction::FMul:
2438   case Instruction::FDiv:
2439   case Instruction::FRem:
2440     Assert(B.getType()->isFPOrFPVectorTy(),
2441            "Floating-point arithmetic operators only work with "
2442            "floating-point types!",
2443            &B);
2444     Assert(B.getType() == B.getOperand(0)->getType(),
2445            "Floating-point arithmetic operators must have same type "
2446            "for operands and result!",
2447            &B);
2448     break;
2449   // Check that logical operators are only used with integral operands.
2450   case Instruction::And:
2451   case Instruction::Or:
2452   case Instruction::Xor:
2453     Assert(B.getType()->isIntOrIntVectorTy(),
2454            "Logical operators only work with integral types!", &B);
2455     Assert(B.getType() == B.getOperand(0)->getType(),
2456            "Logical operators must have same type for operands and result!",
2457            &B);
2458     break;
2459   case Instruction::Shl:
2460   case Instruction::LShr:
2461   case Instruction::AShr:
2462     Assert(B.getType()->isIntOrIntVectorTy(),
2463            "Shifts only work with integral types!", &B);
2464     Assert(B.getType() == B.getOperand(0)->getType(),
2465            "Shift return type must be same as operands!", &B);
2466     break;
2467   default:
2468     llvm_unreachable("Unknown BinaryOperator opcode!");
2469   }
2470
2471   visitInstruction(B);
2472 }
2473
2474 void Verifier::visitICmpInst(ICmpInst &IC) {
2475   // Check that the operands are the same type
2476   Type *Op0Ty = IC.getOperand(0)->getType();
2477   Type *Op1Ty = IC.getOperand(1)->getType();
2478   Assert(Op0Ty == Op1Ty,
2479          "Both operands to ICmp instruction are not of the same type!", &IC);
2480   // Check that the operands are the right type
2481   Assert(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
2482          "Invalid operand types for ICmp instruction", &IC);
2483   // Check that the predicate is valid.
2484   Assert(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
2485              IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
2486          "Invalid predicate in ICmp instruction!", &IC);
2487
2488   visitInstruction(IC);
2489 }
2490
2491 void Verifier::visitFCmpInst(FCmpInst &FC) {
2492   // Check that the operands are the same type
2493   Type *Op0Ty = FC.getOperand(0)->getType();
2494   Type *Op1Ty = FC.getOperand(1)->getType();
2495   Assert(Op0Ty == Op1Ty,
2496          "Both operands to FCmp instruction are not of the same type!", &FC);
2497   // Check that the operands are the right type
2498   Assert(Op0Ty->isFPOrFPVectorTy(),
2499          "Invalid operand types for FCmp instruction", &FC);
2500   // Check that the predicate is valid.
2501   Assert(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
2502              FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
2503          "Invalid predicate in FCmp instruction!", &FC);
2504
2505   visitInstruction(FC);
2506 }
2507
2508 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
2509   Assert(
2510       ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)),
2511       "Invalid extractelement operands!", &EI);
2512   visitInstruction(EI);
2513 }
2514
2515 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
2516   Assert(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
2517                                             IE.getOperand(2)),
2518          "Invalid insertelement operands!", &IE);
2519   visitInstruction(IE);
2520 }
2521
2522 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
2523   Assert(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
2524                                             SV.getOperand(2)),
2525          "Invalid shufflevector operands!", &SV);
2526   visitInstruction(SV);
2527 }
2528
2529 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
2530   Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
2531
2532   Assert(isa<PointerType>(TargetTy),
2533          "GEP base pointer is not a vector or a vector of pointers", &GEP);
2534   Assert(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP);
2535   Assert(GEP.getPointerOperandType()->isVectorTy() ==
2536              GEP.getType()->isVectorTy(),
2537          "Vector GEP must return a vector value", &GEP);
2538
2539   SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
2540   Type *ElTy =
2541       GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs);
2542   Assert(ElTy, "Invalid indices for GEP pointer type!", &GEP);
2543
2544   Assert(GEP.getType()->getScalarType()->isPointerTy() &&
2545              GEP.getResultElementType() == ElTy,
2546          "GEP is not of right type for indices!", &GEP, ElTy);
2547
2548   if (GEP.getPointerOperandType()->isVectorTy()) {
2549     // Additional checks for vector GEPs.
2550     unsigned GepWidth = GEP.getPointerOperandType()->getVectorNumElements();
2551     Assert(GepWidth == GEP.getType()->getVectorNumElements(),
2552            "Vector GEP result width doesn't match operand's", &GEP);
2553     for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
2554       Type *IndexTy = Idxs[i]->getType();
2555       Assert(IndexTy->isVectorTy(), "Vector GEP must have vector indices!",
2556              &GEP);
2557       unsigned IndexWidth = IndexTy->getVectorNumElements();
2558       Assert(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP);
2559     }
2560   }
2561   visitInstruction(GEP);
2562 }
2563
2564 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
2565   return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
2566 }
2567
2568 void Verifier::visitRangeMetadata(Instruction& I,
2569                                   MDNode* Range, Type* Ty) {
2570   assert(Range &&
2571          Range == I.getMetadata(LLVMContext::MD_range) &&
2572          "precondition violation");
2573
2574   unsigned NumOperands = Range->getNumOperands();
2575   Assert(NumOperands % 2 == 0, "Unfinished range!", Range);
2576   unsigned NumRanges = NumOperands / 2;
2577   Assert(NumRanges >= 1, "It should have at least one range!", Range);
2578
2579   ConstantRange LastRange(1); // Dummy initial value
2580   for (unsigned i = 0; i < NumRanges; ++i) {
2581     ConstantInt *Low =
2582         mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
2583     Assert(Low, "The lower limit must be an integer!", Low);
2584     ConstantInt *High =
2585         mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
2586     Assert(High, "The upper limit must be an integer!", High);
2587     Assert(High->getType() == Low->getType() && High->getType() == Ty,
2588            "Range types must match instruction type!", &I);
2589
2590     APInt HighV = High->getValue();
2591     APInt LowV = Low->getValue();
2592     ConstantRange CurRange(LowV, HighV);
2593     Assert(!CurRange.isEmptySet() && !CurRange.isFullSet(),
2594            "Range must not be empty!", Range);
2595     if (i != 0) {
2596       Assert(CurRange.intersectWith(LastRange).isEmptySet(),
2597              "Intervals are overlapping", Range);
2598       Assert(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
2599              Range);
2600       Assert(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
2601              Range);
2602     }
2603     LastRange = ConstantRange(LowV, HighV);
2604   }
2605   if (NumRanges > 2) {
2606     APInt FirstLow =
2607         mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
2608     APInt FirstHigh =
2609         mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
2610     ConstantRange FirstRange(FirstLow, FirstHigh);
2611     Assert(FirstRange.intersectWith(LastRange).isEmptySet(),
2612            "Intervals are overlapping", Range);
2613     Assert(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
2614            Range);
2615   }
2616 }
2617
2618 void Verifier::visitLoadInst(LoadInst &LI) {
2619   PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
2620   Assert(PTy, "Load operand must be a pointer.", &LI);
2621   Type *ElTy = LI.getType();
2622   Assert(LI.getAlignment() <= Value::MaximumAlignment,
2623          "huge alignment values are unsupported", &LI);
2624   if (LI.isAtomic()) {
2625     Assert(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
2626            "Load cannot have Release ordering", &LI);
2627     Assert(LI.getAlignment() != 0,
2628            "Atomic load must specify explicit alignment", &LI);
2629     if (!ElTy->isPointerTy()) {
2630       Assert(ElTy->isIntegerTy(), "atomic load operand must have integer type!",
2631              &LI, ElTy);
2632       unsigned Size = ElTy->getPrimitiveSizeInBits();
2633       Assert(Size >= 8 && !(Size & (Size - 1)),
2634              "atomic load operand must be power-of-two byte-sized integer", &LI,
2635              ElTy);
2636     }
2637   } else {
2638     Assert(LI.getSynchScope() == CrossThread,
2639            "Non-atomic load cannot have SynchronizationScope specified", &LI);
2640   }
2641
2642   visitInstruction(LI);
2643 }
2644
2645 void Verifier::visitStoreInst(StoreInst &SI) {
2646   PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
2647   Assert(PTy, "Store operand must be a pointer.", &SI);
2648   Type *ElTy = PTy->getElementType();
2649   Assert(ElTy == SI.getOperand(0)->getType(),
2650          "Stored value type does not match pointer operand type!", &SI, ElTy);
2651   Assert(SI.getAlignment() <= Value::MaximumAlignment,
2652          "huge alignment values are unsupported", &SI);
2653   if (SI.isAtomic()) {
2654     Assert(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
2655            "Store cannot have Acquire ordering", &SI);
2656     Assert(SI.getAlignment() != 0,
2657            "Atomic store must specify explicit alignment", &SI);
2658     if (!ElTy->isPointerTy()) {
2659       Assert(ElTy->isIntegerTy(),
2660              "atomic store operand must have integer type!", &SI, ElTy);
2661       unsigned Size = ElTy->getPrimitiveSizeInBits();
2662       Assert(Size >= 8 && !(Size & (Size - 1)),
2663              "atomic store operand must be power-of-two byte-sized integer",
2664              &SI, ElTy);
2665     }
2666   } else {
2667     Assert(SI.getSynchScope() == CrossThread,
2668            "Non-atomic store cannot have SynchronizationScope specified", &SI);
2669   }
2670   visitInstruction(SI);
2671 }
2672
2673 void Verifier::visitAllocaInst(AllocaInst &AI) {
2674   SmallPtrSet<const Type*, 4> Visited;
2675   PointerType *PTy = AI.getType();
2676   Assert(PTy->getAddressSpace() == 0,
2677          "Allocation instruction pointer not in the generic address space!",
2678          &AI);
2679   Assert(AI.getAllocatedType()->isSized(&Visited),
2680          "Cannot allocate unsized type", &AI);
2681   Assert(AI.getArraySize()->getType()->isIntegerTy(),
2682          "Alloca array size must have integer type", &AI);
2683   Assert(AI.getAlignment() <= Value::MaximumAlignment,
2684          "huge alignment values are unsupported", &AI);
2685
2686   visitInstruction(AI);
2687 }
2688
2689 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
2690
2691   // FIXME: more conditions???
2692   Assert(CXI.getSuccessOrdering() != NotAtomic,
2693          "cmpxchg instructions must be atomic.", &CXI);
2694   Assert(CXI.getFailureOrdering() != NotAtomic,
2695          "cmpxchg instructions must be atomic.", &CXI);
2696   Assert(CXI.getSuccessOrdering() != Unordered,
2697          "cmpxchg instructions cannot be unordered.", &CXI);
2698   Assert(CXI.getFailureOrdering() != Unordered,
2699          "cmpxchg instructions cannot be unordered.", &CXI);
2700   Assert(CXI.getSuccessOrdering() >= CXI.getFailureOrdering(),
2701          "cmpxchg instructions be at least as constrained on success as fail",
2702          &CXI);
2703   Assert(CXI.getFailureOrdering() != Release &&
2704              CXI.getFailureOrdering() != AcquireRelease,
2705          "cmpxchg failure ordering cannot include release semantics", &CXI);
2706
2707   PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
2708   Assert(PTy, "First cmpxchg operand must be a pointer.", &CXI);
2709   Type *ElTy = PTy->getElementType();
2710   Assert(ElTy->isIntegerTy(), "cmpxchg operand must have integer type!", &CXI,
2711          ElTy);
2712   unsigned Size = ElTy->getPrimitiveSizeInBits();
2713   Assert(Size >= 8 && !(Size & (Size - 1)),
2714          "cmpxchg operand must be power-of-two byte-sized integer", &CXI, ElTy);
2715   Assert(ElTy == CXI.getOperand(1)->getType(),
2716          "Expected value type does not match pointer operand type!", &CXI,
2717          ElTy);
2718   Assert(ElTy == CXI.getOperand(2)->getType(),
2719          "Stored value type does not match pointer operand type!", &CXI, ElTy);
2720   visitInstruction(CXI);
2721 }
2722
2723 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
2724   Assert(RMWI.getOrdering() != NotAtomic,
2725          "atomicrmw instructions must be atomic.", &RMWI);
2726   Assert(RMWI.getOrdering() != Unordered,
2727          "atomicrmw instructions cannot be unordered.", &RMWI);
2728   PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
2729   Assert(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
2730   Type *ElTy = PTy->getElementType();
2731   Assert(ElTy->isIntegerTy(), "atomicrmw operand must have integer type!",
2732          &RMWI, ElTy);
2733   unsigned Size = ElTy->getPrimitiveSizeInBits();
2734   Assert(Size >= 8 && !(Size & (Size - 1)),
2735          "atomicrmw operand must be power-of-two byte-sized integer", &RMWI,
2736          ElTy);
2737   Assert(ElTy == RMWI.getOperand(1)->getType(),
2738          "Argument value type does not match pointer operand type!", &RMWI,
2739          ElTy);
2740   Assert(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
2741              RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
2742          "Invalid binary operation!", &RMWI);
2743   visitInstruction(RMWI);
2744 }
2745
2746 void Verifier::visitFenceInst(FenceInst &FI) {
2747   const AtomicOrdering Ordering = FI.getOrdering();
2748   Assert(Ordering == Acquire || Ordering == Release ||
2749              Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
2750          "fence instructions may only have "
2751          "acquire, release, acq_rel, or seq_cst ordering.",
2752          &FI);
2753   visitInstruction(FI);
2754 }
2755
2756 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
2757   Assert(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
2758                                           EVI.getIndices()) == EVI.getType(),
2759          "Invalid ExtractValueInst operands!", &EVI);
2760
2761   visitInstruction(EVI);
2762 }
2763
2764 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
2765   Assert(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
2766                                           IVI.getIndices()) ==
2767              IVI.getOperand(1)->getType(),
2768          "Invalid InsertValueInst operands!", &IVI);
2769
2770   visitInstruction(IVI);
2771 }
2772
2773 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
2774   BasicBlock *BB = LPI.getParent();
2775
2776   // The landingpad instruction is ill-formed if it doesn't have any clauses and
2777   // isn't a cleanup.
2778   Assert(LPI.getNumClauses() > 0 || LPI.isCleanup(),
2779          "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
2780
2781   // The landingpad instruction defines its parent as a landing pad block. The
2782   // landing pad block may be branched to only by the unwind edge of an invoke.
2783   for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
2784     const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator());
2785     Assert(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
2786            "Block containing LandingPadInst must be jumped to "
2787            "only by the unwind edge of an invoke.",
2788            &LPI);
2789   }
2790
2791   Function *F = LPI.getParent()->getParent();
2792   Assert(F->hasPersonalityFn(),
2793          "LandingPadInst needs to be in a function with a personality.", &LPI);
2794
2795   // The landingpad instruction must be the first non-PHI instruction in the
2796   // block.
2797   Assert(LPI.getParent()->getLandingPadInst() == &LPI,
2798          "LandingPadInst not the first non-PHI instruction in the block.",
2799          &LPI);
2800
2801   for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
2802     Constant *Clause = LPI.getClause(i);
2803     if (LPI.isCatch(i)) {
2804       Assert(isa<PointerType>(Clause->getType()),
2805              "Catch operand does not have pointer type!", &LPI);
2806     } else {
2807       Assert(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
2808       Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
2809              "Filter operand is not an array of constants!", &LPI);
2810     }
2811   }
2812
2813   visitInstruction(LPI);
2814 }
2815
2816 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
2817   Instruction *Op = cast<Instruction>(I.getOperand(i));
2818   // If the we have an invalid invoke, don't try to compute the dominance.
2819   // We already reject it in the invoke specific checks and the dominance
2820   // computation doesn't handle multiple edges.
2821   if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
2822     if (II->getNormalDest() == II->getUnwindDest())
2823       return;
2824   }
2825
2826   const Use &U = I.getOperandUse(i);
2827   Assert(InstsInThisBlock.count(Op) || DT.dominates(Op, U),
2828          "Instruction does not dominate all uses!", Op, &I);
2829 }
2830
2831 /// verifyInstruction - Verify that an instruction is well formed.
2832 ///
2833 void Verifier::visitInstruction(Instruction &I) {
2834   BasicBlock *BB = I.getParent();
2835   Assert(BB, "Instruction not embedded in basic block!", &I);
2836
2837   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
2838     for (User *U : I.users()) {
2839       Assert(U != (User *)&I || !DT.isReachableFromEntry(BB),
2840              "Only PHI nodes may reference their own value!", &I);
2841     }
2842   }
2843
2844   // Check that void typed values don't have names
2845   Assert(!I.getType()->isVoidTy() || !I.hasName(),
2846          "Instruction has a name, but provides a void value!", &I);
2847
2848   // Check that the return value of the instruction is either void or a legal
2849   // value type.
2850   Assert(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
2851          "Instruction returns a non-scalar type!", &I);
2852
2853   // Check that the instruction doesn't produce metadata. Calls are already
2854   // checked against the callee type.
2855   Assert(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
2856          "Invalid use of metadata!", &I);
2857
2858   // Check that all uses of the instruction, if they are instructions
2859   // themselves, actually have parent basic blocks.  If the use is not an
2860   // instruction, it is an error!
2861   for (Use &U : I.uses()) {
2862     if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
2863       Assert(Used->getParent() != nullptr,
2864              "Instruction referencing"
2865              " instruction not embedded in a basic block!",
2866              &I, Used);
2867     else {
2868       CheckFailed("Use of instruction is not an instruction!", U);
2869       return;
2870     }
2871   }
2872
2873   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2874     Assert(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
2875
2876     // Check to make sure that only first-class-values are operands to
2877     // instructions.
2878     if (!I.getOperand(i)->getType()->isFirstClassType()) {
2879       Assert(0, "Instruction operands must be first-class values!", &I);
2880     }
2881
2882     if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
2883       // Check to make sure that the "address of" an intrinsic function is never
2884       // taken.
2885       Assert(
2886           !F->isIntrinsic() ||
2887               i == (isa<CallInst>(I) ? e - 1 : isa<InvokeInst>(I) ? e - 3 : 0),
2888           "Cannot take the address of an intrinsic!", &I);
2889       Assert(
2890           !F->isIntrinsic() || isa<CallInst>(I) ||
2891               F->getIntrinsicID() == Intrinsic::donothing ||
2892               F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void ||
2893               F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 ||
2894               F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint,
2895           "Cannot invoke an intrinsinc other than"
2896           " donothing or patchpoint",
2897           &I);
2898       Assert(F->getParent() == M, "Referencing function in another module!",
2899              &I);
2900     } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
2901       Assert(OpBB->getParent() == BB->getParent(),
2902              "Referring to a basic block in another function!", &I);
2903     } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
2904       Assert(OpArg->getParent() == BB->getParent(),
2905              "Referring to an argument in another function!", &I);
2906     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
2907       Assert(GV->getParent() == M, "Referencing global in another module!", &I);
2908     } else if (isa<Instruction>(I.getOperand(i))) {
2909       verifyDominatesUse(I, i);
2910     } else if (isa<InlineAsm>(I.getOperand(i))) {
2911       Assert((i + 1 == e && isa<CallInst>(I)) ||
2912                  (i + 3 == e && isa<InvokeInst>(I)),
2913              "Cannot take the address of an inline asm!", &I);
2914     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
2915       if (CE->getType()->isPtrOrPtrVectorTy()) {
2916         // If we have a ConstantExpr pointer, we need to see if it came from an
2917         // illegal bitcast (inttoptr <constant int> )
2918         SmallVector<const ConstantExpr *, 4> Stack;
2919         SmallPtrSet<const ConstantExpr *, 4> Visited;
2920         Stack.push_back(CE);
2921
2922         while (!Stack.empty()) {
2923           const ConstantExpr *V = Stack.pop_back_val();
2924           if (!Visited.insert(V).second)
2925             continue;
2926
2927           VerifyConstantExprBitcastType(V);
2928
2929           for (unsigned I = 0, N = V->getNumOperands(); I != N; ++I) {
2930             if (ConstantExpr *Op = dyn_cast<ConstantExpr>(V->getOperand(I)))
2931               Stack.push_back(Op);
2932           }
2933         }
2934       }
2935     }
2936   }
2937
2938   if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
2939     Assert(I.getType()->isFPOrFPVectorTy(),
2940            "fpmath requires a floating point result!", &I);
2941     Assert(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
2942     if (ConstantFP *CFP0 =
2943             mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) {
2944       APFloat Accuracy = CFP0->getValueAPF();
2945       Assert(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
2946              "fpmath accuracy not a positive number!", &I);
2947     } else {
2948       Assert(false, "invalid fpmath accuracy!", &I);
2949     }
2950   }
2951
2952   if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
2953     Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),
2954            "Ranges are only for loads, calls and invokes!", &I);
2955     visitRangeMetadata(I, Range, I.getType());
2956   }
2957
2958   if (I.getMetadata(LLVMContext::MD_nonnull)) {
2959     Assert(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
2960            &I);
2961     Assert(isa<LoadInst>(I),
2962            "nonnull applies only to load instructions, use attributes"
2963            " for calls or invokes",
2964            &I);
2965   }
2966
2967   if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
2968     Assert(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N);
2969     visitMDNode(*N);
2970   }
2971
2972   InstsInThisBlock.insert(&I);
2973 }
2974
2975 /// VerifyIntrinsicType - Verify that the specified type (which comes from an
2976 /// intrinsic argument or return value) matches the type constraints specified
2977 /// by the .td file (e.g. an "any integer" argument really is an integer).
2978 ///
2979 /// This return true on error but does not print a message.
2980 bool Verifier::VerifyIntrinsicType(Type *Ty,
2981                                    ArrayRef<Intrinsic::IITDescriptor> &Infos,
2982                                    SmallVectorImpl<Type*> &ArgTys) {
2983   using namespace Intrinsic;
2984
2985   // If we ran out of descriptors, there are too many arguments.
2986   if (Infos.empty()) return true;
2987   IITDescriptor D = Infos.front();
2988   Infos = Infos.slice(1);
2989
2990   switch (D.Kind) {
2991   case IITDescriptor::Void: return !Ty->isVoidTy();
2992   case IITDescriptor::VarArg: return true;
2993   case IITDescriptor::MMX:  return !Ty->isX86_MMXTy();
2994   case IITDescriptor::Metadata: return !Ty->isMetadataTy();
2995   case IITDescriptor::Half: return !Ty->isHalfTy();
2996   case IITDescriptor::Float: return !Ty->isFloatTy();
2997   case IITDescriptor::Double: return !Ty->isDoubleTy();
2998   case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
2999   case IITDescriptor::Vector: {
3000     VectorType *VT = dyn_cast<VectorType>(Ty);
3001     return !VT || VT->getNumElements() != D.Vector_Width ||
3002            VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
3003   }
3004   case IITDescriptor::Pointer: {
3005     PointerType *PT = dyn_cast<PointerType>(Ty);
3006     return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
3007            VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
3008   }
3009
3010   case IITDescriptor::Struct: {
3011     StructType *ST = dyn_cast<StructType>(Ty);
3012     if (!ST || ST->getNumElements() != D.Struct_NumElements)
3013       return true;
3014
3015     for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
3016       if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
3017         return true;
3018     return false;
3019   }
3020
3021   case IITDescriptor::Argument:
3022     // Two cases here - If this is the second occurrence of an argument, verify
3023     // that the later instance matches the previous instance.
3024     if (D.getArgumentNumber() < ArgTys.size())
3025       return Ty != ArgTys[D.getArgumentNumber()];
3026
3027     // Otherwise, if this is the first instance of an argument, record it and
3028     // verify the "Any" kind.
3029     assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
3030     ArgTys.push_back(Ty);
3031
3032     switch (D.getArgumentKind()) {
3033     case IITDescriptor::AK_Any:        return false; // Success
3034     case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
3035     case IITDescriptor::AK_AnyFloat:   return !Ty->isFPOrFPVectorTy();
3036     case IITDescriptor::AK_AnyVector:  return !isa<VectorType>(Ty);
3037     case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
3038     }
3039     llvm_unreachable("all argument kinds not covered");
3040
3041   case IITDescriptor::ExtendArgument: {
3042     // This may only be used when referring to a previous vector argument.
3043     if (D.getArgumentNumber() >= ArgTys.size())
3044       return true;
3045
3046     Type *NewTy = ArgTys[D.getArgumentNumber()];
3047     if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
3048       NewTy = VectorType::getExtendedElementVectorType(VTy);
3049     else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
3050       NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
3051     else
3052       return true;
3053
3054     return Ty != NewTy;
3055   }
3056   case IITDescriptor::TruncArgument: {
3057     // This may only be used when referring to a previous vector argument.
3058     if (D.getArgumentNumber() >= ArgTys.size())
3059       return true;
3060
3061     Type *NewTy = ArgTys[D.getArgumentNumber()];
3062     if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
3063       NewTy = VectorType::getTruncatedElementVectorType(VTy);
3064     else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
3065       NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
3066     else
3067       return true;
3068
3069     return Ty != NewTy;
3070   }
3071   case IITDescriptor::HalfVecArgument:
3072     // This may only be used when referring to a previous vector argument.
3073     return D.getArgumentNumber() >= ArgTys.size() ||
3074            !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
3075            VectorType::getHalfElementsVectorType(
3076                          cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
3077   case IITDescriptor::SameVecWidthArgument: {
3078     if (D.getArgumentNumber() >= ArgTys.size())
3079       return true;
3080     VectorType * ReferenceType =
3081       dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
3082     VectorType *ThisArgType = dyn_cast<VectorType>(Ty);
3083     if (!ThisArgType || !ReferenceType || 
3084         (ReferenceType->getVectorNumElements() !=
3085          ThisArgType->getVectorNumElements()))
3086       return true;
3087     return VerifyIntrinsicType(ThisArgType->getVectorElementType(),
3088                                Infos, ArgTys);
3089   }
3090   case IITDescriptor::PtrToArgument: {
3091     if (D.getArgumentNumber() >= ArgTys.size())
3092       return true;
3093     Type * ReferenceType = ArgTys[D.getArgumentNumber()];
3094     PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
3095     return (!ThisArgType || ThisArgType->getElementType() != ReferenceType);
3096   }
3097   case IITDescriptor::VecOfPtrsToElt: {
3098     if (D.getArgumentNumber() >= ArgTys.size())
3099       return true;
3100     VectorType * ReferenceType =
3101       dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]);
3102     VectorType *ThisArgVecTy = dyn_cast<VectorType>(Ty);
3103     if (!ThisArgVecTy || !ReferenceType || 
3104         (ReferenceType->getVectorNumElements() !=
3105          ThisArgVecTy->getVectorNumElements()))
3106       return true;
3107     PointerType *ThisArgEltTy =
3108       dyn_cast<PointerType>(ThisArgVecTy->getVectorElementType());
3109     if (!ThisArgEltTy)
3110       return true;
3111     return ThisArgEltTy->getElementType() !=
3112            ReferenceType->getVectorElementType();
3113   }
3114   }
3115   llvm_unreachable("unhandled");
3116 }
3117
3118 /// \brief Verify if the intrinsic has variable arguments.
3119 /// This method is intended to be called after all the fixed arguments have been
3120 /// verified first.
3121 ///
3122 /// This method returns true on error and does not print an error message.
3123 bool
3124 Verifier::VerifyIntrinsicIsVarArg(bool isVarArg,
3125                                   ArrayRef<Intrinsic::IITDescriptor> &Infos) {
3126   using namespace Intrinsic;
3127
3128   // If there are no descriptors left, then it can't be a vararg.
3129   if (Infos.empty())
3130     return isVarArg;
3131
3132   // There should be only one descriptor remaining at this point.
3133   if (Infos.size() != 1)
3134     return true;
3135
3136   // Check and verify the descriptor.
3137   IITDescriptor D = Infos.front();
3138   Infos = Infos.slice(1);
3139   if (D.Kind == IITDescriptor::VarArg)
3140     return !isVarArg;
3141
3142   return true;
3143 }
3144
3145 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
3146 ///
3147 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallSite CI) {
3148   Function *IF = CI.getCalledFunction();
3149   Assert(IF->isDeclaration(), "Intrinsic functions should never be defined!",
3150          IF);
3151
3152   // Verify that the intrinsic prototype lines up with what the .td files
3153   // describe.
3154   FunctionType *IFTy = IF->getFunctionType();
3155   bool IsVarArg = IFTy->isVarArg();
3156
3157   SmallVector<Intrinsic::IITDescriptor, 8> Table;
3158   getIntrinsicInfoTableEntries(ID, Table);
3159   ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
3160
3161   SmallVector<Type *, 4> ArgTys;
3162   Assert(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
3163          "Intrinsic has incorrect return type!", IF);
3164   for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
3165     Assert(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
3166            "Intrinsic has incorrect argument type!", IF);
3167
3168   // Verify if the intrinsic call matches the vararg property.
3169   if (IsVarArg)
3170     Assert(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
3171            "Intrinsic was not defined with variable arguments!", IF);
3172   else
3173     Assert(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
3174            "Callsite was not defined with variable arguments!", IF);
3175
3176   // All descriptors should be absorbed by now.
3177   Assert(TableRef.empty(), "Intrinsic has too few arguments!", IF);
3178
3179   // Now that we have the intrinsic ID and the actual argument types (and we
3180   // know they are legal for the intrinsic!) get the intrinsic name through the
3181   // usual means.  This allows us to verify the mangling of argument types into
3182   // the name.
3183   const std::string ExpectedName = Intrinsic::getName(ID, ArgTys);
3184   Assert(ExpectedName == IF->getName(),
3185          "Intrinsic name not mangled correctly for type arguments! "
3186          "Should be: " +
3187              ExpectedName,
3188          IF);
3189
3190   // If the intrinsic takes MDNode arguments, verify that they are either global
3191   // or are local to *this* function.
3192   for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
3193     if (auto *MD = dyn_cast<MetadataAsValue>(CI.getArgOperand(i)))
3194       visitMetadataAsValue(*MD, CI.getParent()->getParent());
3195
3196   switch (ID) {
3197   default:
3198     break;
3199   case Intrinsic::ctlz:  // llvm.ctlz
3200   case Intrinsic::cttz:  // llvm.cttz
3201     Assert(isa<ConstantInt>(CI.getArgOperand(1)),
3202            "is_zero_undef argument of bit counting intrinsics must be a "
3203            "constant int",
3204            &CI);
3205     break;
3206   case Intrinsic::dbg_declare: // llvm.dbg.declare
3207     Assert(isa<MetadataAsValue>(CI.getArgOperand(0)),
3208            "invalid llvm.dbg.declare intrinsic call 1", &CI);
3209     visitDbgIntrinsic("declare", cast<DbgDeclareInst>(*CI.getInstruction()));
3210     break;
3211   case Intrinsic::dbg_value: // llvm.dbg.value
3212     visitDbgIntrinsic("value", cast<DbgValueInst>(*CI.getInstruction()));
3213     break;
3214   case Intrinsic::memcpy:
3215   case Intrinsic::memmove:
3216   case Intrinsic::memset: {
3217     ConstantInt *AlignCI = dyn_cast<ConstantInt>(CI.getArgOperand(3));
3218     Assert(AlignCI,
3219            "alignment argument of memory intrinsics must be a constant int",
3220            &CI);
3221     const APInt &AlignVal = AlignCI->getValue();
3222     Assert(AlignCI->isZero() || AlignVal.isPowerOf2(),
3223            "alignment argument of memory intrinsics must be a power of 2", &CI);
3224     Assert(isa<ConstantInt>(CI.getArgOperand(4)),
3225            "isvolatile argument of memory intrinsics must be a constant int",
3226            &CI);
3227     break;
3228   }
3229   case Intrinsic::gcroot:
3230   case Intrinsic::gcwrite:
3231   case Intrinsic::gcread:
3232     if (ID == Intrinsic::gcroot) {
3233       AllocaInst *AI =
3234         dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
3235       Assert(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
3236       Assert(isa<Constant>(CI.getArgOperand(1)),
3237              "llvm.gcroot parameter #2 must be a constant.", &CI);
3238       if (!AI->getAllocatedType()->isPointerTy()) {
3239         Assert(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
3240                "llvm.gcroot parameter #1 must either be a pointer alloca, "
3241                "or argument #2 must be a non-null constant.",
3242                &CI);
3243       }
3244     }
3245
3246     Assert(CI.getParent()->getParent()->hasGC(),
3247            "Enclosing function does not use GC.", &CI);
3248     break;
3249   case Intrinsic::init_trampoline:
3250     Assert(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
3251            "llvm.init_trampoline parameter #2 must resolve to a function.",
3252            &CI);
3253     break;
3254   case Intrinsic::prefetch:
3255     Assert(isa<ConstantInt>(CI.getArgOperand(1)) &&
3256                isa<ConstantInt>(CI.getArgOperand(2)) &&
3257                cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
3258                cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
3259            "invalid arguments to llvm.prefetch", &CI);
3260     break;
3261   case Intrinsic::stackprotector:
3262     Assert(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
3263            "llvm.stackprotector parameter #2 must resolve to an alloca.", &CI);
3264     break;
3265   case Intrinsic::lifetime_start:
3266   case Intrinsic::lifetime_end:
3267   case Intrinsic::invariant_start:
3268     Assert(isa<ConstantInt>(CI.getArgOperand(0)),
3269            "size argument of memory use markers must be a constant integer",
3270            &CI);
3271     break;
3272   case Intrinsic::invariant_end:
3273     Assert(isa<ConstantInt>(CI.getArgOperand(1)),
3274            "llvm.invariant.end parameter #2 must be a constant integer", &CI);
3275     break;
3276
3277   case Intrinsic::frameescape: {
3278     BasicBlock *BB = CI.getParent();
3279     Assert(BB == &BB->getParent()->front(),
3280            "llvm.frameescape used outside of entry block", &CI);
3281     Assert(!SawFrameEscape,
3282            "multiple calls to llvm.frameescape in one function", &CI);
3283     for (Value *Arg : CI.args()) {
3284       if (isa<ConstantPointerNull>(Arg))
3285         continue; // Null values are allowed as placeholders.
3286       auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
3287       Assert(AI && AI->isStaticAlloca(),
3288              "llvm.frameescape only accepts static allocas", &CI);
3289     }
3290     FrameEscapeInfo[BB->getParent()].first = CI.getNumArgOperands();
3291     SawFrameEscape = true;
3292     break;
3293   }
3294   case Intrinsic::framerecover: {
3295     Value *FnArg = CI.getArgOperand(0)->stripPointerCasts();
3296     Function *Fn = dyn_cast<Function>(FnArg);
3297     Assert(Fn && !Fn->isDeclaration(),
3298            "llvm.framerecover first "
3299            "argument must be function defined in this module",
3300            &CI);
3301     auto *IdxArg = dyn_cast<ConstantInt>(CI.getArgOperand(2));
3302     Assert(IdxArg, "idx argument of llvm.framerecover must be a constant int",
3303            &CI);
3304     auto &Entry = FrameEscapeInfo[Fn];
3305     Entry.second = unsigned(
3306         std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
3307     break;
3308   }
3309
3310   case Intrinsic::experimental_gc_statepoint:
3311     Assert(!CI.isInlineAsm(),
3312            "gc.statepoint support for inline assembly unimplemented", &CI);
3313     Assert(CI.getParent()->getParent()->hasGC(),
3314            "Enclosing function does not use GC.", &CI);
3315
3316     VerifyStatepoint(ImmutableCallSite(CI));
3317     break;
3318   case Intrinsic::experimental_gc_result_int:
3319   case Intrinsic::experimental_gc_result_float:
3320   case Intrinsic::experimental_gc_result_ptr:
3321   case Intrinsic::experimental_gc_result: {
3322     Assert(CI.getParent()->getParent()->hasGC(),
3323            "Enclosing function does not use GC.", &CI);
3324     // Are we tied to a statepoint properly?
3325     CallSite StatepointCS(CI.getArgOperand(0));
3326     const Function *StatepointFn =
3327       StatepointCS.getInstruction() ? StatepointCS.getCalledFunction() : nullptr;
3328     Assert(StatepointFn && StatepointFn->isDeclaration() &&
3329                StatepointFn->getIntrinsicID() ==
3330                    Intrinsic::experimental_gc_statepoint,
3331            "gc.result operand #1 must be from a statepoint", &CI,
3332            CI.getArgOperand(0));
3333
3334     // Assert that result type matches wrapped callee.
3335     const Value *Target = StatepointCS.getArgument(2);
3336     const PointerType *PT = cast<PointerType>(Target->getType());
3337     const FunctionType *TargetFuncType =
3338       cast<FunctionType>(PT->getElementType());
3339     Assert(CI.getType() == TargetFuncType->getReturnType(),
3340            "gc.result result type does not match wrapped callee", &CI);
3341     break;
3342   }
3343   case Intrinsic::experimental_gc_relocate: {
3344     Assert(CI.getNumArgOperands() == 3, "wrong number of arguments", &CI);
3345
3346     // Check that this relocate is correctly tied to the statepoint
3347
3348     // This is case for relocate on the unwinding path of an invoke statepoint
3349     if (ExtractValueInst *ExtractValue =
3350           dyn_cast<ExtractValueInst>(CI.getArgOperand(0))) {
3351       Assert(isa<LandingPadInst>(ExtractValue->getAggregateOperand()),
3352              "gc relocate on unwind path incorrectly linked to the statepoint",
3353              &CI);
3354
3355       const BasicBlock *InvokeBB =
3356         ExtractValue->getParent()->getUniquePredecessor();
3357
3358       // Landingpad relocates should have only one predecessor with invoke
3359       // statepoint terminator
3360       Assert(InvokeBB, "safepoints should have unique landingpads",
3361              ExtractValue->getParent());
3362       Assert(InvokeBB->getTerminator(), "safepoint block should be well formed",
3363              InvokeBB);
3364       Assert(isStatepoint(InvokeBB->getTerminator()),
3365              "gc relocate should be linked to a statepoint", InvokeBB);
3366     }
3367     else {
3368       // In all other cases relocate should be tied to the statepoint directly.
3369       // This covers relocates on a normal return path of invoke statepoint and
3370       // relocates of a call statepoint
3371       auto Token = CI.getArgOperand(0);
3372       Assert(isa<Instruction>(Token) && isStatepoint(cast<Instruction>(Token)),
3373              "gc relocate is incorrectly tied to the statepoint", &CI, Token);
3374     }
3375
3376     // Verify rest of the relocate arguments
3377
3378     GCRelocateOperands Ops(CI);
3379     ImmutableCallSite StatepointCS(Ops.getStatepoint());
3380
3381     // Both the base and derived must be piped through the safepoint
3382     Value* Base = CI.getArgOperand(1);
3383     Assert(isa<ConstantInt>(Base),
3384            "gc.relocate operand #2 must be integer offset", &CI);
3385
3386     Value* Derived = CI.getArgOperand(2);
3387     Assert(isa<ConstantInt>(Derived),
3388            "gc.relocate operand #3 must be integer offset", &CI);
3389
3390     const int BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
3391     const int DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
3392     // Check the bounds
3393     Assert(0 <= BaseIndex && BaseIndex < (int)StatepointCS.arg_size(),
3394            "gc.relocate: statepoint base index out of bounds", &CI);
3395     Assert(0 <= DerivedIndex && DerivedIndex < (int)StatepointCS.arg_size(),
3396            "gc.relocate: statepoint derived index out of bounds", &CI);
3397
3398     // Check that BaseIndex and DerivedIndex fall within the 'gc parameters'
3399     // section of the statepoint's argument
3400     Assert(StatepointCS.arg_size() > 0,
3401            "gc.statepoint: insufficient arguments");
3402     Assert(isa<ConstantInt>(StatepointCS.getArgument(3)),
3403            "gc.statement: number of call arguments must be constant integer");
3404     const unsigned NumCallArgs =
3405         cast<ConstantInt>(StatepointCS.getArgument(3))->getZExtValue();
3406     Assert(StatepointCS.arg_size() > NumCallArgs + 5,
3407            "gc.statepoint: mismatch in number of call arguments");
3408     Assert(isa<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 5)),
3409            "gc.statepoint: number of transition arguments must be "
3410            "a constant integer");
3411     const int NumTransitionArgs =
3412         cast<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 5))
3413             ->getZExtValue();
3414     const int DeoptArgsStart = 4 + NumCallArgs + 1 + NumTransitionArgs + 1;
3415     Assert(isa<ConstantInt>(StatepointCS.getArgument(DeoptArgsStart)),
3416            "gc.statepoint: number of deoptimization arguments must be "
3417            "a constant integer");
3418     const int NumDeoptArgs =
3419       cast<ConstantInt>(StatepointCS.getArgument(DeoptArgsStart))->getZExtValue();
3420     const int GCParamArgsStart = DeoptArgsStart + 1 + NumDeoptArgs;
3421     const int GCParamArgsEnd = StatepointCS.arg_size();
3422     Assert(GCParamArgsStart <= BaseIndex && BaseIndex < GCParamArgsEnd,
3423            "gc.relocate: statepoint base index doesn't fall within the "
3424            "'gc parameters' section of the statepoint call",
3425            &CI);
3426     Assert(GCParamArgsStart <= DerivedIndex && DerivedIndex < GCParamArgsEnd,
3427            "gc.relocate: statepoint derived index doesn't fall within the "
3428            "'gc parameters' section of the statepoint call",
3429            &CI);
3430
3431     // Relocated value must be a pointer type, but gc_relocate does not need to return the
3432     // same pointer type as the relocated pointer. It can be casted to the correct type later
3433     // if it's desired. However, they must have the same address space.
3434     GCRelocateOperands Operands(CI);
3435     Assert(Operands.getDerivedPtr()->getType()->isPointerTy(),
3436            "gc.relocate: relocated value must be a gc pointer", &CI);
3437
3438     // gc_relocate return type must be a pointer type, and is verified earlier in
3439     // VerifyIntrinsicType().
3440     Assert(cast<PointerType>(CI.getType())->getAddressSpace() ==
3441            cast<PointerType>(Operands.getDerivedPtr()->getType())->getAddressSpace(),
3442            "gc.relocate: relocating a pointer shouldn't change its address space", &CI);
3443     break;
3444   }
3445   };
3446 }
3447
3448 /// \brief Carefully grab the subprogram from a local scope.
3449 ///
3450 /// This carefully grabs the subprogram from a local scope, avoiding the
3451 /// built-in assertions that would typically fire.
3452 static DISubprogram *getSubprogram(Metadata *LocalScope) {
3453   if (!LocalScope)
3454     return nullptr;
3455
3456   if (auto *SP = dyn_cast<DISubprogram>(LocalScope))
3457     return SP;
3458
3459   if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope))
3460     return getSubprogram(LB->getRawScope());
3461
3462   // Just return null; broken scope chains are checked elsewhere.
3463   assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope");
3464   return nullptr;
3465 }
3466
3467 template <class DbgIntrinsicTy>
3468 void Verifier::visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII) {
3469   auto *MD = cast<MetadataAsValue>(DII.getArgOperand(0))->getMetadata();
3470   Assert(isa<ValueAsMetadata>(MD) ||
3471              (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()),
3472          "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD);
3473   Assert(isa<DILocalVariable>(DII.getRawVariable()),
3474          "invalid llvm.dbg." + Kind + " intrinsic variable", &DII,
3475          DII.getRawVariable());
3476   Assert(isa<DIExpression>(DII.getRawExpression()),
3477          "invalid llvm.dbg." + Kind + " intrinsic expression", &DII,
3478          DII.getRawExpression());
3479
3480   // Ignore broken !dbg attachments; they're checked elsewhere.
3481   if (MDNode *N = DII.getDebugLoc().getAsMDNode())
3482     if (!isa<DILocation>(N))
3483       return;
3484
3485   BasicBlock *BB = DII.getParent();
3486   Function *F = BB ? BB->getParent() : nullptr;
3487
3488   // The scopes for variables and !dbg attachments must agree.
3489   DILocalVariable *Var = DII.getVariable();
3490   DILocation *Loc = DII.getDebugLoc();
3491   Assert(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment",
3492          &DII, BB, F);
3493
3494   DISubprogram *VarSP = getSubprogram(Var->getRawScope());
3495   DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
3496   if (!VarSP || !LocSP)
3497     return; // Broken scope chains are checked elsewhere.
3498
3499   Assert(VarSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind +
3500                              " variable and !dbg attachment",
3501          &DII, BB, F, Var, Var->getScope()->getSubprogram(), Loc,
3502          Loc->getScope()->getSubprogram());
3503 }
3504
3505 template <class MapTy>
3506 static uint64_t getVariableSize(const DILocalVariable &V, const MapTy &Map) {
3507   // Be careful of broken types (checked elsewhere).
3508   const Metadata *RawType = V.getRawType();
3509   while (RawType) {
3510     // Try to get the size directly.
3511     if (auto *T = dyn_cast<DIType>(RawType))
3512       if (uint64_t Size = T->getSizeInBits())
3513         return Size;
3514
3515     if (auto *DT = dyn_cast<DIDerivedType>(RawType)) {
3516       // Look at the base type.
3517       RawType = DT->getRawBaseType();
3518       continue;
3519     }
3520
3521     if (auto *S = dyn_cast<MDString>(RawType)) {
3522       // Don't error on missing types (checked elsewhere).
3523       RawType = Map.lookup(S);
3524       continue;
3525     }
3526
3527     // Missing type or size.
3528     break;
3529   }
3530
3531   // Fail gracefully.
3532   return 0;
3533 }
3534
3535 template <class MapTy>
3536 void Verifier::verifyBitPieceExpression(const DbgInfoIntrinsic &I,
3537                                         const MapTy &TypeRefs) {
3538   DILocalVariable *V;
3539   DIExpression *E;
3540   if (auto *DVI = dyn_cast<DbgValueInst>(&I)) {
3541     V = dyn_cast_or_null<DILocalVariable>(DVI->getRawVariable());
3542     E = dyn_cast_or_null<DIExpression>(DVI->getRawExpression());
3543   } else {
3544     auto *DDI = cast<DbgDeclareInst>(&I);
3545     V = dyn_cast_or_null<DILocalVariable>(DDI->getRawVariable());
3546     E = dyn_cast_or_null<DIExpression>(DDI->getRawExpression());
3547   }
3548
3549   // We don't know whether this intrinsic verified correctly.
3550   if (!V || !E || !E->isValid())
3551     return;
3552
3553   // Nothing to do if this isn't a bit piece expression.
3554   if (!E->isBitPiece())
3555     return;
3556
3557   // The frontend helps out GDB by emitting the members of local anonymous
3558   // unions as artificial local variables with shared storage. When SROA splits
3559   // the storage for artificial local variables that are smaller than the entire
3560   // union, the overhang piece will be outside of the allotted space for the
3561   // variable and this check fails.
3562   // FIXME: Remove this check as soon as clang stops doing this; it hides bugs.
3563   if (V->isArtificial())
3564     return;
3565
3566   // If there's no size, the type is broken, but that should be checked
3567   // elsewhere.
3568   uint64_t VarSize = getVariableSize(*V, TypeRefs);
3569   if (!VarSize)
3570     return;
3571
3572   unsigned PieceSize = E->getBitPieceSize();
3573   unsigned PieceOffset = E->getBitPieceOffset();
3574   Assert(PieceSize + PieceOffset <= VarSize,
3575          "piece is larger than or outside of variable", &I, V, E);
3576   Assert(PieceSize != VarSize, "piece covers entire variable", &I, V, E);
3577 }
3578
3579 void Verifier::visitUnresolvedTypeRef(const MDString *S, const MDNode *N) {
3580   // This is in its own function so we get an error for each bad type ref (not
3581   // just the first).
3582   Assert(false, "unresolved type ref", S, N);
3583 }
3584
3585 void Verifier::verifyTypeRefs() {
3586   auto *CUs = M->getNamedMetadata("llvm.dbg.cu");
3587   if (!CUs)
3588     return;
3589
3590   // Visit all the compile units again to map the type references.
3591   SmallDenseMap<const MDString *, const DIType *, 32> TypeRefs;
3592   for (auto *CU : CUs->operands())
3593     if (auto Ts = cast<DICompileUnit>(CU)->getRetainedTypes())
3594       for (DIType *Op : Ts)
3595         if (auto *T = dyn_cast<DICompositeType>(Op))
3596           if (auto *S = T->getRawIdentifier()) {
3597             UnresolvedTypeRefs.erase(S);
3598             TypeRefs.insert(std::make_pair(S, T));
3599           }
3600
3601   // Verify debug info intrinsic bit piece expressions.  This needs a second
3602   // pass through the intructions, since we haven't built TypeRefs yet when
3603   // verifying functions, and simply queuing the DbgInfoIntrinsics to evaluate
3604   // later/now would queue up some that could be later deleted.
3605   for (const Function &F : *M)
3606     for (const BasicBlock &BB : F)
3607       for (const Instruction &I : BB)
3608         if (auto *DII = dyn_cast<DbgInfoIntrinsic>(&I))
3609           verifyBitPieceExpression(*DII, TypeRefs);
3610
3611   // Return early if all typerefs were resolved.
3612   if (UnresolvedTypeRefs.empty())
3613     return;
3614
3615   // Sort the unresolved references by name so the output is deterministic.
3616   typedef std::pair<const MDString *, const MDNode *> TypeRef;
3617   SmallVector<TypeRef, 32> Unresolved(UnresolvedTypeRefs.begin(),
3618                                       UnresolvedTypeRefs.end());
3619   std::sort(Unresolved.begin(), Unresolved.end(),
3620             [](const TypeRef &LHS, const TypeRef &RHS) {
3621     return LHS.first->getString() < RHS.first->getString();
3622   });
3623
3624   // Visit the unresolved refs (printing out the errors).
3625   for (const TypeRef &TR : Unresolved)
3626     visitUnresolvedTypeRef(TR.first, TR.second);
3627 }
3628
3629 //===----------------------------------------------------------------------===//
3630 //  Implement the public interfaces to this file...
3631 //===----------------------------------------------------------------------===//
3632
3633 bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
3634   Function &F = const_cast<Function &>(f);
3635   assert(!F.isDeclaration() && "Cannot verify external functions");
3636
3637   raw_null_ostream NullStr;
3638   Verifier V(OS ? *OS : NullStr);
3639
3640   // Note that this function's return value is inverted from what you would
3641   // expect of a function called "verify".
3642   return !V.verify(F);
3643 }
3644
3645 bool llvm::verifyModule(const Module &M, raw_ostream *OS) {
3646   raw_null_ostream NullStr;
3647   Verifier V(OS ? *OS : NullStr);
3648
3649   bool Broken = false;
3650   for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
3651     if (!I->isDeclaration() && !I->isMaterializable())
3652       Broken |= !V.verify(*I);
3653
3654   // Note that this function's return value is inverted from what you would
3655   // expect of a function called "verify".
3656   return !V.verify(M) || Broken;
3657 }
3658
3659 namespace {
3660 struct VerifierLegacyPass : public FunctionPass {
3661   static char ID;
3662
3663   Verifier V;
3664   bool FatalErrors;
3665
3666   VerifierLegacyPass() : FunctionPass(ID), V(dbgs()), FatalErrors(true) {
3667     initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
3668   }
3669   explicit VerifierLegacyPass(bool FatalErrors)
3670       : FunctionPass(ID), V(dbgs()), FatalErrors(FatalErrors) {
3671     initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
3672   }
3673
3674   bool runOnFunction(Function &F) override {
3675     if (!V.verify(F) && FatalErrors)
3676       report_fatal_error("Broken function found, compilation aborted!");
3677
3678     return false;
3679   }
3680
3681   bool doFinalization(Module &M) override {
3682     if (!V.verify(M) && FatalErrors)
3683       report_fatal_error("Broken module found, compilation aborted!");
3684
3685     return false;
3686   }
3687
3688   void getAnalysisUsage(AnalysisUsage &AU) const override {
3689     AU.setPreservesAll();
3690   }
3691 };
3692 }
3693
3694 char VerifierLegacyPass::ID = 0;
3695 INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
3696
3697 FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
3698   return new VerifierLegacyPass(FatalErrors);
3699 }
3700
3701 PreservedAnalyses VerifierPass::run(Module &M) {
3702   if (verifyModule(M, &dbgs()) && FatalErrors)
3703     report_fatal_error("Broken module found, compilation aborted!");
3704
3705   return PreservedAnalyses::all();
3706 }
3707
3708 PreservedAnalyses VerifierPass::run(Function &F) {
3709   if (verifyFunction(F, &dbgs()) && FatalErrors)
3710     report_fatal_error("Broken function found, compilation aborted!");
3711
3712   return PreservedAnalyses::all();
3713 }