Convert StringMapEntry::Create to use StringRef instead of start/end pointers. Simpli...
[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/Pass.h"
72 #include "llvm/Support/CommandLine.h"
73 #include "llvm/Support/Debug.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/raw_ostream.h"
76 #include <algorithm>
77 #include <cstdarg>
78 using namespace llvm;
79
80 static cl::opt<bool> VerifyDebugInfo("verify-debug-info", cl::init(false));
81
82 namespace {
83 struct VerifierSupport {
84   raw_ostream &OS;
85   const Module *M;
86
87   /// \brief Track the brokenness of the module while recursively visiting.
88   bool Broken;
89
90   explicit VerifierSupport(raw_ostream &OS)
91       : OS(OS), M(nullptr), Broken(false) {}
92
93   void WriteValue(const Value *V) {
94     if (!V)
95       return;
96     if (isa<Instruction>(V)) {
97       OS << *V << '\n';
98     } else {
99       V->printAsOperand(OS, true, M);
100       OS << '\n';
101     }
102   }
103
104   void WriteType(Type *T) {
105     if (!T)
106       return;
107     OS << ' ' << *T;
108   }
109
110   // CheckFailed - A check failed, so print out the condition and the message
111   // that failed.  This provides a nice place to put a breakpoint if you want
112   // to see why something is not correct.
113   void CheckFailed(const Twine &Message, const Value *V1 = nullptr,
114                    const Value *V2 = nullptr, const Value *V3 = nullptr,
115                    const Value *V4 = nullptr) {
116     OS << Message.str() << "\n";
117     WriteValue(V1);
118     WriteValue(V2);
119     WriteValue(V3);
120     WriteValue(V4);
121     Broken = true;
122   }
123
124   void CheckFailed(const Twine &Message, const Value *V1, Type *T2,
125                    const Value *V3 = nullptr) {
126     OS << Message.str() << "\n";
127     WriteValue(V1);
128     WriteType(T2);
129     WriteValue(V3);
130     Broken = true;
131   }
132
133   void CheckFailed(const Twine &Message, Type *T1, Type *T2 = nullptr,
134                    Type *T3 = nullptr) {
135     OS << Message.str() << "\n";
136     WriteType(T1);
137     WriteType(T2);
138     WriteType(T3);
139     Broken = true;
140   }
141 };
142 class Verifier : public InstVisitor<Verifier>, VerifierSupport {
143   friend class InstVisitor<Verifier>;
144
145   LLVMContext *Context;
146   const DataLayout *DL;
147   DominatorTree DT;
148
149   /// \brief When verifying a basic block, keep track of all of the
150   /// instructions we have seen so far.
151   ///
152   /// This allows us to do efficient dominance checks for the case when an
153   /// instruction has an operand that is an instruction in the same block.
154   SmallPtrSet<Instruction *, 16> InstsInThisBlock;
155
156   /// \brief Keep track of the metadata nodes that have been checked already.
157   SmallPtrSet<MDNode *, 32> MDNodes;
158
159   /// \brief The personality function referenced by the LandingPadInsts.
160   /// All LandingPadInsts within the same function must use the same
161   /// personality function.
162   const Value *PersonalityFn;
163
164 public:
165   explicit Verifier(raw_ostream &OS = dbgs())
166       : VerifierSupport(OS), Context(nullptr), DL(nullptr),
167         PersonalityFn(nullptr) {}
168
169   bool verify(const Function &F) {
170     M = F.getParent();
171     Context = &M->getContext();
172
173     // First ensure the function is well-enough formed to compute dominance
174     // information.
175     if (F.empty()) {
176       OS << "Function '" << F.getName()
177          << "' does not contain an entry block!\n";
178       return false;
179     }
180     for (Function::const_iterator I = F.begin(), E = F.end(); I != E; ++I) {
181       if (I->empty() || !I->back().isTerminator()) {
182         OS << "Basic Block in function '" << F.getName()
183            << "' does not have terminator!\n";
184         I->printAsOperand(OS, true);
185         OS << "\n";
186         return false;
187       }
188     }
189
190     // Now directly compute a dominance tree. We don't rely on the pass
191     // manager to provide this as it isolates us from a potentially
192     // out-of-date dominator tree and makes it significantly more complex to
193     // run this code outside of a pass manager.
194     // FIXME: It's really gross that we have to cast away constness here.
195     DT.recalculate(const_cast<Function &>(F));
196
197     Broken = false;
198     // FIXME: We strip const here because the inst visitor strips const.
199     visit(const_cast<Function &>(F));
200     InstsInThisBlock.clear();
201     PersonalityFn = nullptr;
202
203     return !Broken;
204   }
205
206   bool verify(const Module &M) {
207     this->M = &M;
208     Context = &M.getContext();
209     Broken = false;
210
211     // Scan through, checking all of the external function's linkage now...
212     for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
213       visitGlobalValue(*I);
214
215       // Check to make sure function prototypes are okay.
216       if (I->isDeclaration())
217         visitFunction(*I);
218     }
219
220     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
221          I != E; ++I)
222       visitGlobalVariable(*I);
223
224     for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
225          I != E; ++I)
226       visitGlobalAlias(*I);
227
228     for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
229                                                E = M.named_metadata_end();
230          I != E; ++I)
231       visitNamedMDNode(*I);
232
233     visitModuleFlags(M);
234     visitModuleIdents(M);
235
236     return !Broken;
237   }
238
239 private:
240   // Verification methods...
241   void visitGlobalValue(const GlobalValue &GV);
242   void visitGlobalVariable(const GlobalVariable &GV);
243   void visitGlobalAlias(const GlobalAlias &GA);
244   void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
245   void visitAliaseeSubExpr(SmallPtrSet<const GlobalAlias *, 4> &Visited,
246                            const GlobalAlias &A, const Constant &C);
247   void visitNamedMDNode(const NamedMDNode &NMD);
248   void visitMDNode(MDNode &MD, Function *F);
249   void visitModuleIdents(const Module &M);
250   void visitModuleFlags(const Module &M);
251   void visitModuleFlag(const MDNode *Op,
252                        DenseMap<const MDString *, const MDNode *> &SeenIDs,
253                        SmallVectorImpl<const MDNode *> &Requirements);
254   void visitFunction(const Function &F);
255   void visitBasicBlock(BasicBlock &BB);
256
257   // InstVisitor overrides...
258   using InstVisitor<Verifier>::visit;
259   void visit(Instruction &I);
260
261   void visitTruncInst(TruncInst &I);
262   void visitZExtInst(ZExtInst &I);
263   void visitSExtInst(SExtInst &I);
264   void visitFPTruncInst(FPTruncInst &I);
265   void visitFPExtInst(FPExtInst &I);
266   void visitFPToUIInst(FPToUIInst &I);
267   void visitFPToSIInst(FPToSIInst &I);
268   void visitUIToFPInst(UIToFPInst &I);
269   void visitSIToFPInst(SIToFPInst &I);
270   void visitIntToPtrInst(IntToPtrInst &I);
271   void visitPtrToIntInst(PtrToIntInst &I);
272   void visitBitCastInst(BitCastInst &I);
273   void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
274   void visitPHINode(PHINode &PN);
275   void visitBinaryOperator(BinaryOperator &B);
276   void visitICmpInst(ICmpInst &IC);
277   void visitFCmpInst(FCmpInst &FC);
278   void visitExtractElementInst(ExtractElementInst &EI);
279   void visitInsertElementInst(InsertElementInst &EI);
280   void visitShuffleVectorInst(ShuffleVectorInst &EI);
281   void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
282   void visitCallInst(CallInst &CI);
283   void visitInvokeInst(InvokeInst &II);
284   void visitGetElementPtrInst(GetElementPtrInst &GEP);
285   void visitLoadInst(LoadInst &LI);
286   void visitStoreInst(StoreInst &SI);
287   void verifyDominatesUse(Instruction &I, unsigned i);
288   void visitInstruction(Instruction &I);
289   void visitTerminatorInst(TerminatorInst &I);
290   void visitBranchInst(BranchInst &BI);
291   void visitReturnInst(ReturnInst &RI);
292   void visitSwitchInst(SwitchInst &SI);
293   void visitIndirectBrInst(IndirectBrInst &BI);
294   void visitSelectInst(SelectInst &SI);
295   void visitUserOp1(Instruction &I);
296   void visitUserOp2(Instruction &I) { visitUserOp1(I); }
297   void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
298   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
299   void visitAtomicRMWInst(AtomicRMWInst &RMWI);
300   void visitFenceInst(FenceInst &FI);
301   void visitAllocaInst(AllocaInst &AI);
302   void visitExtractValueInst(ExtractValueInst &EVI);
303   void visitInsertValueInst(InsertValueInst &IVI);
304   void visitLandingPadInst(LandingPadInst &LPI);
305
306   void VerifyCallSite(CallSite CS);
307   void verifyMustTailCall(CallInst &CI);
308   bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT,
309                         unsigned ArgNo, std::string &Suffix);
310   bool VerifyIntrinsicType(Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
311                            SmallVectorImpl<Type *> &ArgTys);
312   bool VerifyIntrinsicIsVarArg(bool isVarArg,
313                                ArrayRef<Intrinsic::IITDescriptor> &Infos);
314   bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params);
315   void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx, bool isFunction,
316                             const Value *V);
317   void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
318                             bool isReturnValue, const Value *V);
319   void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
320                            const Value *V);
321
322   void VerifyBitcastType(const Value *V, Type *DestTy, Type *SrcTy);
323   void VerifyConstantExprBitcastType(const ConstantExpr *CE);
324 };
325 class DebugInfoVerifier : public VerifierSupport {
326 public:
327   explicit DebugInfoVerifier(raw_ostream &OS = dbgs()) : VerifierSupport(OS) {}
328
329   bool verify(const Module &M) {
330     this->M = &M;
331     verifyDebugInfo();
332     return !Broken;
333   }
334
335 private:
336   void verifyDebugInfo();
337   void processInstructions(DebugInfoFinder &Finder);
338   void processCallInst(DebugInfoFinder &Finder, const CallInst &CI);
339 };
340 } // End anonymous namespace
341
342 // Assert - We know that cond should be true, if not print an error message.
343 #define Assert(C, M) \
344   do { if (!(C)) { CheckFailed(M); return; } } while (0)
345 #define Assert1(C, M, V1) \
346   do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
347 #define Assert2(C, M, V1, V2) \
348   do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
349 #define Assert3(C, M, V1, V2, V3) \
350   do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
351 #define Assert4(C, M, V1, V2, V3, V4) \
352   do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
353
354 void Verifier::visit(Instruction &I) {
355   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
356     Assert1(I.getOperand(i) != nullptr, "Operand is null", &I);
357   InstVisitor<Verifier>::visit(I);
358 }
359
360
361 void Verifier::visitGlobalValue(const GlobalValue &GV) {
362   Assert1(!GV.isDeclaration() || GV.isMaterializable() ||
363               GV.hasExternalLinkage() || GV.hasExternalWeakLinkage(),
364           "Global is external, but doesn't have external or weak linkage!",
365           &GV);
366
367   Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
368           "Only global variables can have appending linkage!", &GV);
369
370   if (GV.hasAppendingLinkage()) {
371     const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
372     Assert1(GVar && GVar->getType()->getElementType()->isArrayTy(),
373             "Only global arrays can have appending linkage!", GVar);
374   }
375 }
376
377 void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
378   if (GV.hasInitializer()) {
379     Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
380             "Global variable initializer type does not match global "
381             "variable type!", &GV);
382
383     // If the global has common linkage, it must have a zero initializer and
384     // cannot be constant.
385     if (GV.hasCommonLinkage()) {
386       Assert1(GV.getInitializer()->isNullValue(),
387               "'common' global must have a zero initializer!", &GV);
388       Assert1(!GV.isConstant(), "'common' global may not be marked constant!",
389               &GV);
390     }
391   } else {
392     Assert1(GV.hasExternalLinkage() || GV.hasExternalWeakLinkage(),
393             "invalid linkage type for global declaration", &GV);
394   }
395
396   if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
397                        GV.getName() == "llvm.global_dtors")) {
398     Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
399             "invalid linkage for intrinsic global variable", &GV);
400     // Don't worry about emitting an error for it not being an array,
401     // visitGlobalValue will complain on appending non-array.
402     if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType()->getElementType())) {
403       StructType *STy = dyn_cast<StructType>(ATy->getElementType());
404       PointerType *FuncPtrTy =
405           FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
406       // FIXME: Reject the 2-field form in LLVM 4.0.
407       Assert1(STy && (STy->getNumElements() == 2 ||
408                       STy->getNumElements() == 3) &&
409               STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
410               STy->getTypeAtIndex(1) == FuncPtrTy,
411               "wrong type for intrinsic global variable", &GV);
412       if (STy->getNumElements() == 3) {
413         Type *ETy = STy->getTypeAtIndex(2);
414         Assert1(ETy->isPointerTy() &&
415                     cast<PointerType>(ETy)->getElementType()->isIntegerTy(8),
416                 "wrong type for intrinsic global variable", &GV);
417       }
418     }
419   }
420
421   if (GV.hasName() && (GV.getName() == "llvm.used" ||
422                        GV.getName() == "llvm.compiler.used")) {
423     Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
424             "invalid linkage for intrinsic global variable", &GV);
425     Type *GVType = GV.getType()->getElementType();
426     if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
427       PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
428       Assert1(PTy, "wrong type for intrinsic global variable", &GV);
429       if (GV.hasInitializer()) {
430         const Constant *Init = GV.getInitializer();
431         const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
432         Assert1(InitArray, "wrong initalizer for intrinsic global variable",
433                 Init);
434         for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) {
435           Value *V = Init->getOperand(i)->stripPointerCastsNoFollowAliases();
436           Assert1(
437               isa<GlobalVariable>(V) || isa<Function>(V) || isa<GlobalAlias>(V),
438               "invalid llvm.used member", V);
439           Assert1(V->hasName(), "members of llvm.used must be named", V);
440         }
441       }
442     }
443   }
444
445   Assert1(!GV.hasDLLImportStorageClass() ||
446           (GV.isDeclaration() && GV.hasExternalLinkage()) ||
447           GV.hasAvailableExternallyLinkage(),
448           "Global is marked as dllimport, but not external", &GV);
449
450   if (!GV.hasInitializer()) {
451     visitGlobalValue(GV);
452     return;
453   }
454
455   // Walk any aggregate initializers looking for bitcasts between address spaces
456   SmallPtrSet<const Value *, 4> Visited;
457   SmallVector<const Value *, 4> WorkStack;
458   WorkStack.push_back(cast<Value>(GV.getInitializer()));
459
460   while (!WorkStack.empty()) {
461     const Value *V = WorkStack.pop_back_val();
462     if (!Visited.insert(V))
463       continue;
464
465     if (const User *U = dyn_cast<User>(V)) {
466       for (unsigned I = 0, N = U->getNumOperands(); I != N; ++I)
467         WorkStack.push_back(U->getOperand(I));
468     }
469
470     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
471       VerifyConstantExprBitcastType(CE);
472       if (Broken)
473         return;
474     }
475   }
476
477   visitGlobalValue(GV);
478 }
479
480 void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
481   SmallPtrSet<const GlobalAlias*, 4> Visited;
482   Visited.insert(&GA);
483   visitAliaseeSubExpr(Visited, GA, C);
484 }
485
486 void Verifier::visitAliaseeSubExpr(SmallPtrSet<const GlobalAlias *, 4> &Visited,
487                                    const GlobalAlias &GA, const Constant &C) {
488   if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
489     Assert1(!GV->isDeclaration(), "Alias must point to a definition", &GA);
490
491     if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
492       Assert1(Visited.insert(GA2), "Aliases cannot form a cycle", &GA);
493
494       Assert1(!GA2->mayBeOverridden(), "Alias cannot point to a weak alias",
495               &GA);
496     }
497   }
498
499   if (const auto *CE = dyn_cast<ConstantExpr>(&C))
500     VerifyConstantExprBitcastType(CE);
501
502   for (const Use &U : C.operands()) {
503     Value *V = &*U;
504     if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
505       visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
506     else if (const auto *C2 = dyn_cast<Constant>(V))
507       visitAliaseeSubExpr(Visited, GA, *C2);
508   }
509 }
510
511 void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
512   Assert1(!GA.getName().empty(),
513           "Alias name cannot be empty!", &GA);
514   Assert1(GlobalAlias::isValidLinkage(GA.getLinkage()),
515           "Alias should have external or external weak linkage!", &GA);
516   const Constant *Aliasee = GA.getAliasee();
517   Assert1(Aliasee, "Aliasee cannot be NULL!", &GA);
518   Assert1(GA.getType() == Aliasee->getType(),
519           "Alias and aliasee types should match!", &GA);
520
521   Assert1(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
522           "Aliasee should be either GlobalValue or ConstantExpr", &GA);
523
524   visitAliaseeSubExpr(GA, *Aliasee);
525
526   visitGlobalValue(GA);
527 }
528
529 void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
530   for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
531     MDNode *MD = NMD.getOperand(i);
532     if (!MD)
533       continue;
534
535     Assert1(!MD->isFunctionLocal(),
536             "Named metadata operand cannot be function local!", MD);
537     visitMDNode(*MD, nullptr);
538   }
539 }
540
541 void Verifier::visitMDNode(MDNode &MD, Function *F) {
542   // Only visit each node once.  Metadata can be mutually recursive, so this
543   // avoids infinite recursion here, as well as being an optimization.
544   if (!MDNodes.insert(&MD))
545     return;
546
547   for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
548     Value *Op = MD.getOperand(i);
549     if (!Op)
550       continue;
551     if (isa<Constant>(Op) || isa<MDString>(Op))
552       continue;
553     if (MDNode *N = dyn_cast<MDNode>(Op)) {
554       Assert2(MD.isFunctionLocal() || !N->isFunctionLocal(),
555               "Global metadata operand cannot be function local!", &MD, N);
556       visitMDNode(*N, F);
557       continue;
558     }
559     Assert2(MD.isFunctionLocal(), "Invalid operand for global metadata!", &MD, Op);
560
561     // If this was an instruction, bb, or argument, verify that it is in the
562     // function that we expect.
563     Function *ActualF = nullptr;
564     if (Instruction *I = dyn_cast<Instruction>(Op))
565       ActualF = I->getParent()->getParent();
566     else if (BasicBlock *BB = dyn_cast<BasicBlock>(Op))
567       ActualF = BB->getParent();
568     else if (Argument *A = dyn_cast<Argument>(Op))
569       ActualF = A->getParent();
570     assert(ActualF && "Unimplemented function local metadata case!");
571
572     Assert2(ActualF == F, "function-local metadata used in wrong function",
573             &MD, Op);
574   }
575 }
576
577 void Verifier::visitModuleIdents(const Module &M) {
578   const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
579   if (!Idents) 
580     return;
581   
582   // llvm.ident takes a list of metadata entry. Each entry has only one string.
583   // Scan each llvm.ident entry and make sure that this requirement is met.
584   for (unsigned i = 0, e = Idents->getNumOperands(); i != e; ++i) {
585     const MDNode *N = Idents->getOperand(i);
586     Assert1(N->getNumOperands() == 1,
587             "incorrect number of operands in llvm.ident metadata", N);
588     Assert1(isa<MDString>(N->getOperand(0)),
589             ("invalid value for llvm.ident metadata entry operand"
590              "(the operand should be a string)"),
591             N->getOperand(0));
592   } 
593 }
594
595 void Verifier::visitModuleFlags(const Module &M) {
596   const NamedMDNode *Flags = M.getModuleFlagsMetadata();
597   if (!Flags) return;
598
599   // Scan each flag, and track the flags and requirements.
600   DenseMap<const MDString*, const MDNode*> SeenIDs;
601   SmallVector<const MDNode*, 16> Requirements;
602   for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) {
603     visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements);
604   }
605
606   // Validate that the requirements in the module are valid.
607   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
608     const MDNode *Requirement = Requirements[I];
609     const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
610     const Value *ReqValue = Requirement->getOperand(1);
611
612     const MDNode *Op = SeenIDs.lookup(Flag);
613     if (!Op) {
614       CheckFailed("invalid requirement on flag, flag is not present in module",
615                   Flag);
616       continue;
617     }
618
619     if (Op->getOperand(2) != ReqValue) {
620       CheckFailed(("invalid requirement on flag, "
621                    "flag does not have the required value"),
622                   Flag);
623       continue;
624     }
625   }
626 }
627
628 void
629 Verifier::visitModuleFlag(const MDNode *Op,
630                           DenseMap<const MDString *, const MDNode *> &SeenIDs,
631                           SmallVectorImpl<const MDNode *> &Requirements) {
632   // Each module flag should have three arguments, the merge behavior (a
633   // constant int), the flag ID (an MDString), and the value.
634   Assert1(Op->getNumOperands() == 3,
635           "incorrect number of operands in module flag", Op);
636   ConstantInt *Behavior = dyn_cast<ConstantInt>(Op->getOperand(0));
637   MDString *ID = dyn_cast<MDString>(Op->getOperand(1));
638   Assert1(Behavior,
639           "invalid behavior operand in module flag (expected constant integer)",
640           Op->getOperand(0));
641   unsigned BehaviorValue = Behavior->getZExtValue();
642   Assert1(ID,
643           "invalid ID operand in module flag (expected metadata string)",
644           Op->getOperand(1));
645
646   // Sanity check the values for behaviors with additional requirements.
647   switch (BehaviorValue) {
648   default:
649     Assert1(false,
650             "invalid behavior operand in module flag (unexpected constant)",
651             Op->getOperand(0));
652     break;
653
654   case Module::Error:
655   case Module::Warning:
656   case Module::Override:
657     // These behavior types accept any value.
658     break;
659
660   case Module::Require: {
661     // The value should itself be an MDNode with two operands, a flag ID (an
662     // MDString), and a value.
663     MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
664     Assert1(Value && Value->getNumOperands() == 2,
665             "invalid value for 'require' module flag (expected metadata pair)",
666             Op->getOperand(2));
667     Assert1(isa<MDString>(Value->getOperand(0)),
668             ("invalid value for 'require' module flag "
669              "(first value operand should be a string)"),
670             Value->getOperand(0));
671
672     // Append it to the list of requirements, to check once all module flags are
673     // scanned.
674     Requirements.push_back(Value);
675     break;
676   }
677
678   case Module::Append:
679   case Module::AppendUnique: {
680     // These behavior types require the operand be an MDNode.
681     Assert1(isa<MDNode>(Op->getOperand(2)),
682             "invalid value for 'append'-type module flag "
683             "(expected a metadata node)", Op->getOperand(2));
684     break;
685   }
686   }
687
688   // Unless this is a "requires" flag, check the ID is unique.
689   if (BehaviorValue != Module::Require) {
690     bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
691     Assert1(Inserted,
692             "module flag identifiers must be unique (or of 'require' type)",
693             ID);
694   }
695 }
696
697 void Verifier::VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
698                                     bool isFunction, const Value *V) {
699   unsigned Slot = ~0U;
700   for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I)
701     if (Attrs.getSlotIndex(I) == Idx) {
702       Slot = I;
703       break;
704     }
705
706   assert(Slot != ~0U && "Attribute set inconsistency!");
707
708   for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot);
709          I != E; ++I) {
710     if (I->isStringAttribute())
711       continue;
712
713     if (I->getKindAsEnum() == Attribute::NoReturn ||
714         I->getKindAsEnum() == Attribute::NoUnwind ||
715         I->getKindAsEnum() == Attribute::NoInline ||
716         I->getKindAsEnum() == Attribute::AlwaysInline ||
717         I->getKindAsEnum() == Attribute::OptimizeForSize ||
718         I->getKindAsEnum() == Attribute::StackProtect ||
719         I->getKindAsEnum() == Attribute::StackProtectReq ||
720         I->getKindAsEnum() == Attribute::StackProtectStrong ||
721         I->getKindAsEnum() == Attribute::NoRedZone ||
722         I->getKindAsEnum() == Attribute::NoImplicitFloat ||
723         I->getKindAsEnum() == Attribute::Naked ||
724         I->getKindAsEnum() == Attribute::InlineHint ||
725         I->getKindAsEnum() == Attribute::StackAlignment ||
726         I->getKindAsEnum() == Attribute::UWTable ||
727         I->getKindAsEnum() == Attribute::NonLazyBind ||
728         I->getKindAsEnum() == Attribute::ReturnsTwice ||
729         I->getKindAsEnum() == Attribute::SanitizeAddress ||
730         I->getKindAsEnum() == Attribute::SanitizeThread ||
731         I->getKindAsEnum() == Attribute::SanitizeMemory ||
732         I->getKindAsEnum() == Attribute::MinSize ||
733         I->getKindAsEnum() == Attribute::NoDuplicate ||
734         I->getKindAsEnum() == Attribute::Builtin ||
735         I->getKindAsEnum() == Attribute::NoBuiltin ||
736         I->getKindAsEnum() == Attribute::Cold ||
737         I->getKindAsEnum() == Attribute::OptimizeNone ||
738         I->getKindAsEnum() == Attribute::JumpTable) {
739       if (!isFunction) {
740         CheckFailed("Attribute '" + I->getAsString() +
741                     "' only applies to functions!", V);
742         return;
743       }
744     } else if (I->getKindAsEnum() == Attribute::ReadOnly ||
745                I->getKindAsEnum() == Attribute::ReadNone) {
746       if (Idx == 0) {
747         CheckFailed("Attribute '" + I->getAsString() +
748                     "' does not apply to function returns");
749         return;
750       }
751     } else if (isFunction) {
752       CheckFailed("Attribute '" + I->getAsString() +
753                   "' does not apply to functions!", V);
754       return;
755     }
756   }
757 }
758
759 // VerifyParameterAttrs - Check the given attributes for an argument or return
760 // value of the specified type.  The value V is printed in error messages.
761 void Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
762                                     bool isReturnValue, const Value *V) {
763   if (!Attrs.hasAttributes(Idx))
764     return;
765
766   VerifyAttributeTypes(Attrs, Idx, false, V);
767
768   if (isReturnValue)
769     Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
770             !Attrs.hasAttribute(Idx, Attribute::Nest) &&
771             !Attrs.hasAttribute(Idx, Attribute::StructRet) &&
772             !Attrs.hasAttribute(Idx, Attribute::NoCapture) &&
773             !Attrs.hasAttribute(Idx, Attribute::Returned) &&
774             !Attrs.hasAttribute(Idx, Attribute::InAlloca),
775             "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', and "
776             "'returned' do not apply to return values!", V);
777
778   // Check for mutually incompatible attributes.  Only inreg is compatible with
779   // sret.
780   unsigned AttrCount = 0;
781   AttrCount += Attrs.hasAttribute(Idx, Attribute::ByVal);
782   AttrCount += Attrs.hasAttribute(Idx, Attribute::InAlloca);
783   AttrCount += Attrs.hasAttribute(Idx, Attribute::StructRet) ||
784                Attrs.hasAttribute(Idx, Attribute::InReg);
785   AttrCount += Attrs.hasAttribute(Idx, Attribute::Nest);
786   Assert1(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', "
787                           "and 'sret' are incompatible!", V);
788
789   Assert1(!(Attrs.hasAttribute(Idx, Attribute::InAlloca) &&
790             Attrs.hasAttribute(Idx, Attribute::ReadOnly)), "Attributes "
791           "'inalloca and readonly' are incompatible!", V);
792
793   Assert1(!(Attrs.hasAttribute(Idx, Attribute::StructRet) &&
794             Attrs.hasAttribute(Idx, Attribute::Returned)), "Attributes "
795           "'sret and returned' are incompatible!", V);
796
797   Assert1(!(Attrs.hasAttribute(Idx, Attribute::ZExt) &&
798             Attrs.hasAttribute(Idx, Attribute::SExt)), "Attributes "
799           "'zeroext and signext' are incompatible!", V);
800
801   Assert1(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
802             Attrs.hasAttribute(Idx, Attribute::ReadOnly)), "Attributes "
803           "'readnone and readonly' are incompatible!", V);
804
805   Assert1(!(Attrs.hasAttribute(Idx, Attribute::NoInline) &&
806             Attrs.hasAttribute(Idx, Attribute::AlwaysInline)), "Attributes "
807           "'noinline and alwaysinline' are incompatible!", V);
808
809   Assert1(!AttrBuilder(Attrs, Idx).
810             hasAttributes(AttributeFuncs::typeIncompatible(Ty, Idx), Idx),
811           "Wrong types for attribute: " +
812           AttributeFuncs::typeIncompatible(Ty, Idx).getAsString(Idx), V);
813
814   if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
815     if (!PTy->getElementType()->isSized()) {
816       Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
817               !Attrs.hasAttribute(Idx, Attribute::InAlloca),
818               "Attributes 'byval' and 'inalloca' do not support unsized types!",
819               V);
820     }
821   } else {
822     Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal),
823             "Attribute 'byval' only applies to parameters with pointer type!",
824             V);
825   }
826 }
827
828 // VerifyFunctionAttrs - Check parameter attributes against a function type.
829 // The value V is printed in error messages.
830 void Verifier::VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
831                                    const Value *V) {
832   if (Attrs.isEmpty())
833     return;
834
835   bool SawNest = false;
836   bool SawReturned = false;
837   bool SawSRet = false;
838
839   for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
840     unsigned Idx = Attrs.getSlotIndex(i);
841
842     Type *Ty;
843     if (Idx == 0)
844       Ty = FT->getReturnType();
845     else if (Idx-1 < FT->getNumParams())
846       Ty = FT->getParamType(Idx-1);
847     else
848       break;  // VarArgs attributes, verified elsewhere.
849
850     VerifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V);
851
852     if (Idx == 0)
853       continue;
854
855     if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
856       Assert1(!SawNest, "More than one parameter has attribute nest!", V);
857       SawNest = true;
858     }
859
860     if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
861       Assert1(!SawReturned, "More than one parameter has attribute returned!",
862               V);
863       Assert1(Ty->canLosslesslyBitCastTo(FT->getReturnType()), "Incompatible "
864               "argument and return types for 'returned' attribute", V);
865       SawReturned = true;
866     }
867
868     if (Attrs.hasAttribute(Idx, Attribute::StructRet)) {
869       Assert1(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
870       Assert1(Idx == 1 || Idx == 2,
871               "Attribute 'sret' is not on first or second parameter!", V);
872       SawSRet = true;
873     }
874
875     if (Attrs.hasAttribute(Idx, Attribute::InAlloca)) {
876       Assert1(Idx == FT->getNumParams(),
877               "inalloca isn't on the last parameter!", V);
878     }
879   }
880
881   if (!Attrs.hasAttributes(AttributeSet::FunctionIndex))
882     return;
883
884   VerifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V);
885
886   Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
887                                Attribute::ReadNone) &&
888             Attrs.hasAttribute(AttributeSet::FunctionIndex,
889                                Attribute::ReadOnly)),
890           "Attributes 'readnone and readonly' are incompatible!", V);
891
892   Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
893                                Attribute::NoInline) &&
894             Attrs.hasAttribute(AttributeSet::FunctionIndex,
895                                Attribute::AlwaysInline)),
896           "Attributes 'noinline and alwaysinline' are incompatible!", V);
897
898   if (Attrs.hasAttribute(AttributeSet::FunctionIndex, 
899                          Attribute::OptimizeNone)) {
900     Assert1(Attrs.hasAttribute(AttributeSet::FunctionIndex,
901                                Attribute::NoInline),
902             "Attribute 'optnone' requires 'noinline'!", V);
903
904     Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
905                                 Attribute::OptimizeForSize),
906             "Attributes 'optsize and optnone' are incompatible!", V);
907
908     Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
909                                 Attribute::MinSize),
910             "Attributes 'minsize and optnone' are incompatible!", V);
911   }
912
913   if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
914                          Attribute::JumpTable)) {
915     const GlobalValue *GV = cast<GlobalValue>(V);
916     Assert1(GV->hasUnnamedAddr(),
917             "Attribute 'jumptable' requires 'unnamed_addr'", V);
918
919   }
920 }
921
922 void Verifier::VerifyBitcastType(const Value *V, Type *DestTy, Type *SrcTy) {
923   // Get the size of the types in bits, we'll need this later
924   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
925   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
926
927   // BitCast implies a no-op cast of type only. No bits change.
928   // However, you can't cast pointers to anything but pointers.
929   Assert1(SrcTy->isPointerTy() == DestTy->isPointerTy(),
930           "Bitcast requires both operands to be pointer or neither", V);
931   Assert1(SrcBitSize == DestBitSize,
932           "Bitcast requires types of same width", V);
933
934   // Disallow aggregates.
935   Assert1(!SrcTy->isAggregateType(),
936           "Bitcast operand must not be aggregate", V);
937   Assert1(!DestTy->isAggregateType(),
938           "Bitcast type must not be aggregate", V);
939
940   // Without datalayout, assume all address spaces are the same size.
941   // Don't check if both types are not pointers.
942   // Skip casts between scalars and vectors.
943   if (!DL ||
944       !SrcTy->isPtrOrPtrVectorTy() ||
945       !DestTy->isPtrOrPtrVectorTy() ||
946       SrcTy->isVectorTy() != DestTy->isVectorTy()) {
947     return;
948   }
949
950   unsigned SrcAS = SrcTy->getPointerAddressSpace();
951   unsigned DstAS = DestTy->getPointerAddressSpace();
952
953   Assert1(SrcAS == DstAS,
954           "Bitcasts between pointers of different address spaces is not legal."
955           "Use AddrSpaceCast instead.", V);
956 }
957
958 void Verifier::VerifyConstantExprBitcastType(const ConstantExpr *CE) {
959   if (CE->getOpcode() == Instruction::BitCast) {
960     Type *SrcTy = CE->getOperand(0)->getType();
961     Type *DstTy = CE->getType();
962     VerifyBitcastType(CE, DstTy, SrcTy);
963   }
964 }
965
966 bool Verifier::VerifyAttributeCount(AttributeSet Attrs, unsigned Params) {
967   if (Attrs.getNumSlots() == 0)
968     return true;
969
970   unsigned LastSlot = Attrs.getNumSlots() - 1;
971   unsigned LastIndex = Attrs.getSlotIndex(LastSlot);
972   if (LastIndex <= Params
973       || (LastIndex == AttributeSet::FunctionIndex
974           && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params)))
975     return true;
976
977   return false;
978 }
979
980 // visitFunction - Verify that a function is ok.
981 //
982 void Verifier::visitFunction(const Function &F) {
983   // Check function arguments.
984   FunctionType *FT = F.getFunctionType();
985   unsigned NumArgs = F.arg_size();
986
987   Assert1(Context == &F.getContext(),
988           "Function context does not match Module context!", &F);
989
990   Assert1(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
991   Assert2(FT->getNumParams() == NumArgs,
992           "# formal arguments must match # of arguments for function type!",
993           &F, FT);
994   Assert1(F.getReturnType()->isFirstClassType() ||
995           F.getReturnType()->isVoidTy() ||
996           F.getReturnType()->isStructTy(),
997           "Functions cannot return aggregate values!", &F);
998
999   Assert1(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
1000           "Invalid struct return type!", &F);
1001
1002   AttributeSet Attrs = F.getAttributes();
1003
1004   Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()),
1005           "Attribute after last parameter!", &F);
1006
1007   // Check function attributes.
1008   VerifyFunctionAttrs(FT, Attrs, &F);
1009
1010   // On function declarations/definitions, we do not support the builtin
1011   // attribute. We do not check this in VerifyFunctionAttrs since that is
1012   // checking for Attributes that can/can not ever be on functions.
1013   Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
1014                               Attribute::Builtin),
1015           "Attribute 'builtin' can only be applied to a callsite.", &F);
1016
1017   // Check that this function meets the restrictions on this calling convention.
1018   switch (F.getCallingConv()) {
1019   default:
1020     break;
1021   case CallingConv::C:
1022     break;
1023   case CallingConv::Fast:
1024   case CallingConv::Cold:
1025   case CallingConv::X86_FastCall:
1026   case CallingConv::X86_ThisCall:
1027   case CallingConv::Intel_OCL_BI:
1028   case CallingConv::PTX_Kernel:
1029   case CallingConv::PTX_Device:
1030     Assert1(!F.isVarArg(),
1031             "Varargs functions must have C calling conventions!", &F);
1032     break;
1033   }
1034
1035   bool isLLVMdotName = F.getName().size() >= 5 &&
1036                        F.getName().substr(0, 5) == "llvm.";
1037
1038   // Check that the argument values match the function type for this function...
1039   unsigned i = 0;
1040   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
1041        ++I, ++i) {
1042     Assert2(I->getType() == FT->getParamType(i),
1043             "Argument value does not match function argument type!",
1044             I, FT->getParamType(i));
1045     Assert1(I->getType()->isFirstClassType(),
1046             "Function arguments must have first-class types!", I);
1047     if (!isLLVMdotName)
1048       Assert2(!I->getType()->isMetadataTy(),
1049               "Function takes metadata but isn't an intrinsic", I, &F);
1050   }
1051
1052   if (F.isMaterializable()) {
1053     // Function has a body somewhere we can't see.
1054   } else if (F.isDeclaration()) {
1055     Assert1(F.hasExternalLinkage() || F.hasExternalWeakLinkage(),
1056             "invalid linkage type for function declaration", &F);
1057   } else {
1058     // Verify that this function (which has a body) is not named "llvm.*".  It
1059     // is not legal to define intrinsics.
1060     Assert1(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
1061
1062     // Check the entry node
1063     const BasicBlock *Entry = &F.getEntryBlock();
1064     Assert1(pred_begin(Entry) == pred_end(Entry),
1065             "Entry block to function must not have predecessors!", Entry);
1066
1067     // The address of the entry block cannot be taken, unless it is dead.
1068     if (Entry->hasAddressTaken()) {
1069       Assert1(!BlockAddress::lookup(Entry)->isConstantUsed(),
1070               "blockaddress may not be used with the entry block!", Entry);
1071     }
1072   }
1073
1074   // If this function is actually an intrinsic, verify that it is only used in
1075   // direct call/invokes, never having its "address taken".
1076   if (F.getIntrinsicID()) {
1077     const User *U;
1078     if (F.hasAddressTaken(&U))
1079       Assert1(0, "Invalid user of intrinsic instruction!", U);
1080   }
1081
1082   Assert1(!F.hasDLLImportStorageClass() ||
1083           (F.isDeclaration() && F.hasExternalLinkage()) ||
1084           F.hasAvailableExternallyLinkage(),
1085           "Function is marked as dllimport, but not external.", &F);
1086 }
1087
1088 // verifyBasicBlock - Verify that a basic block is well formed...
1089 //
1090 void Verifier::visitBasicBlock(BasicBlock &BB) {
1091   InstsInThisBlock.clear();
1092
1093   // Ensure that basic blocks have terminators!
1094   Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
1095
1096   // Check constraints that this basic block imposes on all of the PHI nodes in
1097   // it.
1098   if (isa<PHINode>(BB.front())) {
1099     SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
1100     SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
1101     std::sort(Preds.begin(), Preds.end());
1102     PHINode *PN;
1103     for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
1104       // Ensure that PHI nodes have at least one entry!
1105       Assert1(PN->getNumIncomingValues() != 0,
1106               "PHI nodes must have at least one entry.  If the block is dead, "
1107               "the PHI should be removed!", PN);
1108       Assert1(PN->getNumIncomingValues() == Preds.size(),
1109               "PHINode should have one entry for each predecessor of its "
1110               "parent basic block!", PN);
1111
1112       // Get and sort all incoming values in the PHI node...
1113       Values.clear();
1114       Values.reserve(PN->getNumIncomingValues());
1115       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1116         Values.push_back(std::make_pair(PN->getIncomingBlock(i),
1117                                         PN->getIncomingValue(i)));
1118       std::sort(Values.begin(), Values.end());
1119
1120       for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1121         // Check to make sure that if there is more than one entry for a
1122         // particular basic block in this PHI node, that the incoming values are
1123         // all identical.
1124         //
1125         Assert4(i == 0 || Values[i].first  != Values[i-1].first ||
1126                 Values[i].second == Values[i-1].second,
1127                 "PHI node has multiple entries for the same basic block with "
1128                 "different incoming values!", PN, Values[i].first,
1129                 Values[i].second, Values[i-1].second);
1130
1131         // Check to make sure that the predecessors and PHI node entries are
1132         // matched up.
1133         Assert3(Values[i].first == Preds[i],
1134                 "PHI node entries do not match predecessors!", PN,
1135                 Values[i].first, Preds[i]);
1136       }
1137     }
1138   }
1139 }
1140
1141 void Verifier::visitTerminatorInst(TerminatorInst &I) {
1142   // Ensure that terminators only exist at the end of the basic block.
1143   Assert1(&I == I.getParent()->getTerminator(),
1144           "Terminator found in the middle of a basic block!", I.getParent());
1145   visitInstruction(I);
1146 }
1147
1148 void Verifier::visitBranchInst(BranchInst &BI) {
1149   if (BI.isConditional()) {
1150     Assert2(BI.getCondition()->getType()->isIntegerTy(1),
1151             "Branch condition is not 'i1' type!", &BI, BI.getCondition());
1152   }
1153   visitTerminatorInst(BI);
1154 }
1155
1156 void Verifier::visitReturnInst(ReturnInst &RI) {
1157   Function *F = RI.getParent()->getParent();
1158   unsigned N = RI.getNumOperands();
1159   if (F->getReturnType()->isVoidTy())
1160     Assert2(N == 0,
1161             "Found return instr that returns non-void in Function of void "
1162             "return type!", &RI, F->getReturnType());
1163   else
1164     Assert2(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
1165             "Function return type does not match operand "
1166             "type of return inst!", &RI, F->getReturnType());
1167
1168   // Check to make sure that the return value has necessary properties for
1169   // terminators...
1170   visitTerminatorInst(RI);
1171 }
1172
1173 void Verifier::visitSwitchInst(SwitchInst &SI) {
1174   // Check to make sure that all of the constants in the switch instruction
1175   // have the same type as the switched-on value.
1176   Type *SwitchTy = SI.getCondition()->getType();
1177   SmallPtrSet<ConstantInt*, 32> Constants;
1178   for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
1179     Assert1(i.getCaseValue()->getType() == SwitchTy,
1180             "Switch constants must all be same type as switch value!", &SI);
1181     Assert2(Constants.insert(i.getCaseValue()),
1182             "Duplicate integer as switch case", &SI, i.getCaseValue());
1183   }
1184
1185   visitTerminatorInst(SI);
1186 }
1187
1188 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
1189   Assert1(BI.getAddress()->getType()->isPointerTy(),
1190           "Indirectbr operand must have pointer type!", &BI);
1191   for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
1192     Assert1(BI.getDestination(i)->getType()->isLabelTy(),
1193             "Indirectbr destinations must all have pointer type!", &BI);
1194
1195   visitTerminatorInst(BI);
1196 }
1197
1198 void Verifier::visitSelectInst(SelectInst &SI) {
1199   Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
1200                                           SI.getOperand(2)),
1201           "Invalid operands for select instruction!", &SI);
1202
1203   Assert1(SI.getTrueValue()->getType() == SI.getType(),
1204           "Select values must have same type as select instruction!", &SI);
1205   visitInstruction(SI);
1206 }
1207
1208 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
1209 /// a pass, if any exist, it's an error.
1210 ///
1211 void Verifier::visitUserOp1(Instruction &I) {
1212   Assert1(0, "User-defined operators should not live outside of a pass!", &I);
1213 }
1214
1215 void Verifier::visitTruncInst(TruncInst &I) {
1216   // Get the source and destination types
1217   Type *SrcTy = I.getOperand(0)->getType();
1218   Type *DestTy = I.getType();
1219
1220   // Get the size of the types in bits, we'll need this later
1221   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1222   unsigned DestBitSize = DestTy->getScalarSizeInBits();
1223
1224   Assert1(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
1225   Assert1(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
1226   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1227           "trunc source and destination must both be a vector or neither", &I);
1228   Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
1229
1230   visitInstruction(I);
1231 }
1232
1233 void Verifier::visitZExtInst(ZExtInst &I) {
1234   // Get the source and destination types
1235   Type *SrcTy = I.getOperand(0)->getType();
1236   Type *DestTy = I.getType();
1237
1238   // Get the size of the types in bits, we'll need this later
1239   Assert1(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
1240   Assert1(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
1241   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1242           "zext source and destination must both be a vector or neither", &I);
1243   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1244   unsigned DestBitSize = DestTy->getScalarSizeInBits();
1245
1246   Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
1247
1248   visitInstruction(I);
1249 }
1250
1251 void Verifier::visitSExtInst(SExtInst &I) {
1252   // Get the source and destination types
1253   Type *SrcTy = I.getOperand(0)->getType();
1254   Type *DestTy = I.getType();
1255
1256   // Get the size of the types in bits, we'll need this later
1257   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1258   unsigned DestBitSize = DestTy->getScalarSizeInBits();
1259
1260   Assert1(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
1261   Assert1(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
1262   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1263           "sext source and destination must both be a vector or neither", &I);
1264   Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
1265
1266   visitInstruction(I);
1267 }
1268
1269 void Verifier::visitFPTruncInst(FPTruncInst &I) {
1270   // Get the source and destination types
1271   Type *SrcTy = I.getOperand(0)->getType();
1272   Type *DestTy = I.getType();
1273   // Get the size of the types in bits, we'll need this later
1274   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1275   unsigned DestBitSize = DestTy->getScalarSizeInBits();
1276
1277   Assert1(SrcTy->isFPOrFPVectorTy(),"FPTrunc only operates on FP", &I);
1278   Assert1(DestTy->isFPOrFPVectorTy(),"FPTrunc only produces an FP", &I);
1279   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1280           "fptrunc source and destination must both be a vector or neither",&I);
1281   Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
1282
1283   visitInstruction(I);
1284 }
1285
1286 void Verifier::visitFPExtInst(FPExtInst &I) {
1287   // Get the source and destination types
1288   Type *SrcTy = I.getOperand(0)->getType();
1289   Type *DestTy = I.getType();
1290
1291   // Get the size of the types in bits, we'll need this later
1292   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1293   unsigned DestBitSize = DestTy->getScalarSizeInBits();
1294
1295   Assert1(SrcTy->isFPOrFPVectorTy(),"FPExt only operates on FP", &I);
1296   Assert1(DestTy->isFPOrFPVectorTy(),"FPExt only produces an FP", &I);
1297   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1298           "fpext source and destination must both be a vector or neither", &I);
1299   Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
1300
1301   visitInstruction(I);
1302 }
1303
1304 void Verifier::visitUIToFPInst(UIToFPInst &I) {
1305   // Get the source and destination types
1306   Type *SrcTy = I.getOperand(0)->getType();
1307   Type *DestTy = I.getType();
1308
1309   bool SrcVec = SrcTy->isVectorTy();
1310   bool DstVec = DestTy->isVectorTy();
1311
1312   Assert1(SrcVec == DstVec,
1313           "UIToFP source and dest must both be vector or scalar", &I);
1314   Assert1(SrcTy->isIntOrIntVectorTy(),
1315           "UIToFP source must be integer or integer vector", &I);
1316   Assert1(DestTy->isFPOrFPVectorTy(),
1317           "UIToFP result must be FP or FP vector", &I);
1318
1319   if (SrcVec && DstVec)
1320     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1321             cast<VectorType>(DestTy)->getNumElements(),
1322             "UIToFP source and dest vector length mismatch", &I);
1323
1324   visitInstruction(I);
1325 }
1326
1327 void Verifier::visitSIToFPInst(SIToFPInst &I) {
1328   // Get the source and destination types
1329   Type *SrcTy = I.getOperand(0)->getType();
1330   Type *DestTy = I.getType();
1331
1332   bool SrcVec = SrcTy->isVectorTy();
1333   bool DstVec = DestTy->isVectorTy();
1334
1335   Assert1(SrcVec == DstVec,
1336           "SIToFP source and dest must both be vector or scalar", &I);
1337   Assert1(SrcTy->isIntOrIntVectorTy(),
1338           "SIToFP source must be integer or integer vector", &I);
1339   Assert1(DestTy->isFPOrFPVectorTy(),
1340           "SIToFP result must be FP or FP vector", &I);
1341
1342   if (SrcVec && DstVec)
1343     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1344             cast<VectorType>(DestTy)->getNumElements(),
1345             "SIToFP source and dest vector length mismatch", &I);
1346
1347   visitInstruction(I);
1348 }
1349
1350 void Verifier::visitFPToUIInst(FPToUIInst &I) {
1351   // Get the source and destination types
1352   Type *SrcTy = I.getOperand(0)->getType();
1353   Type *DestTy = I.getType();
1354
1355   bool SrcVec = SrcTy->isVectorTy();
1356   bool DstVec = DestTy->isVectorTy();
1357
1358   Assert1(SrcVec == DstVec,
1359           "FPToUI source and dest must both be vector or scalar", &I);
1360   Assert1(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
1361           &I);
1362   Assert1(DestTy->isIntOrIntVectorTy(),
1363           "FPToUI result must be integer or integer vector", &I);
1364
1365   if (SrcVec && DstVec)
1366     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1367             cast<VectorType>(DestTy)->getNumElements(),
1368             "FPToUI source and dest vector length mismatch", &I);
1369
1370   visitInstruction(I);
1371 }
1372
1373 void Verifier::visitFPToSIInst(FPToSIInst &I) {
1374   // Get the source and destination types
1375   Type *SrcTy = I.getOperand(0)->getType();
1376   Type *DestTy = I.getType();
1377
1378   bool SrcVec = SrcTy->isVectorTy();
1379   bool DstVec = DestTy->isVectorTy();
1380
1381   Assert1(SrcVec == DstVec,
1382           "FPToSI source and dest must both be vector or scalar", &I);
1383   Assert1(SrcTy->isFPOrFPVectorTy(),
1384           "FPToSI source must be FP or FP vector", &I);
1385   Assert1(DestTy->isIntOrIntVectorTy(),
1386           "FPToSI result must be integer or integer vector", &I);
1387
1388   if (SrcVec && DstVec)
1389     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1390             cast<VectorType>(DestTy)->getNumElements(),
1391             "FPToSI source and dest vector length mismatch", &I);
1392
1393   visitInstruction(I);
1394 }
1395
1396 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
1397   // Get the source and destination types
1398   Type *SrcTy = I.getOperand(0)->getType();
1399   Type *DestTy = I.getType();
1400
1401   Assert1(SrcTy->getScalarType()->isPointerTy(),
1402           "PtrToInt source must be pointer", &I);
1403   Assert1(DestTy->getScalarType()->isIntegerTy(),
1404           "PtrToInt result must be integral", &I);
1405   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1406           "PtrToInt type mismatch", &I);
1407
1408   if (SrcTy->isVectorTy()) {
1409     VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1410     VectorType *VDest = dyn_cast<VectorType>(DestTy);
1411     Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1412           "PtrToInt Vector width mismatch", &I);
1413   }
1414
1415   visitInstruction(I);
1416 }
1417
1418 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
1419   // Get the source and destination types
1420   Type *SrcTy = I.getOperand(0)->getType();
1421   Type *DestTy = I.getType();
1422
1423   Assert1(SrcTy->getScalarType()->isIntegerTy(),
1424           "IntToPtr source must be an integral", &I);
1425   Assert1(DestTy->getScalarType()->isPointerTy(),
1426           "IntToPtr result must be a pointer",&I);
1427   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1428           "IntToPtr type mismatch", &I);
1429   if (SrcTy->isVectorTy()) {
1430     VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1431     VectorType *VDest = dyn_cast<VectorType>(DestTy);
1432     Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1433           "IntToPtr Vector width mismatch", &I);
1434   }
1435   visitInstruction(I);
1436 }
1437
1438 void Verifier::visitBitCastInst(BitCastInst &I) {
1439   Type *SrcTy = I.getOperand(0)->getType();
1440   Type *DestTy = I.getType();
1441   VerifyBitcastType(&I, DestTy, SrcTy);
1442   visitInstruction(I);
1443 }
1444
1445 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
1446   Type *SrcTy = I.getOperand(0)->getType();
1447   Type *DestTy = I.getType();
1448
1449   Assert1(SrcTy->isPtrOrPtrVectorTy(),
1450           "AddrSpaceCast source must be a pointer", &I);
1451   Assert1(DestTy->isPtrOrPtrVectorTy(),
1452           "AddrSpaceCast result must be a pointer", &I);
1453   Assert1(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
1454           "AddrSpaceCast must be between different address spaces", &I);
1455   if (SrcTy->isVectorTy())
1456     Assert1(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(),
1457             "AddrSpaceCast vector pointer number of elements mismatch", &I);
1458   visitInstruction(I);
1459 }
1460
1461 /// visitPHINode - Ensure that a PHI node is well formed.
1462 ///
1463 void Verifier::visitPHINode(PHINode &PN) {
1464   // Ensure that the PHI nodes are all grouped together at the top of the block.
1465   // This can be tested by checking whether the instruction before this is
1466   // either nonexistent (because this is begin()) or is a PHI node.  If not,
1467   // then there is some other instruction before a PHI.
1468   Assert2(&PN == &PN.getParent()->front() ||
1469           isa<PHINode>(--BasicBlock::iterator(&PN)),
1470           "PHI nodes not grouped at top of basic block!",
1471           &PN, PN.getParent());
1472
1473   // Check that all of the values of the PHI node have the same type as the
1474   // result, and that the incoming blocks are really basic blocks.
1475   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1476     Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
1477             "PHI node operands are not the same type as the result!", &PN);
1478   }
1479
1480   // All other PHI node constraints are checked in the visitBasicBlock method.
1481
1482   visitInstruction(PN);
1483 }
1484
1485 void Verifier::VerifyCallSite(CallSite CS) {
1486   Instruction *I = CS.getInstruction();
1487
1488   Assert1(CS.getCalledValue()->getType()->isPointerTy(),
1489           "Called function must be a pointer!", I);
1490   PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
1491
1492   Assert1(FPTy->getElementType()->isFunctionTy(),
1493           "Called function is not pointer to function type!", I);
1494   FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
1495
1496   // Verify that the correct number of arguments are being passed
1497   if (FTy->isVarArg())
1498     Assert1(CS.arg_size() >= FTy->getNumParams(),
1499             "Called function requires more parameters than were provided!",I);
1500   else
1501     Assert1(CS.arg_size() == FTy->getNumParams(),
1502             "Incorrect number of arguments passed to called function!", I);
1503
1504   // Verify that all arguments to the call match the function type.
1505   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1506     Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i),
1507             "Call parameter type does not match function signature!",
1508             CS.getArgument(i), FTy->getParamType(i), I);
1509
1510   AttributeSet Attrs = CS.getAttributes();
1511
1512   Assert1(VerifyAttributeCount(Attrs, CS.arg_size()),
1513           "Attribute after last parameter!", I);
1514
1515   // Verify call attributes.
1516   VerifyFunctionAttrs(FTy, Attrs, I);
1517
1518   // Conservatively check the inalloca argument.
1519   // We have a bug if we can find that there is an underlying alloca without
1520   // inalloca.
1521   if (CS.hasInAllocaArgument()) {
1522     Value *InAllocaArg = CS.getArgument(FTy->getNumParams() - 1);
1523     if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
1524       Assert2(AI->isUsedWithInAlloca(),
1525               "inalloca argument for call has mismatched alloca", AI, I);
1526   }
1527
1528   if (FTy->isVarArg()) {
1529     // FIXME? is 'nest' even legal here?
1530     bool SawNest = false;
1531     bool SawReturned = false;
1532
1533     for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) {
1534       if (Attrs.hasAttribute(Idx, Attribute::Nest))
1535         SawNest = true;
1536       if (Attrs.hasAttribute(Idx, Attribute::Returned))
1537         SawReturned = true;
1538     }
1539
1540     // Check attributes on the varargs part.
1541     for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
1542       Type *Ty = CS.getArgument(Idx-1)->getType();
1543       VerifyParameterAttrs(Attrs, Idx, Ty, false, I);
1544
1545       if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
1546         Assert1(!SawNest, "More than one parameter has attribute nest!", I);
1547         SawNest = true;
1548       }
1549
1550       if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
1551         Assert1(!SawReturned, "More than one parameter has attribute returned!",
1552                 I);
1553         Assert1(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
1554                 "Incompatible argument and return types for 'returned' "
1555                 "attribute", I);
1556         SawReturned = true;
1557       }
1558
1559       Assert1(!Attrs.hasAttribute(Idx, Attribute::StructRet),
1560               "Attribute 'sret' cannot be used for vararg call arguments!", I);
1561
1562       if (Attrs.hasAttribute(Idx, Attribute::InAlloca))
1563         Assert1(Idx == CS.arg_size(), "inalloca isn't on the last argument!",
1564                 I);
1565     }
1566   }
1567
1568   // Verify that there's no metadata unless it's a direct call to an intrinsic.
1569   if (CS.getCalledFunction() == nullptr ||
1570       !CS.getCalledFunction()->getName().startswith("llvm.")) {
1571     for (FunctionType::param_iterator PI = FTy->param_begin(),
1572            PE = FTy->param_end(); PI != PE; ++PI)
1573       Assert1(!(*PI)->isMetadataTy(),
1574               "Function has metadata parameter but isn't an intrinsic", I);
1575   }
1576
1577   visitInstruction(*I);
1578 }
1579
1580 /// Two types are "congruent" if they are identical, or if they are both pointer
1581 /// types with different pointee types and the same address space.
1582 static bool isTypeCongruent(Type *L, Type *R) {
1583   if (L == R)
1584     return true;
1585   PointerType *PL = dyn_cast<PointerType>(L);
1586   PointerType *PR = dyn_cast<PointerType>(R);
1587   if (!PL || !PR)
1588     return false;
1589   return PL->getAddressSpace() == PR->getAddressSpace();
1590 }
1591
1592 static AttrBuilder getParameterABIAttributes(int I, AttributeSet Attrs) {
1593   static const Attribute::AttrKind ABIAttrs[] = {
1594       Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
1595       Attribute::InReg, Attribute::Returned};
1596   AttrBuilder Copy;
1597   for (auto AK : ABIAttrs) {
1598     if (Attrs.hasAttribute(I + 1, AK))
1599       Copy.addAttribute(AK);
1600   }
1601   if (Attrs.hasAttribute(I + 1, Attribute::Alignment))
1602     Copy.addAlignmentAttr(Attrs.getParamAlignment(I + 1));
1603   return Copy;
1604 }
1605
1606 void Verifier::verifyMustTailCall(CallInst &CI) {
1607   Assert1(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
1608
1609   // - The caller and callee prototypes must match.  Pointer types of
1610   //   parameters or return types may differ in pointee type, but not
1611   //   address space.
1612   Function *F = CI.getParent()->getParent();
1613   auto GetFnTy = [](Value *V) {
1614     return cast<FunctionType>(
1615         cast<PointerType>(V->getType())->getElementType());
1616   };
1617   FunctionType *CallerTy = GetFnTy(F);
1618   FunctionType *CalleeTy = GetFnTy(CI.getCalledValue());
1619   Assert1(CallerTy->getNumParams() == CalleeTy->getNumParams(),
1620           "cannot guarantee tail call due to mismatched parameter counts", &CI);
1621   Assert1(CallerTy->isVarArg() == CalleeTy->isVarArg(),
1622           "cannot guarantee tail call due to mismatched varargs", &CI);
1623   Assert1(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
1624           "cannot guarantee tail call due to mismatched return types", &CI);
1625   for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
1626     Assert1(
1627         isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
1628         "cannot guarantee tail call due to mismatched parameter types", &CI);
1629   }
1630
1631   // - The calling conventions of the caller and callee must match.
1632   Assert1(F->getCallingConv() == CI.getCallingConv(),
1633           "cannot guarantee tail call due to mismatched calling conv", &CI);
1634
1635   // - All ABI-impacting function attributes, such as sret, byval, inreg,
1636   //   returned, and inalloca, must match.
1637   AttributeSet CallerAttrs = F->getAttributes();
1638   AttributeSet CalleeAttrs = CI.getAttributes();
1639   for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
1640     AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs);
1641     AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs);
1642     Assert2(CallerABIAttrs == CalleeABIAttrs,
1643             "cannot guarantee tail call due to mismatched ABI impacting "
1644             "function attributes", &CI, CI.getOperand(I));
1645   }
1646
1647   // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
1648   //   or a pointer bitcast followed by a ret instruction.
1649   // - The ret instruction must return the (possibly bitcasted) value
1650   //   produced by the call or void.
1651   Value *RetVal = &CI;
1652   Instruction *Next = CI.getNextNode();
1653
1654   // Handle the optional bitcast.
1655   if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
1656     Assert1(BI->getOperand(0) == RetVal,
1657             "bitcast following musttail call must use the call", BI);
1658     RetVal = BI;
1659     Next = BI->getNextNode();
1660   }
1661
1662   // Check the return.
1663   ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
1664   Assert1(Ret, "musttail call must be precede a ret with an optional bitcast",
1665           &CI);
1666   Assert1(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal,
1667           "musttail call result must be returned", Ret);
1668 }
1669
1670 void Verifier::visitCallInst(CallInst &CI) {
1671   VerifyCallSite(&CI);
1672
1673   if (CI.isMustTailCall())
1674     verifyMustTailCall(CI);
1675
1676   if (Function *F = CI.getCalledFunction())
1677     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
1678       visitIntrinsicFunctionCall(ID, CI);
1679 }
1680
1681 void Verifier::visitInvokeInst(InvokeInst &II) {
1682   VerifyCallSite(&II);
1683
1684   // Verify that there is a landingpad instruction as the first non-PHI
1685   // instruction of the 'unwind' destination.
1686   Assert1(II.getUnwindDest()->isLandingPad(),
1687           "The unwind destination does not have a landingpad instruction!",&II);
1688
1689   visitTerminatorInst(II);
1690 }
1691
1692 /// visitBinaryOperator - Check that both arguments to the binary operator are
1693 /// of the same type!
1694 ///
1695 void Verifier::visitBinaryOperator(BinaryOperator &B) {
1696   Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
1697           "Both operands to a binary operator are not of the same type!", &B);
1698
1699   switch (B.getOpcode()) {
1700   // Check that integer arithmetic operators are only used with
1701   // integral operands.
1702   case Instruction::Add:
1703   case Instruction::Sub:
1704   case Instruction::Mul:
1705   case Instruction::SDiv:
1706   case Instruction::UDiv:
1707   case Instruction::SRem:
1708   case Instruction::URem:
1709     Assert1(B.getType()->isIntOrIntVectorTy(),
1710             "Integer arithmetic operators only work with integral types!", &B);
1711     Assert1(B.getType() == B.getOperand(0)->getType(),
1712             "Integer arithmetic operators must have same type "
1713             "for operands and result!", &B);
1714     break;
1715   // Check that floating-point arithmetic operators are only used with
1716   // floating-point operands.
1717   case Instruction::FAdd:
1718   case Instruction::FSub:
1719   case Instruction::FMul:
1720   case Instruction::FDiv:
1721   case Instruction::FRem:
1722     Assert1(B.getType()->isFPOrFPVectorTy(),
1723             "Floating-point arithmetic operators only work with "
1724             "floating-point types!", &B);
1725     Assert1(B.getType() == B.getOperand(0)->getType(),
1726             "Floating-point arithmetic operators must have same type "
1727             "for operands and result!", &B);
1728     break;
1729   // Check that logical operators are only used with integral operands.
1730   case Instruction::And:
1731   case Instruction::Or:
1732   case Instruction::Xor:
1733     Assert1(B.getType()->isIntOrIntVectorTy(),
1734             "Logical operators only work with integral types!", &B);
1735     Assert1(B.getType() == B.getOperand(0)->getType(),
1736             "Logical operators must have same type for operands and result!",
1737             &B);
1738     break;
1739   case Instruction::Shl:
1740   case Instruction::LShr:
1741   case Instruction::AShr:
1742     Assert1(B.getType()->isIntOrIntVectorTy(),
1743             "Shifts only work with integral types!", &B);
1744     Assert1(B.getType() == B.getOperand(0)->getType(),
1745             "Shift return type must be same as operands!", &B);
1746     break;
1747   default:
1748     llvm_unreachable("Unknown BinaryOperator opcode!");
1749   }
1750
1751   visitInstruction(B);
1752 }
1753
1754 void Verifier::visitICmpInst(ICmpInst &IC) {
1755   // Check that the operands are the same type
1756   Type *Op0Ty = IC.getOperand(0)->getType();
1757   Type *Op1Ty = IC.getOperand(1)->getType();
1758   Assert1(Op0Ty == Op1Ty,
1759           "Both operands to ICmp instruction are not of the same type!", &IC);
1760   // Check that the operands are the right type
1761   Assert1(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
1762           "Invalid operand types for ICmp instruction", &IC);
1763   // Check that the predicate is valid.
1764   Assert1(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
1765           IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
1766           "Invalid predicate in ICmp instruction!", &IC);
1767
1768   visitInstruction(IC);
1769 }
1770
1771 void Verifier::visitFCmpInst(FCmpInst &FC) {
1772   // Check that the operands are the same type
1773   Type *Op0Ty = FC.getOperand(0)->getType();
1774   Type *Op1Ty = FC.getOperand(1)->getType();
1775   Assert1(Op0Ty == Op1Ty,
1776           "Both operands to FCmp instruction are not of the same type!", &FC);
1777   // Check that the operands are the right type
1778   Assert1(Op0Ty->isFPOrFPVectorTy(),
1779           "Invalid operand types for FCmp instruction", &FC);
1780   // Check that the predicate is valid.
1781   Assert1(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
1782           FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
1783           "Invalid predicate in FCmp instruction!", &FC);
1784
1785   visitInstruction(FC);
1786 }
1787
1788 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
1789   Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
1790                                               EI.getOperand(1)),
1791           "Invalid extractelement operands!", &EI);
1792   visitInstruction(EI);
1793 }
1794
1795 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
1796   Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
1797                                              IE.getOperand(1),
1798                                              IE.getOperand(2)),
1799           "Invalid insertelement operands!", &IE);
1800   visitInstruction(IE);
1801 }
1802
1803 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
1804   Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
1805                                              SV.getOperand(2)),
1806           "Invalid shufflevector operands!", &SV);
1807   visitInstruction(SV);
1808 }
1809
1810 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1811   Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
1812
1813   Assert1(isa<PointerType>(TargetTy),
1814     "GEP base pointer is not a vector or a vector of pointers", &GEP);
1815   Assert1(cast<PointerType>(TargetTy)->getElementType()->isSized(),
1816           "GEP into unsized type!", &GEP);
1817   Assert1(GEP.getPointerOperandType()->isVectorTy() ==
1818           GEP.getType()->isVectorTy(), "Vector GEP must return a vector value",
1819           &GEP);
1820
1821   SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
1822   Type *ElTy =
1823     GetElementPtrInst::getIndexedType(GEP.getPointerOperandType(), Idxs);
1824   Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
1825
1826   Assert2(GEP.getType()->getScalarType()->isPointerTy() &&
1827           cast<PointerType>(GEP.getType()->getScalarType())->getElementType()
1828           == ElTy, "GEP is not of right type for indices!", &GEP, ElTy);
1829
1830   if (GEP.getPointerOperandType()->isVectorTy()) {
1831     // Additional checks for vector GEPs.
1832     unsigned GepWidth = GEP.getPointerOperandType()->getVectorNumElements();
1833     Assert1(GepWidth == GEP.getType()->getVectorNumElements(),
1834             "Vector GEP result width doesn't match operand's", &GEP);
1835     for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
1836       Type *IndexTy = Idxs[i]->getType();
1837       Assert1(IndexTy->isVectorTy(),
1838               "Vector GEP must have vector indices!", &GEP);
1839       unsigned IndexWidth = IndexTy->getVectorNumElements();
1840       Assert1(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP);
1841     }
1842   }
1843   visitInstruction(GEP);
1844 }
1845
1846 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
1847   return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
1848 }
1849
1850 void Verifier::visitLoadInst(LoadInst &LI) {
1851   PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
1852   Assert1(PTy, "Load operand must be a pointer.", &LI);
1853   Type *ElTy = PTy->getElementType();
1854   Assert2(ElTy == LI.getType(),
1855           "Load result type does not match pointer operand type!", &LI, ElTy);
1856   if (LI.isAtomic()) {
1857     Assert1(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
1858             "Load cannot have Release ordering", &LI);
1859     Assert1(LI.getAlignment() != 0,
1860             "Atomic load must specify explicit alignment", &LI);
1861     if (!ElTy->isPointerTy()) {
1862       Assert2(ElTy->isIntegerTy(),
1863               "atomic load operand must have integer type!",
1864               &LI, ElTy);
1865       unsigned Size = ElTy->getPrimitiveSizeInBits();
1866       Assert2(Size >= 8 && !(Size & (Size - 1)),
1867               "atomic load operand must be power-of-two byte-sized integer",
1868               &LI, ElTy);
1869     }
1870   } else {
1871     Assert1(LI.getSynchScope() == CrossThread,
1872             "Non-atomic load cannot have SynchronizationScope specified", &LI);
1873   }
1874
1875   if (MDNode *Range = LI.getMetadata(LLVMContext::MD_range)) {
1876     unsigned NumOperands = Range->getNumOperands();
1877     Assert1(NumOperands % 2 == 0, "Unfinished range!", Range);
1878     unsigned NumRanges = NumOperands / 2;
1879     Assert1(NumRanges >= 1, "It should have at least one range!", Range);
1880
1881     ConstantRange LastRange(1); // Dummy initial value
1882     for (unsigned i = 0; i < NumRanges; ++i) {
1883       ConstantInt *Low = dyn_cast<ConstantInt>(Range->getOperand(2*i));
1884       Assert1(Low, "The lower limit must be an integer!", Low);
1885       ConstantInt *High = dyn_cast<ConstantInt>(Range->getOperand(2*i + 1));
1886       Assert1(High, "The upper limit must be an integer!", High);
1887       Assert1(High->getType() == Low->getType() &&
1888               High->getType() == ElTy, "Range types must match load type!",
1889               &LI);
1890
1891       APInt HighV = High->getValue();
1892       APInt LowV = Low->getValue();
1893       ConstantRange CurRange(LowV, HighV);
1894       Assert1(!CurRange.isEmptySet() && !CurRange.isFullSet(),
1895               "Range must not be empty!", Range);
1896       if (i != 0) {
1897         Assert1(CurRange.intersectWith(LastRange).isEmptySet(),
1898                 "Intervals are overlapping", Range);
1899         Assert1(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
1900                 Range);
1901         Assert1(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
1902                 Range);
1903       }
1904       LastRange = ConstantRange(LowV, HighV);
1905     }
1906     if (NumRanges > 2) {
1907       APInt FirstLow =
1908         dyn_cast<ConstantInt>(Range->getOperand(0))->getValue();
1909       APInt FirstHigh =
1910         dyn_cast<ConstantInt>(Range->getOperand(1))->getValue();
1911       ConstantRange FirstRange(FirstLow, FirstHigh);
1912       Assert1(FirstRange.intersectWith(LastRange).isEmptySet(),
1913               "Intervals are overlapping", Range);
1914       Assert1(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
1915               Range);
1916     }
1917
1918
1919   }
1920
1921   visitInstruction(LI);
1922 }
1923
1924 void Verifier::visitStoreInst(StoreInst &SI) {
1925   PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
1926   Assert1(PTy, "Store operand must be a pointer.", &SI);
1927   Type *ElTy = PTy->getElementType();
1928   Assert2(ElTy == SI.getOperand(0)->getType(),
1929           "Stored value type does not match pointer operand type!",
1930           &SI, ElTy);
1931   if (SI.isAtomic()) {
1932     Assert1(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
1933             "Store cannot have Acquire ordering", &SI);
1934     Assert1(SI.getAlignment() != 0,
1935             "Atomic store must specify explicit alignment", &SI);
1936     if (!ElTy->isPointerTy()) {
1937       Assert2(ElTy->isIntegerTy(),
1938               "atomic store operand must have integer type!",
1939               &SI, ElTy);
1940       unsigned Size = ElTy->getPrimitiveSizeInBits();
1941       Assert2(Size >= 8 && !(Size & (Size - 1)),
1942               "atomic store operand must be power-of-two byte-sized integer",
1943               &SI, ElTy);
1944     }
1945   } else {
1946     Assert1(SI.getSynchScope() == CrossThread,
1947             "Non-atomic store cannot have SynchronizationScope specified", &SI);
1948   }
1949   visitInstruction(SI);
1950 }
1951
1952 void Verifier::visitAllocaInst(AllocaInst &AI) {
1953   SmallPtrSet<const Type*, 4> Visited;
1954   PointerType *PTy = AI.getType();
1955   Assert1(PTy->getAddressSpace() == 0,
1956           "Allocation instruction pointer not in the generic address space!",
1957           &AI);
1958   Assert1(PTy->getElementType()->isSized(&Visited), "Cannot allocate unsized type",
1959           &AI);
1960   Assert1(AI.getArraySize()->getType()->isIntegerTy(),
1961           "Alloca array size must have integer type", &AI);
1962
1963   visitInstruction(AI);
1964 }
1965
1966 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
1967
1968   // FIXME: more conditions???
1969   Assert1(CXI.getSuccessOrdering() != NotAtomic,
1970           "cmpxchg instructions must be atomic.", &CXI);
1971   Assert1(CXI.getFailureOrdering() != NotAtomic,
1972           "cmpxchg instructions must be atomic.", &CXI);
1973   Assert1(CXI.getSuccessOrdering() != Unordered,
1974           "cmpxchg instructions cannot be unordered.", &CXI);
1975   Assert1(CXI.getFailureOrdering() != Unordered,
1976           "cmpxchg instructions cannot be unordered.", &CXI);
1977   Assert1(CXI.getSuccessOrdering() >= CXI.getFailureOrdering(),
1978           "cmpxchg instructions be at least as constrained on success as fail",
1979           &CXI);
1980   Assert1(CXI.getFailureOrdering() != Release &&
1981               CXI.getFailureOrdering() != AcquireRelease,
1982           "cmpxchg failure ordering cannot include release semantics", &CXI);
1983
1984   PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
1985   Assert1(PTy, "First cmpxchg operand must be a pointer.", &CXI);
1986   Type *ElTy = PTy->getElementType();
1987   Assert2(ElTy->isIntegerTy(),
1988           "cmpxchg operand must have integer type!",
1989           &CXI, ElTy);
1990   unsigned Size = ElTy->getPrimitiveSizeInBits();
1991   Assert2(Size >= 8 && !(Size & (Size - 1)),
1992           "cmpxchg operand must be power-of-two byte-sized integer",
1993           &CXI, ElTy);
1994   Assert2(ElTy == CXI.getOperand(1)->getType(),
1995           "Expected value type does not match pointer operand type!",
1996           &CXI, ElTy);
1997   Assert2(ElTy == CXI.getOperand(2)->getType(),
1998           "Stored value type does not match pointer operand type!",
1999           &CXI, ElTy);
2000   visitInstruction(CXI);
2001 }
2002
2003 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
2004   Assert1(RMWI.getOrdering() != NotAtomic,
2005           "atomicrmw instructions must be atomic.", &RMWI);
2006   Assert1(RMWI.getOrdering() != Unordered,
2007           "atomicrmw instructions cannot be unordered.", &RMWI);
2008   PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
2009   Assert1(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
2010   Type *ElTy = PTy->getElementType();
2011   Assert2(ElTy->isIntegerTy(),
2012           "atomicrmw operand must have integer type!",
2013           &RMWI, ElTy);
2014   unsigned Size = ElTy->getPrimitiveSizeInBits();
2015   Assert2(Size >= 8 && !(Size & (Size - 1)),
2016           "atomicrmw operand must be power-of-two byte-sized integer",
2017           &RMWI, ElTy);
2018   Assert2(ElTy == RMWI.getOperand(1)->getType(),
2019           "Argument value type does not match pointer operand type!",
2020           &RMWI, ElTy);
2021   Assert1(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
2022           RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
2023           "Invalid binary operation!", &RMWI);
2024   visitInstruction(RMWI);
2025 }
2026
2027 void Verifier::visitFenceInst(FenceInst &FI) {
2028   const AtomicOrdering Ordering = FI.getOrdering();
2029   Assert1(Ordering == Acquire || Ordering == Release ||
2030           Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
2031           "fence instructions may only have "
2032           "acquire, release, acq_rel, or seq_cst ordering.", &FI);
2033   visitInstruction(FI);
2034 }
2035
2036 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
2037   Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
2038                                            EVI.getIndices()) ==
2039           EVI.getType(),
2040           "Invalid ExtractValueInst operands!", &EVI);
2041
2042   visitInstruction(EVI);
2043 }
2044
2045 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
2046   Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
2047                                            IVI.getIndices()) ==
2048           IVI.getOperand(1)->getType(),
2049           "Invalid InsertValueInst operands!", &IVI);
2050
2051   visitInstruction(IVI);
2052 }
2053
2054 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
2055   BasicBlock *BB = LPI.getParent();
2056
2057   // The landingpad instruction is ill-formed if it doesn't have any clauses and
2058   // isn't a cleanup.
2059   Assert1(LPI.getNumClauses() > 0 || LPI.isCleanup(),
2060           "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
2061
2062   // The landingpad instruction defines its parent as a landing pad block. The
2063   // landing pad block may be branched to only by the unwind edge of an invoke.
2064   for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
2065     const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator());
2066     Assert1(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
2067             "Block containing LandingPadInst must be jumped to "
2068             "only by the unwind edge of an invoke.", &LPI);
2069   }
2070
2071   // The landingpad instruction must be the first non-PHI instruction in the
2072   // block.
2073   Assert1(LPI.getParent()->getLandingPadInst() == &LPI,
2074           "LandingPadInst not the first non-PHI instruction in the block.",
2075           &LPI);
2076
2077   // The personality functions for all landingpad instructions within the same
2078   // function should match.
2079   if (PersonalityFn)
2080     Assert1(LPI.getPersonalityFn() == PersonalityFn,
2081             "Personality function doesn't match others in function", &LPI);
2082   PersonalityFn = LPI.getPersonalityFn();
2083
2084   // All operands must be constants.
2085   Assert1(isa<Constant>(PersonalityFn), "Personality function is not constant!",
2086           &LPI);
2087   for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
2088     Constant *Clause = LPI.getClause(i);
2089     if (LPI.isCatch(i)) {
2090       Assert1(isa<PointerType>(Clause->getType()),
2091               "Catch operand does not have pointer type!", &LPI);
2092     } else {
2093       Assert1(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
2094       Assert1(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
2095               "Filter operand is not an array of constants!", &LPI);
2096     }
2097   }
2098
2099   visitInstruction(LPI);
2100 }
2101
2102 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
2103   Instruction *Op = cast<Instruction>(I.getOperand(i));
2104   // If the we have an invalid invoke, don't try to compute the dominance.
2105   // We already reject it in the invoke specific checks and the dominance
2106   // computation doesn't handle multiple edges.
2107   if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
2108     if (II->getNormalDest() == II->getUnwindDest())
2109       return;
2110   }
2111
2112   const Use &U = I.getOperandUse(i);
2113   Assert2(InstsInThisBlock.count(Op) || DT.dominates(Op, U),
2114           "Instruction does not dominate all uses!", Op, &I);
2115 }
2116
2117 /// verifyInstruction - Verify that an instruction is well formed.
2118 ///
2119 void Verifier::visitInstruction(Instruction &I) {
2120   BasicBlock *BB = I.getParent();
2121   Assert1(BB, "Instruction not embedded in basic block!", &I);
2122
2123   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
2124     for (User *U : I.users()) {
2125       Assert1(U != (User*)&I || !DT.isReachableFromEntry(BB),
2126               "Only PHI nodes may reference their own value!", &I);
2127     }
2128   }
2129
2130   // Check that void typed values don't have names
2131   Assert1(!I.getType()->isVoidTy() || !I.hasName(),
2132           "Instruction has a name, but provides a void value!", &I);
2133
2134   // Check that the return value of the instruction is either void or a legal
2135   // value type.
2136   Assert1(I.getType()->isVoidTy() ||
2137           I.getType()->isFirstClassType(),
2138           "Instruction returns a non-scalar type!", &I);
2139
2140   // Check that the instruction doesn't produce metadata. Calls are already
2141   // checked against the callee type.
2142   Assert1(!I.getType()->isMetadataTy() ||
2143           isa<CallInst>(I) || isa<InvokeInst>(I),
2144           "Invalid use of metadata!", &I);
2145
2146   // Check that all uses of the instruction, if they are instructions
2147   // themselves, actually have parent basic blocks.  If the use is not an
2148   // instruction, it is an error!
2149   for (Use &U : I.uses()) {
2150     if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
2151       Assert2(Used->getParent() != nullptr, "Instruction referencing"
2152               " instruction not embedded in a basic block!", &I, Used);
2153     else {
2154       CheckFailed("Use of instruction is not an instruction!", U);
2155       return;
2156     }
2157   }
2158
2159   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2160     Assert1(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
2161
2162     // Check to make sure that only first-class-values are operands to
2163     // instructions.
2164     if (!I.getOperand(i)->getType()->isFirstClassType()) {
2165       Assert1(0, "Instruction operands must be first-class values!", &I);
2166     }
2167
2168     if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
2169       // Check to make sure that the "address of" an intrinsic function is never
2170       // taken.
2171       Assert1(!F->isIntrinsic() || i == (isa<CallInst>(I) ? e-1 : 0),
2172               "Cannot take the address of an intrinsic!", &I);
2173       Assert1(!F->isIntrinsic() || isa<CallInst>(I) ||
2174               F->getIntrinsicID() == Intrinsic::donothing,
2175               "Cannot invoke an intrinsinc other than donothing", &I);
2176       Assert1(F->getParent() == M, "Referencing function in another module!",
2177               &I);
2178     } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
2179       Assert1(OpBB->getParent() == BB->getParent(),
2180               "Referring to a basic block in another function!", &I);
2181     } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
2182       Assert1(OpArg->getParent() == BB->getParent(),
2183               "Referring to an argument in another function!", &I);
2184     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
2185       Assert1(GV->getParent() == M, "Referencing global in another module!",
2186               &I);
2187     } else if (isa<Instruction>(I.getOperand(i))) {
2188       verifyDominatesUse(I, i);
2189     } else if (isa<InlineAsm>(I.getOperand(i))) {
2190       Assert1((i + 1 == e && isa<CallInst>(I)) ||
2191               (i + 3 == e && isa<InvokeInst>(I)),
2192               "Cannot take the address of an inline asm!", &I);
2193     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
2194       if (CE->getType()->isPtrOrPtrVectorTy()) {
2195         // If we have a ConstantExpr pointer, we need to see if it came from an
2196         // illegal bitcast (inttoptr <constant int> )
2197         SmallVector<const ConstantExpr *, 4> Stack;
2198         SmallPtrSet<const ConstantExpr *, 4> Visited;
2199         Stack.push_back(CE);
2200
2201         while (!Stack.empty()) {
2202           const ConstantExpr *V = Stack.pop_back_val();
2203           if (!Visited.insert(V))
2204             continue;
2205
2206           VerifyConstantExprBitcastType(V);
2207
2208           for (unsigned I = 0, N = V->getNumOperands(); I != N; ++I) {
2209             if (ConstantExpr *Op = dyn_cast<ConstantExpr>(V->getOperand(I)))
2210               Stack.push_back(Op);
2211           }
2212         }
2213       }
2214     }
2215   }
2216
2217   if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
2218     Assert1(I.getType()->isFPOrFPVectorTy(),
2219             "fpmath requires a floating point result!", &I);
2220     Assert1(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
2221     Value *Op0 = MD->getOperand(0);
2222     if (ConstantFP *CFP0 = dyn_cast_or_null<ConstantFP>(Op0)) {
2223       APFloat Accuracy = CFP0->getValueAPF();
2224       Assert1(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
2225               "fpmath accuracy not a positive number!", &I);
2226     } else {
2227       Assert1(false, "invalid fpmath accuracy!", &I);
2228     }
2229   }
2230
2231   MDNode *MD = I.getMetadata(LLVMContext::MD_range);
2232   Assert1(!MD || isa<LoadInst>(I), "Ranges are only for loads!", &I);
2233
2234   InstsInThisBlock.insert(&I);
2235 }
2236
2237 /// VerifyIntrinsicType - Verify that the specified type (which comes from an
2238 /// intrinsic argument or return value) matches the type constraints specified
2239 /// by the .td file (e.g. an "any integer" argument really is an integer).
2240 ///
2241 /// This return true on error but does not print a message.
2242 bool Verifier::VerifyIntrinsicType(Type *Ty,
2243                                    ArrayRef<Intrinsic::IITDescriptor> &Infos,
2244                                    SmallVectorImpl<Type*> &ArgTys) {
2245   using namespace Intrinsic;
2246
2247   // If we ran out of descriptors, there are too many arguments.
2248   if (Infos.empty()) return true;
2249   IITDescriptor D = Infos.front();
2250   Infos = Infos.slice(1);
2251
2252   switch (D.Kind) {
2253   case IITDescriptor::Void: return !Ty->isVoidTy();
2254   case IITDescriptor::VarArg: return true;
2255   case IITDescriptor::MMX:  return !Ty->isX86_MMXTy();
2256   case IITDescriptor::Metadata: return !Ty->isMetadataTy();
2257   case IITDescriptor::Half: return !Ty->isHalfTy();
2258   case IITDescriptor::Float: return !Ty->isFloatTy();
2259   case IITDescriptor::Double: return !Ty->isDoubleTy();
2260   case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
2261   case IITDescriptor::Vector: {
2262     VectorType *VT = dyn_cast<VectorType>(Ty);
2263     return !VT || VT->getNumElements() != D.Vector_Width ||
2264            VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
2265   }
2266   case IITDescriptor::Pointer: {
2267     PointerType *PT = dyn_cast<PointerType>(Ty);
2268     return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
2269            VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
2270   }
2271
2272   case IITDescriptor::Struct: {
2273     StructType *ST = dyn_cast<StructType>(Ty);
2274     if (!ST || ST->getNumElements() != D.Struct_NumElements)
2275       return true;
2276
2277     for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
2278       if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
2279         return true;
2280     return false;
2281   }
2282
2283   case IITDescriptor::Argument:
2284     // Two cases here - If this is the second occurrence of an argument, verify
2285     // that the later instance matches the previous instance.
2286     if (D.getArgumentNumber() < ArgTys.size())
2287       return Ty != ArgTys[D.getArgumentNumber()];
2288
2289     // Otherwise, if this is the first instance of an argument, record it and
2290     // verify the "Any" kind.
2291     assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
2292     ArgTys.push_back(Ty);
2293
2294     switch (D.getArgumentKind()) {
2295     case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
2296     case IITDescriptor::AK_AnyFloat:   return !Ty->isFPOrFPVectorTy();
2297     case IITDescriptor::AK_AnyVector:  return !isa<VectorType>(Ty);
2298     case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
2299     }
2300     llvm_unreachable("all argument kinds not covered");
2301
2302   case IITDescriptor::ExtendArgument: {
2303     // This may only be used when referring to a previous vector argument.
2304     if (D.getArgumentNumber() >= ArgTys.size())
2305       return true;
2306
2307     Type *NewTy = ArgTys[D.getArgumentNumber()];
2308     if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
2309       NewTy = VectorType::getExtendedElementVectorType(VTy);
2310     else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
2311       NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
2312     else
2313       return true;
2314
2315     return Ty != NewTy;
2316   }
2317   case IITDescriptor::TruncArgument: {
2318     // This may only be used when referring to a previous vector argument.
2319     if (D.getArgumentNumber() >= ArgTys.size())
2320       return true;
2321
2322     Type *NewTy = ArgTys[D.getArgumentNumber()];
2323     if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
2324       NewTy = VectorType::getTruncatedElementVectorType(VTy);
2325     else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
2326       NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
2327     else
2328       return true;
2329
2330     return Ty != NewTy;
2331   }
2332   case IITDescriptor::HalfVecArgument:
2333     // This may only be used when referring to a previous vector argument.
2334     return D.getArgumentNumber() >= ArgTys.size() ||
2335            !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
2336            VectorType::getHalfElementsVectorType(
2337                          cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
2338   }
2339   llvm_unreachable("unhandled");
2340 }
2341
2342 /// \brief Verify if the intrinsic has variable arguments.
2343 /// This method is intended to be called after all the fixed arguments have been
2344 /// verified first.
2345 ///
2346 /// This method returns true on error and does not print an error message.
2347 bool
2348 Verifier::VerifyIntrinsicIsVarArg(bool isVarArg,
2349                                   ArrayRef<Intrinsic::IITDescriptor> &Infos) {
2350   using namespace Intrinsic;
2351
2352   // If there are no descriptors left, then it can't be a vararg.
2353   if (Infos.empty())
2354     return isVarArg ? true : false;
2355
2356   // There should be only one descriptor remaining at this point.
2357   if (Infos.size() != 1)
2358     return true;
2359
2360   // Check and verify the descriptor.
2361   IITDescriptor D = Infos.front();
2362   Infos = Infos.slice(1);
2363   if (D.Kind == IITDescriptor::VarArg)
2364     return isVarArg ? false : true;
2365
2366   return true;
2367 }
2368
2369 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
2370 ///
2371 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
2372   Function *IF = CI.getCalledFunction();
2373   Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
2374           IF);
2375
2376   // Verify that the intrinsic prototype lines up with what the .td files
2377   // describe.
2378   FunctionType *IFTy = IF->getFunctionType();
2379   bool IsVarArg = IFTy->isVarArg();
2380
2381   SmallVector<Intrinsic::IITDescriptor, 8> Table;
2382   getIntrinsicInfoTableEntries(ID, Table);
2383   ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
2384
2385   SmallVector<Type *, 4> ArgTys;
2386   Assert1(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
2387           "Intrinsic has incorrect return type!", IF);
2388   for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
2389     Assert1(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
2390             "Intrinsic has incorrect argument type!", IF);
2391
2392   // Verify if the intrinsic call matches the vararg property.
2393   if (IsVarArg)
2394     Assert1(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
2395             "Intrinsic was not defined with variable arguments!", IF);
2396   else
2397     Assert1(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
2398             "Callsite was not defined with variable arguments!", IF);
2399
2400   // All descriptors should be absorbed by now.
2401   Assert1(TableRef.empty(), "Intrinsic has too few arguments!", IF);
2402
2403   // Now that we have the intrinsic ID and the actual argument types (and we
2404   // know they are legal for the intrinsic!) get the intrinsic name through the
2405   // usual means.  This allows us to verify the mangling of argument types into
2406   // the name.
2407   const std::string ExpectedName = Intrinsic::getName(ID, ArgTys);
2408   Assert1(ExpectedName == IF->getName(),
2409           "Intrinsic name not mangled correctly for type arguments! "
2410           "Should be: " + ExpectedName, IF);
2411
2412   // If the intrinsic takes MDNode arguments, verify that they are either global
2413   // or are local to *this* function.
2414   for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
2415     if (MDNode *MD = dyn_cast<MDNode>(CI.getArgOperand(i)))
2416       visitMDNode(*MD, CI.getParent()->getParent());
2417
2418   switch (ID) {
2419   default:
2420     break;
2421   case Intrinsic::ctlz:  // llvm.ctlz
2422   case Intrinsic::cttz:  // llvm.cttz
2423     Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
2424             "is_zero_undef argument of bit counting intrinsics must be a "
2425             "constant int", &CI);
2426     break;
2427   case Intrinsic::dbg_declare: {  // llvm.dbg.declare
2428     Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
2429                 "invalid llvm.dbg.declare intrinsic call 1", &CI);
2430     MDNode *MD = cast<MDNode>(CI.getArgOperand(0));
2431     Assert1(MD->getNumOperands() == 1,
2432                 "invalid llvm.dbg.declare intrinsic call 2", &CI);
2433   } break;
2434   case Intrinsic::memcpy:
2435   case Intrinsic::memmove:
2436   case Intrinsic::memset:
2437     Assert1(isa<ConstantInt>(CI.getArgOperand(3)),
2438             "alignment argument of memory intrinsics must be a constant int",
2439             &CI);
2440     Assert1(isa<ConstantInt>(CI.getArgOperand(4)),
2441             "isvolatile argument of memory intrinsics must be a constant int",
2442             &CI);
2443     break;
2444   case Intrinsic::gcroot:
2445   case Intrinsic::gcwrite:
2446   case Intrinsic::gcread:
2447     if (ID == Intrinsic::gcroot) {
2448       AllocaInst *AI =
2449         dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
2450       Assert1(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
2451       Assert1(isa<Constant>(CI.getArgOperand(1)),
2452               "llvm.gcroot parameter #2 must be a constant.", &CI);
2453       if (!AI->getType()->getElementType()->isPointerTy()) {
2454         Assert1(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
2455                 "llvm.gcroot parameter #1 must either be a pointer alloca, "
2456                 "or argument #2 must be a non-null constant.", &CI);
2457       }
2458     }
2459
2460     Assert1(CI.getParent()->getParent()->hasGC(),
2461             "Enclosing function does not use GC.", &CI);
2462     break;
2463   case Intrinsic::init_trampoline:
2464     Assert1(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
2465             "llvm.init_trampoline parameter #2 must resolve to a function.",
2466             &CI);
2467     break;
2468   case Intrinsic::prefetch:
2469     Assert1(isa<ConstantInt>(CI.getArgOperand(1)) &&
2470             isa<ConstantInt>(CI.getArgOperand(2)) &&
2471             cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
2472             cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
2473             "invalid arguments to llvm.prefetch",
2474             &CI);
2475     break;
2476   case Intrinsic::stackprotector:
2477     Assert1(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
2478             "llvm.stackprotector parameter #2 must resolve to an alloca.",
2479             &CI);
2480     break;
2481   case Intrinsic::lifetime_start:
2482   case Intrinsic::lifetime_end:
2483   case Intrinsic::invariant_start:
2484     Assert1(isa<ConstantInt>(CI.getArgOperand(0)),
2485             "size argument of memory use markers must be a constant integer",
2486             &CI);
2487     break;
2488   case Intrinsic::invariant_end:
2489     Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
2490             "llvm.invariant.end parameter #2 must be a constant integer", &CI);
2491     break;
2492   }
2493 }
2494
2495 void DebugInfoVerifier::verifyDebugInfo() {
2496   if (!VerifyDebugInfo)
2497     return;
2498
2499   DebugInfoFinder Finder;
2500   Finder.processModule(*M);
2501   processInstructions(Finder);
2502
2503   // Verify Debug Info.
2504   //
2505   // NOTE:  The loud braces are necessary for MSVC compatibility.
2506   for (DICompileUnit CU : Finder.compile_units()) {
2507     Assert1(CU.Verify(), "DICompileUnit does not Verify!", CU);
2508   }
2509   for (DISubprogram S : Finder.subprograms()) {
2510     Assert1(S.Verify(), "DISubprogram does not Verify!", S);
2511   }
2512   for (DIGlobalVariable GV : Finder.global_variables()) {
2513     Assert1(GV.Verify(), "DIGlobalVariable does not Verify!", GV);
2514   }
2515   for (DIType T : Finder.types()) {
2516     Assert1(T.Verify(), "DIType does not Verify!", T);
2517   }
2518   for (DIScope S : Finder.scopes()) {
2519     Assert1(S.Verify(), "DIScope does not Verify!", S);
2520   }
2521 }
2522
2523 void DebugInfoVerifier::processInstructions(DebugInfoFinder &Finder) {
2524   for (const Function &F : *M)
2525     for (auto I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
2526       if (MDNode *MD = I->getMetadata(LLVMContext::MD_dbg))
2527         Finder.processLocation(*M, DILocation(MD));
2528       if (const CallInst *CI = dyn_cast<CallInst>(&*I))
2529         processCallInst(Finder, *CI);
2530     }
2531 }
2532
2533 void DebugInfoVerifier::processCallInst(DebugInfoFinder &Finder,
2534                                         const CallInst &CI) {
2535   if (Function *F = CI.getCalledFunction())
2536     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
2537       switch (ID) {
2538       case Intrinsic::dbg_declare:
2539         Finder.processDeclare(*M, cast<DbgDeclareInst>(&CI));
2540         break;
2541       case Intrinsic::dbg_value:
2542         Finder.processValue(*M, cast<DbgValueInst>(&CI));
2543         break;
2544       default:
2545         break;
2546       }
2547 }
2548
2549 //===----------------------------------------------------------------------===//
2550 //  Implement the public interfaces to this file...
2551 //===----------------------------------------------------------------------===//
2552
2553 bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
2554   Function &F = const_cast<Function &>(f);
2555   assert(!F.isDeclaration() && "Cannot verify external functions");
2556
2557   raw_null_ostream NullStr;
2558   Verifier V(OS ? *OS : NullStr);
2559
2560   // Note that this function's return value is inverted from what you would
2561   // expect of a function called "verify".
2562   return !V.verify(F);
2563 }
2564
2565 bool llvm::verifyModule(const Module &M, raw_ostream *OS) {
2566   raw_null_ostream NullStr;
2567   Verifier V(OS ? *OS : NullStr);
2568
2569   bool Broken = false;
2570   for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
2571     if (!I->isDeclaration())
2572       Broken |= !V.verify(*I);
2573
2574   // Note that this function's return value is inverted from what you would
2575   // expect of a function called "verify".
2576   DebugInfoVerifier DIV(OS ? *OS : NullStr);
2577   return !V.verify(M) || !DIV.verify(M) || Broken;
2578 }
2579
2580 namespace {
2581 struct VerifierLegacyPass : public FunctionPass {
2582   static char ID;
2583
2584   Verifier V;
2585   bool FatalErrors;
2586
2587   VerifierLegacyPass() : FunctionPass(ID), FatalErrors(true) {
2588     initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
2589   }
2590   explicit VerifierLegacyPass(bool FatalErrors)
2591       : FunctionPass(ID), V(dbgs()), FatalErrors(FatalErrors) {
2592     initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
2593   }
2594
2595   bool runOnFunction(Function &F) override {
2596     if (!V.verify(F) && FatalErrors)
2597       report_fatal_error("Broken function found, compilation aborted!");
2598
2599     return false;
2600   }
2601
2602   bool doFinalization(Module &M) override {
2603     if (!V.verify(M) && FatalErrors)
2604       report_fatal_error("Broken module found, compilation aborted!");
2605
2606     return false;
2607   }
2608
2609   void getAnalysisUsage(AnalysisUsage &AU) const override {
2610     AU.setPreservesAll();
2611   }
2612 };
2613 struct DebugInfoVerifierLegacyPass : public ModulePass {
2614   static char ID;
2615
2616   DebugInfoVerifier V;
2617   bool FatalErrors;
2618
2619   DebugInfoVerifierLegacyPass() : ModulePass(ID), FatalErrors(true) {
2620     initializeDebugInfoVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
2621   }
2622   explicit DebugInfoVerifierLegacyPass(bool FatalErrors)
2623       : ModulePass(ID), V(dbgs()), FatalErrors(FatalErrors) {
2624     initializeDebugInfoVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
2625   }
2626
2627   bool runOnModule(Module &M) override {
2628     if (!V.verify(M) && FatalErrors)
2629       report_fatal_error("Broken debug info found, compilation aborted!");
2630
2631     return false;
2632   }
2633
2634   void getAnalysisUsage(AnalysisUsage &AU) const override {
2635     AU.setPreservesAll();
2636   }
2637 };
2638 }
2639
2640 char VerifierLegacyPass::ID = 0;
2641 INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
2642
2643 char DebugInfoVerifierLegacyPass::ID = 0;
2644 INITIALIZE_PASS(DebugInfoVerifierLegacyPass, "verify-di", "Debug Info Verifier",
2645                 false, false)
2646
2647 FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
2648   return new VerifierLegacyPass(FatalErrors);
2649 }
2650
2651 ModulePass *llvm::createDebugInfoVerifierPass(bool FatalErrors) {
2652   return new DebugInfoVerifierLegacyPass(FatalErrors);
2653 }
2654
2655 PreservedAnalyses VerifierPass::run(Module *M) {
2656   if (verifyModule(*M, &dbgs()) && FatalErrors)
2657     report_fatal_error("Broken module found, compilation aborted!");
2658
2659   return PreservedAnalyses::all();
2660 }
2661
2662 PreservedAnalyses VerifierPass::run(Function *F) {
2663   if (verifyFunction(*F, &dbgs()) && FatalErrors)
2664     report_fatal_error("Broken function found, compilation aborted!");
2665
2666   return PreservedAnalyses::all();
2667 }