1249259Sdim//===-- Verifier.cpp - Implement the Module Verifier -----------------------==// 2249259Sdim// 3249259Sdim// The LLVM Compiler Infrastructure 4249259Sdim// 5249259Sdim// This file is distributed under the University of Illinois Open Source 6249259Sdim// License. See LICENSE.TXT for details. 7249259Sdim// 8249259Sdim//===----------------------------------------------------------------------===// 9249259Sdim// 10249259Sdim// This file defines the function verifier interface, that can be used for some 11249259Sdim// sanity checking of input to the system. 12249259Sdim// 13249259Sdim// Note that this does not provide full `Java style' security and verifications, 14249259Sdim// instead it just tries to ensure that code is well-formed. 15249259Sdim// 16249259Sdim// * Both of a binary operator's parameters are of the same type 17249259Sdim// * Verify that the indices of mem access instructions match other operands 18249259Sdim// * Verify that arithmetic and other things are only performed on first-class 19249259Sdim// types. Verify that shifts & logicals only happen on integrals f.e. 20249259Sdim// * All of the constants in a switch statement are of the correct type 21249259Sdim// * The code is in valid SSA form 22249259Sdim// * It should be illegal to put a label into any other type (like a structure) 23249259Sdim// or to return one. [except constant arrays!] 24249259Sdim// * Only phi nodes can be self referential: 'add i32 %0, %0 ; <int>:0' is bad 25249259Sdim// * PHI nodes must have an entry for each predecessor, with no extras. 26249259Sdim// * PHI nodes must be the first thing in a basic block, all grouped together 27249259Sdim// * PHI nodes must have at least one entry 28249259Sdim// * All basic blocks should only end with terminator insts, not contain them 29249259Sdim// * The entry node to a function must not have predecessors 30249259Sdim// * All Instructions must be embedded into a basic block 31249259Sdim// * Functions cannot take a void-typed parameter 32249259Sdim// * Verify that a function's argument list agrees with it's declared type. 33249259Sdim// * It is illegal to specify a name for a void value. 34249259Sdim// * It is illegal to have a internal global value with no initializer 35249259Sdim// * It is illegal to have a ret instruction that returns a value that does not 36249259Sdim// agree with the function return value type. 37249259Sdim// * Function call argument types match the function prototype 38249259Sdim// * A landing pad is defined by a landingpad instruction, and can be jumped to 39249259Sdim// only by the unwind edge of an invoke instruction. 40249259Sdim// * A landingpad instruction must be the first non-PHI instruction in the 41249259Sdim// block. 42296417Sdim// * Landingpad instructions must be in a function with a personality function. 43249259Sdim// * All other things that are tested by asserts spread about the code... 44249259Sdim// 45249259Sdim//===----------------------------------------------------------------------===// 46249259Sdim 47276479Sdim#include "llvm/IR/Verifier.h" 48296417Sdim#include "llvm/ADT/MapVector.h" 49249259Sdim#include "llvm/ADT/STLExtras.h" 50249259Sdim#include "llvm/ADT/SetVector.h" 51249259Sdim#include "llvm/ADT/SmallPtrSet.h" 52249259Sdim#include "llvm/ADT/SmallVector.h" 53249259Sdim#include "llvm/ADT/StringExtras.h" 54276479Sdim#include "llvm/IR/CFG.h" 55276479Sdim#include "llvm/IR/CallSite.h" 56249259Sdim#include "llvm/IR/CallingConv.h" 57276479Sdim#include "llvm/IR/ConstantRange.h" 58249259Sdim#include "llvm/IR/Constants.h" 59261991Sdim#include "llvm/IR/DataLayout.h" 60276479Sdim#include "llvm/IR/DebugInfo.h" 61249259Sdim#include "llvm/IR/DerivedTypes.h" 62276479Sdim#include "llvm/IR/Dominators.h" 63249259Sdim#include "llvm/IR/InlineAsm.h" 64276479Sdim#include "llvm/IR/InstIterator.h" 65276479Sdim#include "llvm/IR/InstVisitor.h" 66249259Sdim#include "llvm/IR/IntrinsicInst.h" 67249259Sdim#include "llvm/IR/LLVMContext.h" 68249259Sdim#include "llvm/IR/Metadata.h" 69249259Sdim#include "llvm/IR/Module.h" 70276479Sdim#include "llvm/IR/PassManager.h" 71280031Sdim#include "llvm/IR/Statepoint.h" 72249259Sdim#include "llvm/Pass.h" 73261991Sdim#include "llvm/Support/CommandLine.h" 74249259Sdim#include "llvm/Support/Debug.h" 75249259Sdim#include "llvm/Support/ErrorHandling.h" 76249259Sdim#include "llvm/Support/raw_ostream.h" 77249259Sdim#include <algorithm> 78249259Sdim#include <cstdarg> 79249259Sdimusing namespace llvm; 80249259Sdim 81288943Sdimstatic cl::opt<bool> VerifyDebugInfo("verify-debug-info", cl::init(true)); 82261991Sdim 83276479Sdimnamespace { 84276479Sdimstruct VerifierSupport { 85276479Sdim raw_ostream &OS; 86276479Sdim const Module *M; 87249259Sdim 88276479Sdim /// \brief Track the brokenness of the module while recursively visiting. 89276479Sdim bool Broken; 90249259Sdim 91276479Sdim explicit VerifierSupport(raw_ostream &OS) 92276479Sdim : OS(OS), M(nullptr), Broken(false) {} 93249259Sdim 94288943Sdimprivate: 95296417Sdim template <class NodeTy> void Write(const ilist_iterator<NodeTy> &I) { 96296417Sdim Write(&*I); 97296417Sdim } 98296417Sdim 99296417Sdim void Write(const Module *M) { 100296417Sdim if (!M) 101296417Sdim return; 102296417Sdim OS << "; ModuleID = '" << M->getModuleIdentifier() << "'\n"; 103296417Sdim } 104296417Sdim 105288943Sdim void Write(const Value *V) { 106276479Sdim if (!V) 107276479Sdim return; 108276479Sdim if (isa<Instruction>(V)) { 109276479Sdim OS << *V << '\n'; 110276479Sdim } else { 111276479Sdim V->printAsOperand(OS, true, M); 112276479Sdim OS << '\n'; 113249259Sdim } 114276479Sdim } 115288943Sdim void Write(ImmutableCallSite CS) { 116288943Sdim Write(CS.getInstruction()); 117288943Sdim } 118249259Sdim 119288943Sdim void Write(const Metadata *MD) { 120280031Sdim if (!MD) 121280031Sdim return; 122288943Sdim MD->print(OS, M); 123280031Sdim OS << '\n'; 124280031Sdim } 125280031Sdim 126288943Sdim template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) { 127288943Sdim Write(MD.get()); 128288943Sdim } 129288943Sdim 130288943Sdim void Write(const NamedMDNode *NMD) { 131288943Sdim if (!NMD) 132288943Sdim return; 133288943Sdim NMD->print(OS); 134288943Sdim OS << '\n'; 135288943Sdim } 136288943Sdim 137288943Sdim void Write(Type *T) { 138276479Sdim if (!T) 139276479Sdim return; 140276479Sdim OS << ' ' << *T; 141276479Sdim } 142249259Sdim 143288943Sdim void Write(const Comdat *C) { 144276479Sdim if (!C) 145276479Sdim return; 146276479Sdim OS << *C; 147276479Sdim } 148249259Sdim 149296417Sdim template <typename T> void Write(ArrayRef<T> Vs) { 150296417Sdim for (const T &V : Vs) 151296417Sdim Write(V); 152296417Sdim } 153296417Sdim 154288943Sdim template <typename T1, typename... Ts> 155288943Sdim void WriteTs(const T1 &V1, const Ts &... Vs) { 156288943Sdim Write(V1); 157288943Sdim WriteTs(Vs...); 158276479Sdim } 159249259Sdim 160288943Sdim template <typename... Ts> void WriteTs() {} 161280031Sdim 162288943Sdimpublic: 163288943Sdim /// \brief A check failed, so printout out the condition and the message. 164288943Sdim /// 165288943Sdim /// This provides a nice place to put a breakpoint if you want to see why 166288943Sdim /// something is not correct. 167288943Sdim void CheckFailed(const Twine &Message) { 168288943Sdim OS << Message << '\n'; 169280031Sdim Broken = true; 170280031Sdim } 171280031Sdim 172288943Sdim /// \brief A check failed (with values to print). 173288943Sdim /// 174288943Sdim /// This calls the Message-only version so that the above is easier to set a 175288943Sdim /// breakpoint on. 176288943Sdim template <typename T1, typename... Ts> 177288943Sdim void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) { 178288943Sdim CheckFailed(Message); 179288943Sdim WriteTs(V1, Vs...); 180276479Sdim } 181288943Sdim}; 182249259Sdim 183276479Sdimclass Verifier : public InstVisitor<Verifier>, VerifierSupport { 184276479Sdim friend class InstVisitor<Verifier>; 185249259Sdim 186276479Sdim LLVMContext *Context; 187276479Sdim DominatorTree DT; 188261991Sdim 189276479Sdim /// \brief When verifying a basic block, keep track of all of the 190276479Sdim /// instructions we have seen so far. 191276479Sdim /// 192276479Sdim /// This allows us to do efficient dominance checks for the case when an 193276479Sdim /// instruction has an operand that is an instruction in the same block. 194276479Sdim SmallPtrSet<Instruction *, 16> InstsInThisBlock; 195249259Sdim 196276479Sdim /// \brief Keep track of the metadata nodes that have been checked already. 197288943Sdim SmallPtrSet<const Metadata *, 32> MDNodes; 198249259Sdim 199288943Sdim /// \brief Track unresolved string-based type references. 200288943Sdim SmallDenseMap<const MDString *, const MDNode *, 32> UnresolvedTypeRefs; 201261991Sdim 202296417Sdim /// \brief The result type for a landingpad. 203296417Sdim Type *LandingPadResultTy; 204296417Sdim 205288943Sdim /// \brief Whether we've seen a call to @llvm.localescape in this function 206280031Sdim /// already. 207288943Sdim bool SawFrameEscape; 208280031Sdim 209288943Sdim /// Stores the count of how many objects were passed to llvm.localescape for a 210288943Sdim /// given function and the largest index passed to llvm.localrecover. 211288943Sdim DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo; 212288943Sdim 213296417Sdim // Maps catchswitches and cleanuppads that unwind to siblings to the 214296417Sdim // terminators that indicate the unwind, used to detect cycles therein. 215296417Sdim MapVector<Instruction *, TerminatorInst *> SiblingFuncletInfo; 216296417Sdim 217296417Sdim /// Cache of constants visited in search of ConstantExprs. 218296417Sdim SmallPtrSet<const Constant *, 32> ConstantExprVisited; 219296417Sdim 220296417Sdim void checkAtomicMemAccessSize(const Module *M, Type *Ty, 221296417Sdim const Instruction *I); 222276479Sdimpublic: 223288943Sdim explicit Verifier(raw_ostream &OS) 224296417Sdim : VerifierSupport(OS), Context(nullptr), LandingPadResultTy(nullptr), 225296417Sdim SawFrameEscape(false) {} 226249259Sdim 227276479Sdim bool verify(const Function &F) { 228276479Sdim M = F.getParent(); 229276479Sdim Context = &M->getContext(); 230249259Sdim 231276479Sdim // First ensure the function is well-enough formed to compute dominance 232276479Sdim // information. 233276479Sdim if (F.empty()) { 234276479Sdim OS << "Function '" << F.getName() 235276479Sdim << "' does not contain an entry block!\n"; 236276479Sdim return false; 237249259Sdim } 238276479Sdim for (Function::const_iterator I = F.begin(), E = F.end(); I != E; ++I) { 239276479Sdim if (I->empty() || !I->back().isTerminator()) { 240276479Sdim OS << "Basic Block in function '" << F.getName() 241276479Sdim << "' does not have terminator!\n"; 242276479Sdim I->printAsOperand(OS, true); 243276479Sdim OS << "\n"; 244276479Sdim return false; 245249259Sdim } 246276479Sdim } 247249259Sdim 248276479Sdim // Now directly compute a dominance tree. We don't rely on the pass 249276479Sdim // manager to provide this as it isolates us from a potentially 250276479Sdim // out-of-date dominator tree and makes it significantly more complex to 251276479Sdim // run this code outside of a pass manager. 252276479Sdim // FIXME: It's really gross that we have to cast away constness here. 253276479Sdim DT.recalculate(const_cast<Function &>(F)); 254249259Sdim 255276479Sdim Broken = false; 256276479Sdim // FIXME: We strip const here because the inst visitor strips const. 257276479Sdim visit(const_cast<Function &>(F)); 258296417Sdim verifySiblingFuncletUnwinds(); 259276479Sdim InstsInThisBlock.clear(); 260296417Sdim LandingPadResultTy = nullptr; 261288943Sdim SawFrameEscape = false; 262296417Sdim SiblingFuncletInfo.clear(); 263249259Sdim 264276479Sdim return !Broken; 265276479Sdim } 266249259Sdim 267276479Sdim bool verify(const Module &M) { 268276479Sdim this->M = &M; 269276479Sdim Context = &M.getContext(); 270276479Sdim Broken = false; 271249259Sdim 272276479Sdim // Scan through, checking all of the external function's linkage now... 273276479Sdim for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) { 274276479Sdim visitGlobalValue(*I); 275261991Sdim 276276479Sdim // Check to make sure function prototypes are okay. 277276479Sdim if (I->isDeclaration()) 278276479Sdim visitFunction(*I); 279249259Sdim } 280249259Sdim 281288943Sdim // Now that we've visited every function, verify that we never asked to 282288943Sdim // recover a frame index that wasn't escaped. 283288943Sdim verifyFrameRecoverIndices(); 284288943Sdim 285276479Sdim for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); 286276479Sdim I != E; ++I) 287276479Sdim visitGlobalVariable(*I); 288249259Sdim 289276479Sdim for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end(); 290276479Sdim I != E; ++I) 291276479Sdim visitGlobalAlias(*I); 292249259Sdim 293276479Sdim for (Module::const_named_metadata_iterator I = M.named_metadata_begin(), 294276479Sdim E = M.named_metadata_end(); 295276479Sdim I != E; ++I) 296276479Sdim visitNamedMDNode(*I); 297249259Sdim 298276479Sdim for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable()) 299276479Sdim visitComdat(SMEC.getValue()); 300249259Sdim 301276479Sdim visitModuleFlags(M); 302276479Sdim visitModuleIdents(M); 303249259Sdim 304288943Sdim // Verify type referneces last. 305288943Sdim verifyTypeRefs(); 306288943Sdim 307276479Sdim return !Broken; 308276479Sdim } 309249259Sdim 310276479Sdimprivate: 311276479Sdim // Verification methods... 312276479Sdim void visitGlobalValue(const GlobalValue &GV); 313276479Sdim void visitGlobalVariable(const GlobalVariable &GV); 314276479Sdim void visitGlobalAlias(const GlobalAlias &GA); 315276479Sdim void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C); 316280031Sdim void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited, 317276479Sdim const GlobalAlias &A, const Constant &C); 318276479Sdim void visitNamedMDNode(const NamedMDNode &NMD); 319288943Sdim void visitMDNode(const MDNode &MD); 320288943Sdim void visitMetadataAsValue(const MetadataAsValue &MD, Function *F); 321288943Sdim void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F); 322276479Sdim void visitComdat(const Comdat &C); 323276479Sdim void visitModuleIdents(const Module &M); 324276479Sdim void visitModuleFlags(const Module &M); 325276479Sdim void visitModuleFlag(const MDNode *Op, 326276479Sdim DenseMap<const MDString *, const MDNode *> &SeenIDs, 327276479Sdim SmallVectorImpl<const MDNode *> &Requirements); 328276479Sdim void visitFunction(const Function &F); 329276479Sdim void visitBasicBlock(BasicBlock &BB); 330280031Sdim void visitRangeMetadata(Instruction& I, MDNode* Range, Type* Ty); 331296417Sdim void visitDereferenceableMetadata(Instruction& I, MDNode* MD); 332249259Sdim 333288943Sdim template <class Ty> bool isValidMetadataArray(const MDTuple &N); 334288943Sdim#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N); 335288943Sdim#include "llvm/IR/Metadata.def" 336288943Sdim void visitDIScope(const DIScope &N); 337288943Sdim void visitDIVariable(const DIVariable &N); 338288943Sdim void visitDILexicalBlockBase(const DILexicalBlockBase &N); 339288943Sdim void visitDITemplateParameter(const DITemplateParameter &N); 340280031Sdim 341288943Sdim void visitTemplateParams(const MDNode &N, const Metadata &RawParams); 342288943Sdim 343288943Sdim /// \brief Check for a valid string-based type reference. 344288943Sdim /// 345288943Sdim /// Checks if \c MD is a string-based type reference. If it is, keeps track 346288943Sdim /// of it (and its user, \c N) for error messages later. 347288943Sdim bool isValidUUID(const MDNode &N, const Metadata *MD); 348288943Sdim 349288943Sdim /// \brief Check for a valid type reference. 350288943Sdim /// 351288943Sdim /// Checks for subclasses of \a DIType, or \a isValidUUID(). 352288943Sdim bool isTypeRef(const MDNode &N, const Metadata *MD); 353288943Sdim 354288943Sdim /// \brief Check for a valid scope reference. 355288943Sdim /// 356288943Sdim /// Checks for subclasses of \a DIScope, or \a isValidUUID(). 357288943Sdim bool isScopeRef(const MDNode &N, const Metadata *MD); 358288943Sdim 359288943Sdim /// \brief Check for a valid debug info reference. 360288943Sdim /// 361288943Sdim /// Checks for subclasses of \a DINode, or \a isValidUUID(). 362288943Sdim bool isDIRef(const MDNode &N, const Metadata *MD); 363288943Sdim 364276479Sdim // InstVisitor overrides... 365276479Sdim using InstVisitor<Verifier>::visit; 366276479Sdim void visit(Instruction &I); 367261991Sdim 368276479Sdim void visitTruncInst(TruncInst &I); 369276479Sdim void visitZExtInst(ZExtInst &I); 370276479Sdim void visitSExtInst(SExtInst &I); 371276479Sdim void visitFPTruncInst(FPTruncInst &I); 372276479Sdim void visitFPExtInst(FPExtInst &I); 373276479Sdim void visitFPToUIInst(FPToUIInst &I); 374276479Sdim void visitFPToSIInst(FPToSIInst &I); 375276479Sdim void visitUIToFPInst(UIToFPInst &I); 376276479Sdim void visitSIToFPInst(SIToFPInst &I); 377276479Sdim void visitIntToPtrInst(IntToPtrInst &I); 378276479Sdim void visitPtrToIntInst(PtrToIntInst &I); 379276479Sdim void visitBitCastInst(BitCastInst &I); 380276479Sdim void visitAddrSpaceCastInst(AddrSpaceCastInst &I); 381276479Sdim void visitPHINode(PHINode &PN); 382276479Sdim void visitBinaryOperator(BinaryOperator &B); 383276479Sdim void visitICmpInst(ICmpInst &IC); 384276479Sdim void visitFCmpInst(FCmpInst &FC); 385276479Sdim void visitExtractElementInst(ExtractElementInst &EI); 386276479Sdim void visitInsertElementInst(InsertElementInst &EI); 387276479Sdim void visitShuffleVectorInst(ShuffleVectorInst &EI); 388276479Sdim void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); } 389276479Sdim void visitCallInst(CallInst &CI); 390276479Sdim void visitInvokeInst(InvokeInst &II); 391276479Sdim void visitGetElementPtrInst(GetElementPtrInst &GEP); 392276479Sdim void visitLoadInst(LoadInst &LI); 393276479Sdim void visitStoreInst(StoreInst &SI); 394276479Sdim void verifyDominatesUse(Instruction &I, unsigned i); 395276479Sdim void visitInstruction(Instruction &I); 396276479Sdim void visitTerminatorInst(TerminatorInst &I); 397276479Sdim void visitBranchInst(BranchInst &BI); 398276479Sdim void visitReturnInst(ReturnInst &RI); 399276479Sdim void visitSwitchInst(SwitchInst &SI); 400276479Sdim void visitIndirectBrInst(IndirectBrInst &BI); 401276479Sdim void visitSelectInst(SelectInst &SI); 402276479Sdim void visitUserOp1(Instruction &I); 403276479Sdim void visitUserOp2(Instruction &I) { visitUserOp1(I); } 404288943Sdim void visitIntrinsicCallSite(Intrinsic::ID ID, CallSite CS); 405288943Sdim template <class DbgIntrinsicTy> 406288943Sdim void visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII); 407276479Sdim void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI); 408276479Sdim void visitAtomicRMWInst(AtomicRMWInst &RMWI); 409276479Sdim void visitFenceInst(FenceInst &FI); 410276479Sdim void visitAllocaInst(AllocaInst &AI); 411276479Sdim void visitExtractValueInst(ExtractValueInst &EVI); 412276479Sdim void visitInsertValueInst(InsertValueInst &IVI); 413296417Sdim void visitEHPadPredecessors(Instruction &I); 414276479Sdim void visitLandingPadInst(LandingPadInst &LPI); 415296417Sdim void visitCatchPadInst(CatchPadInst &CPI); 416296417Sdim void visitCatchReturnInst(CatchReturnInst &CatchReturn); 417296417Sdim void visitCleanupPadInst(CleanupPadInst &CPI); 418296417Sdim void visitFuncletPadInst(FuncletPadInst &FPI); 419296417Sdim void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch); 420296417Sdim void visitCleanupReturnInst(CleanupReturnInst &CRI); 421261991Sdim 422276479Sdim void VerifyCallSite(CallSite CS); 423276479Sdim void verifyMustTailCall(CallInst &CI); 424276479Sdim bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT, 425276479Sdim unsigned ArgNo, std::string &Suffix); 426276479Sdim bool VerifyIntrinsicType(Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos, 427276479Sdim SmallVectorImpl<Type *> &ArgTys); 428276479Sdim bool VerifyIntrinsicIsVarArg(bool isVarArg, 429276479Sdim ArrayRef<Intrinsic::IITDescriptor> &Infos); 430276479Sdim bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params); 431276479Sdim void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx, bool isFunction, 432276479Sdim const Value *V); 433276479Sdim void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty, 434276479Sdim bool isReturnValue, const Value *V); 435276479Sdim void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs, 436276479Sdim const Value *V); 437288943Sdim void VerifyFunctionMetadata( 438288943Sdim const SmallVector<std::pair<unsigned, MDNode *>, 4> MDs); 439249259Sdim 440296417Sdim void visitConstantExprsRecursively(const Constant *EntryC); 441296417Sdim void visitConstantExpr(const ConstantExpr *CE); 442288943Sdim void VerifyStatepoint(ImmutableCallSite CS); 443288943Sdim void verifyFrameRecoverIndices(); 444296417Sdim void verifySiblingFuncletUnwinds(); 445249259Sdim 446288943Sdim // Module-level debug info verification... 447288943Sdim void verifyTypeRefs(); 448288943Sdim template <class MapTy> 449288943Sdim void verifyBitPieceExpression(const DbgInfoIntrinsic &I, 450288943Sdim const MapTy &TypeRefs); 451288943Sdim void visitUnresolvedTypeRef(const MDString *S, const MDNode *N); 452276479Sdim}; 453249259Sdim} // End anonymous namespace 454249259Sdim 455249259Sdim// Assert - We know that cond should be true, if not print an error message. 456288943Sdim#define Assert(C, ...) \ 457288943Sdim do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (0) 458249259Sdim 459249259Sdimvoid Verifier::visit(Instruction &I) { 460249259Sdim for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) 461288943Sdim Assert(I.getOperand(i) != nullptr, "Operand is null", &I); 462249259Sdim InstVisitor<Verifier>::visit(I); 463249259Sdim} 464249259Sdim 465249259Sdim 466276479Sdimvoid Verifier::visitGlobalValue(const GlobalValue &GV) { 467288943Sdim Assert(!GV.isDeclaration() || GV.hasExternalLinkage() || 468288943Sdim GV.hasExternalWeakLinkage(), 469288943Sdim "Global is external, but doesn't have external or weak linkage!", &GV); 470249259Sdim 471288943Sdim Assert(GV.getAlignment() <= Value::MaximumAlignment, 472288943Sdim "huge alignment values are unsupported", &GV); 473288943Sdim Assert(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV), 474288943Sdim "Only global variables can have appending linkage!", &GV); 475249259Sdim 476249259Sdim if (GV.hasAppendingLinkage()) { 477276479Sdim const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV); 478288943Sdim Assert(GVar && GVar->getValueType()->isArrayTy(), 479288943Sdim "Only global arrays can have appending linkage!", GVar); 480249259Sdim } 481288943Sdim 482288943Sdim if (GV.isDeclarationForLinker()) 483288943Sdim Assert(!GV.hasComdat(), "Declaration may not be in a Comdat!", &GV); 484249259Sdim} 485249259Sdim 486276479Sdimvoid Verifier::visitGlobalVariable(const GlobalVariable &GV) { 487249259Sdim if (GV.hasInitializer()) { 488288943Sdim Assert(GV.getInitializer()->getType() == GV.getType()->getElementType(), 489288943Sdim "Global variable initializer type does not match global " 490288943Sdim "variable type!", 491288943Sdim &GV); 492249259Sdim 493249259Sdim // If the global has common linkage, it must have a zero initializer and 494249259Sdim // cannot be constant. 495249259Sdim if (GV.hasCommonLinkage()) { 496288943Sdim Assert(GV.getInitializer()->isNullValue(), 497288943Sdim "'common' global must have a zero initializer!", &GV); 498288943Sdim Assert(!GV.isConstant(), "'common' global may not be marked constant!", 499288943Sdim &GV); 500288943Sdim Assert(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV); 501249259Sdim } 502249259Sdim } else { 503288943Sdim Assert(GV.hasExternalLinkage() || GV.hasExternalWeakLinkage(), 504288943Sdim "invalid linkage type for global declaration", &GV); 505249259Sdim } 506249259Sdim 507249259Sdim if (GV.hasName() && (GV.getName() == "llvm.global_ctors" || 508249259Sdim GV.getName() == "llvm.global_dtors")) { 509288943Sdim Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(), 510288943Sdim "invalid linkage for intrinsic global variable", &GV); 511249259Sdim // Don't worry about emitting an error for it not being an array, 512249259Sdim // visitGlobalValue will complain on appending non-array. 513288943Sdim if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getValueType())) { 514249259Sdim StructType *STy = dyn_cast<StructType>(ATy->getElementType()); 515249259Sdim PointerType *FuncPtrTy = 516249259Sdim FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo(); 517276479Sdim // FIXME: Reject the 2-field form in LLVM 4.0. 518288943Sdim Assert(STy && 519288943Sdim (STy->getNumElements() == 2 || STy->getNumElements() == 3) && 520288943Sdim STy->getTypeAtIndex(0u)->isIntegerTy(32) && 521288943Sdim STy->getTypeAtIndex(1) == FuncPtrTy, 522288943Sdim "wrong type for intrinsic global variable", &GV); 523276479Sdim if (STy->getNumElements() == 3) { 524276479Sdim Type *ETy = STy->getTypeAtIndex(2); 525288943Sdim Assert(ETy->isPointerTy() && 526288943Sdim cast<PointerType>(ETy)->getElementType()->isIntegerTy(8), 527288943Sdim "wrong type for intrinsic global variable", &GV); 528276479Sdim } 529249259Sdim } 530249259Sdim } 531249259Sdim 532251662Sdim if (GV.hasName() && (GV.getName() == "llvm.used" || 533261991Sdim GV.getName() == "llvm.compiler.used")) { 534288943Sdim Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(), 535288943Sdim "invalid linkage for intrinsic global variable", &GV); 536288943Sdim Type *GVType = GV.getValueType(); 537251662Sdim if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) { 538251662Sdim PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType()); 539288943Sdim Assert(PTy, "wrong type for intrinsic global variable", &GV); 540251662Sdim if (GV.hasInitializer()) { 541276479Sdim const Constant *Init = GV.getInitializer(); 542276479Sdim const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init); 543288943Sdim Assert(InitArray, "wrong initalizer for intrinsic global variable", 544288943Sdim Init); 545251662Sdim for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) { 546261991Sdim Value *V = Init->getOperand(i)->stripPointerCastsNoFollowAliases(); 547288943Sdim Assert(isa<GlobalVariable>(V) || isa<Function>(V) || 548288943Sdim isa<GlobalAlias>(V), 549288943Sdim "invalid llvm.used member", V); 550288943Sdim Assert(V->hasName(), "members of llvm.used must be named", V); 551251662Sdim } 552251662Sdim } 553251662Sdim } 554251662Sdim } 555251662Sdim 556288943Sdim Assert(!GV.hasDLLImportStorageClass() || 557288943Sdim (GV.isDeclaration() && GV.hasExternalLinkage()) || 558288943Sdim GV.hasAvailableExternallyLinkage(), 559288943Sdim "Global is marked as dllimport, but not external", &GV); 560276479Sdim 561261991Sdim if (!GV.hasInitializer()) { 562261991Sdim visitGlobalValue(GV); 563261991Sdim return; 564261991Sdim } 565261991Sdim 566261991Sdim // Walk any aggregate initializers looking for bitcasts between address spaces 567296417Sdim visitConstantExprsRecursively(GV.getInitializer()); 568261991Sdim 569249259Sdim visitGlobalValue(GV); 570249259Sdim} 571249259Sdim 572276479Sdimvoid Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) { 573276479Sdim SmallPtrSet<const GlobalAlias*, 4> Visited; 574276479Sdim Visited.insert(&GA); 575276479Sdim visitAliaseeSubExpr(Visited, GA, C); 576276479Sdim} 577249259Sdim 578280031Sdimvoid Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited, 579276479Sdim const GlobalAlias &GA, const Constant &C) { 580276479Sdim if (const auto *GV = dyn_cast<GlobalValue>(&C)) { 581296417Sdim Assert(!GV->isDeclarationForLinker(), "Alias must point to a definition", 582296417Sdim &GA); 583261991Sdim 584276479Sdim if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) { 585288943Sdim Assert(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA); 586261991Sdim 587288943Sdim Assert(!GA2->mayBeOverridden(), "Alias cannot point to a weak alias", 588288943Sdim &GA); 589276479Sdim } else { 590276479Sdim // Only continue verifying subexpressions of GlobalAliases. 591276479Sdim // Do not recurse into global initializers. 592276479Sdim return; 593261991Sdim } 594249259Sdim } 595249259Sdim 596276479Sdim if (const auto *CE = dyn_cast<ConstantExpr>(&C)) 597296417Sdim visitConstantExprsRecursively(CE); 598249259Sdim 599276479Sdim for (const Use &U : C.operands()) { 600276479Sdim Value *V = &*U; 601276479Sdim if (const auto *GA2 = dyn_cast<GlobalAlias>(V)) 602276479Sdim visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee()); 603276479Sdim else if (const auto *C2 = dyn_cast<Constant>(V)) 604276479Sdim visitAliaseeSubExpr(Visited, GA, *C2); 605276479Sdim } 606276479Sdim} 607276479Sdim 608276479Sdimvoid Verifier::visitGlobalAlias(const GlobalAlias &GA) { 609288943Sdim Assert(GlobalAlias::isValidLinkage(GA.getLinkage()), 610288943Sdim "Alias should have private, internal, linkonce, weak, linkonce_odr, " 611288943Sdim "weak_odr, or external linkage!", 612288943Sdim &GA); 613276479Sdim const Constant *Aliasee = GA.getAliasee(); 614288943Sdim Assert(Aliasee, "Aliasee cannot be NULL!", &GA); 615288943Sdim Assert(GA.getType() == Aliasee->getType(), 616288943Sdim "Alias and aliasee types should match!", &GA); 617276479Sdim 618288943Sdim Assert(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee), 619288943Sdim "Aliasee should be either GlobalValue or ConstantExpr", &GA); 620276479Sdim 621276479Sdim visitAliaseeSubExpr(GA, *Aliasee); 622276479Sdim 623249259Sdim visitGlobalValue(GA); 624249259Sdim} 625249259Sdim 626276479Sdimvoid Verifier::visitNamedMDNode(const NamedMDNode &NMD) { 627249259Sdim for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) { 628249259Sdim MDNode *MD = NMD.getOperand(i); 629288943Sdim 630288943Sdim if (NMD.getName() == "llvm.dbg.cu") { 631288943Sdim Assert(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD); 632288943Sdim } 633288943Sdim 634249259Sdim if (!MD) 635249259Sdim continue; 636249259Sdim 637280031Sdim visitMDNode(*MD); 638249259Sdim } 639249259Sdim} 640249259Sdim 641288943Sdimvoid Verifier::visitMDNode(const MDNode &MD) { 642249259Sdim // Only visit each node once. Metadata can be mutually recursive, so this 643249259Sdim // avoids infinite recursion here, as well as being an optimization. 644280031Sdim if (!MDNodes.insert(&MD).second) 645249259Sdim return; 646249259Sdim 647288943Sdim switch (MD.getMetadataID()) { 648288943Sdim default: 649288943Sdim llvm_unreachable("Invalid MDNode subclass"); 650288943Sdim case Metadata::MDTupleKind: 651288943Sdim break; 652288943Sdim#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \ 653288943Sdim case Metadata::CLASS##Kind: \ 654288943Sdim visit##CLASS(cast<CLASS>(MD)); \ 655288943Sdim break; 656288943Sdim#include "llvm/IR/Metadata.def" 657288943Sdim } 658288943Sdim 659249259Sdim for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) { 660280031Sdim Metadata *Op = MD.getOperand(i); 661249259Sdim if (!Op) 662249259Sdim continue; 663288943Sdim Assert(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!", 664288943Sdim &MD, Op); 665280031Sdim if (auto *N = dyn_cast<MDNode>(Op)) { 666280031Sdim visitMDNode(*N); 667249259Sdim continue; 668280031Sdim } 669280031Sdim if (auto *V = dyn_cast<ValueAsMetadata>(Op)) { 670280031Sdim visitValueAsMetadata(*V, nullptr); 671249259Sdim continue; 672249259Sdim } 673280031Sdim } 674249259Sdim 675280031Sdim // Check these last, so we diagnose problems in operands first. 676288943Sdim Assert(!MD.isTemporary(), "Expected no forward declarations!", &MD); 677288943Sdim Assert(MD.isResolved(), "All nodes should be resolved!", &MD); 678280031Sdim} 679249259Sdim 680288943Sdimvoid Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) { 681288943Sdim Assert(MD.getValue(), "Expected valid value", &MD); 682288943Sdim Assert(!MD.getValue()->getType()->isMetadataTy(), 683288943Sdim "Unexpected metadata round-trip through values", &MD, MD.getValue()); 684280031Sdim 685280031Sdim auto *L = dyn_cast<LocalAsMetadata>(&MD); 686280031Sdim if (!L) 687280031Sdim return; 688280031Sdim 689288943Sdim Assert(F, "function-local metadata used outside a function", L); 690280031Sdim 691280031Sdim // If this was an instruction, bb, or argument, verify that it is in the 692280031Sdim // function that we expect. 693280031Sdim Function *ActualF = nullptr; 694280031Sdim if (Instruction *I = dyn_cast<Instruction>(L->getValue())) { 695288943Sdim Assert(I->getParent(), "function-local metadata not in basic block", L, I); 696280031Sdim ActualF = I->getParent()->getParent(); 697280031Sdim } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue())) 698280031Sdim ActualF = BB->getParent(); 699280031Sdim else if (Argument *A = dyn_cast<Argument>(L->getValue())) 700280031Sdim ActualF = A->getParent(); 701280031Sdim assert(ActualF && "Unimplemented function local metadata case!"); 702280031Sdim 703288943Sdim Assert(ActualF == F, "function-local metadata used in wrong function", L); 704280031Sdim} 705280031Sdim 706288943Sdimvoid Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) { 707280031Sdim Metadata *MD = MDV.getMetadata(); 708280031Sdim if (auto *N = dyn_cast<MDNode>(MD)) { 709280031Sdim visitMDNode(*N); 710280031Sdim return; 711249259Sdim } 712280031Sdim 713280031Sdim // Only visit each node once. Metadata can be mutually recursive, so this 714280031Sdim // avoids infinite recursion here, as well as being an optimization. 715280031Sdim if (!MDNodes.insert(MD).second) 716280031Sdim return; 717280031Sdim 718280031Sdim if (auto *V = dyn_cast<ValueAsMetadata>(MD)) 719280031Sdim visitValueAsMetadata(*V, F); 720249259Sdim} 721249259Sdim 722288943Sdimbool Verifier::isValidUUID(const MDNode &N, const Metadata *MD) { 723288943Sdim auto *S = dyn_cast<MDString>(MD); 724288943Sdim if (!S) 725288943Sdim return false; 726288943Sdim if (S->getString().empty()) 727288943Sdim return false; 728288943Sdim 729288943Sdim // Keep track of names of types referenced via UUID so we can check that they 730288943Sdim // actually exist. 731288943Sdim UnresolvedTypeRefs.insert(std::make_pair(S, &N)); 732288943Sdim return true; 733288943Sdim} 734288943Sdim 735288943Sdim/// \brief Check if a value can be a reference to a type. 736288943Sdimbool Verifier::isTypeRef(const MDNode &N, const Metadata *MD) { 737288943Sdim return !MD || isValidUUID(N, MD) || isa<DIType>(MD); 738288943Sdim} 739288943Sdim 740288943Sdim/// \brief Check if a value can be a ScopeRef. 741288943Sdimbool Verifier::isScopeRef(const MDNode &N, const Metadata *MD) { 742288943Sdim return !MD || isValidUUID(N, MD) || isa<DIScope>(MD); 743288943Sdim} 744288943Sdim 745288943Sdim/// \brief Check if a value can be a debug info ref. 746288943Sdimbool Verifier::isDIRef(const MDNode &N, const Metadata *MD) { 747288943Sdim return !MD || isValidUUID(N, MD) || isa<DINode>(MD); 748288943Sdim} 749288943Sdim 750288943Sdimtemplate <class Ty> 751288943Sdimbool isValidMetadataArrayImpl(const MDTuple &N, bool AllowNull) { 752288943Sdim for (Metadata *MD : N.operands()) { 753288943Sdim if (MD) { 754288943Sdim if (!isa<Ty>(MD)) 755288943Sdim return false; 756288943Sdim } else { 757288943Sdim if (!AllowNull) 758288943Sdim return false; 759288943Sdim } 760288943Sdim } 761288943Sdim return true; 762288943Sdim} 763288943Sdim 764288943Sdimtemplate <class Ty> 765288943Sdimbool isValidMetadataArray(const MDTuple &N) { 766288943Sdim return isValidMetadataArrayImpl<Ty>(N, /* AllowNull */ false); 767288943Sdim} 768288943Sdim 769288943Sdimtemplate <class Ty> 770288943Sdimbool isValidMetadataNullArray(const MDTuple &N) { 771288943Sdim return isValidMetadataArrayImpl<Ty>(N, /* AllowNull */ true); 772288943Sdim} 773288943Sdim 774288943Sdimvoid Verifier::visitDILocation(const DILocation &N) { 775288943Sdim Assert(N.getRawScope() && isa<DILocalScope>(N.getRawScope()), 776288943Sdim "location requires a valid scope", &N, N.getRawScope()); 777288943Sdim if (auto *IA = N.getRawInlinedAt()) 778288943Sdim Assert(isa<DILocation>(IA), "inlined-at should be a location", &N, IA); 779288943Sdim} 780288943Sdim 781288943Sdimvoid Verifier::visitGenericDINode(const GenericDINode &N) { 782288943Sdim Assert(N.getTag(), "invalid tag", &N); 783288943Sdim} 784288943Sdim 785288943Sdimvoid Verifier::visitDIScope(const DIScope &N) { 786288943Sdim if (auto *F = N.getRawFile()) 787288943Sdim Assert(isa<DIFile>(F), "invalid file", &N, F); 788288943Sdim} 789288943Sdim 790288943Sdimvoid Verifier::visitDISubrange(const DISubrange &N) { 791288943Sdim Assert(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N); 792288943Sdim Assert(N.getCount() >= -1, "invalid subrange count", &N); 793288943Sdim} 794288943Sdim 795288943Sdimvoid Verifier::visitDIEnumerator(const DIEnumerator &N) { 796288943Sdim Assert(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N); 797288943Sdim} 798288943Sdim 799288943Sdimvoid Verifier::visitDIBasicType(const DIBasicType &N) { 800288943Sdim Assert(N.getTag() == dwarf::DW_TAG_base_type || 801288943Sdim N.getTag() == dwarf::DW_TAG_unspecified_type, 802288943Sdim "invalid tag", &N); 803288943Sdim} 804288943Sdim 805296417Sdimvoid Verifier::visitDIDerivedType(const DIDerivedType &N) { 806288943Sdim // Common scope checks. 807288943Sdim visitDIScope(N); 808288943Sdim 809288943Sdim Assert(N.getTag() == dwarf::DW_TAG_typedef || 810288943Sdim N.getTag() == dwarf::DW_TAG_pointer_type || 811288943Sdim N.getTag() == dwarf::DW_TAG_ptr_to_member_type || 812288943Sdim N.getTag() == dwarf::DW_TAG_reference_type || 813288943Sdim N.getTag() == dwarf::DW_TAG_rvalue_reference_type || 814288943Sdim N.getTag() == dwarf::DW_TAG_const_type || 815288943Sdim N.getTag() == dwarf::DW_TAG_volatile_type || 816288943Sdim N.getTag() == dwarf::DW_TAG_restrict_type || 817288943Sdim N.getTag() == dwarf::DW_TAG_member || 818288943Sdim N.getTag() == dwarf::DW_TAG_inheritance || 819288943Sdim N.getTag() == dwarf::DW_TAG_friend, 820288943Sdim "invalid tag", &N); 821288943Sdim if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) { 822288943Sdim Assert(isTypeRef(N, N.getExtraData()), "invalid pointer to member type", &N, 823288943Sdim N.getExtraData()); 824288943Sdim } 825296417Sdim 826296417Sdim Assert(isScopeRef(N, N.getScope()), "invalid scope", &N, N.getScope()); 827296417Sdim Assert(isTypeRef(N, N.getBaseType()), "invalid base type", &N, 828296417Sdim N.getBaseType()); 829288943Sdim} 830288943Sdim 831288943Sdimstatic bool hasConflictingReferenceFlags(unsigned Flags) { 832288943Sdim return (Flags & DINode::FlagLValueReference) && 833288943Sdim (Flags & DINode::FlagRValueReference); 834288943Sdim} 835288943Sdim 836288943Sdimvoid Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) { 837288943Sdim auto *Params = dyn_cast<MDTuple>(&RawParams); 838288943Sdim Assert(Params, "invalid template params", &N, &RawParams); 839288943Sdim for (Metadata *Op : Params->operands()) { 840288943Sdim Assert(Op && isa<DITemplateParameter>(Op), "invalid template parameter", &N, 841288943Sdim Params, Op); 842288943Sdim } 843288943Sdim} 844288943Sdim 845288943Sdimvoid Verifier::visitDICompositeType(const DICompositeType &N) { 846296417Sdim // Common scope checks. 847296417Sdim visitDIScope(N); 848288943Sdim 849288943Sdim Assert(N.getTag() == dwarf::DW_TAG_array_type || 850288943Sdim N.getTag() == dwarf::DW_TAG_structure_type || 851288943Sdim N.getTag() == dwarf::DW_TAG_union_type || 852288943Sdim N.getTag() == dwarf::DW_TAG_enumeration_type || 853288943Sdim N.getTag() == dwarf::DW_TAG_class_type, 854288943Sdim "invalid tag", &N); 855288943Sdim 856296417Sdim Assert(isScopeRef(N, N.getScope()), "invalid scope", &N, N.getScope()); 857296417Sdim Assert(isTypeRef(N, N.getBaseType()), "invalid base type", &N, 858296417Sdim N.getBaseType()); 859296417Sdim 860288943Sdim Assert(!N.getRawElements() || isa<MDTuple>(N.getRawElements()), 861288943Sdim "invalid composite elements", &N, N.getRawElements()); 862288943Sdim Assert(isTypeRef(N, N.getRawVTableHolder()), "invalid vtable holder", &N, 863288943Sdim N.getRawVTableHolder()); 864288943Sdim Assert(!hasConflictingReferenceFlags(N.getFlags()), "invalid reference flags", 865288943Sdim &N); 866288943Sdim if (auto *Params = N.getRawTemplateParams()) 867288943Sdim visitTemplateParams(N, *Params); 868296417Sdim 869296417Sdim if (N.getTag() == dwarf::DW_TAG_class_type || 870296417Sdim N.getTag() == dwarf::DW_TAG_union_type) { 871296417Sdim Assert(N.getFile() && !N.getFile()->getFilename().empty(), 872296417Sdim "class/union requires a filename", &N, N.getFile()); 873296417Sdim } 874288943Sdim} 875288943Sdim 876288943Sdimvoid Verifier::visitDISubroutineType(const DISubroutineType &N) { 877288943Sdim Assert(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N); 878288943Sdim if (auto *Types = N.getRawTypeArray()) { 879288943Sdim Assert(isa<MDTuple>(Types), "invalid composite elements", &N, Types); 880288943Sdim for (Metadata *Ty : N.getTypeArray()->operands()) { 881288943Sdim Assert(isTypeRef(N, Ty), "invalid subroutine type ref", &N, Types, Ty); 882288943Sdim } 883288943Sdim } 884288943Sdim Assert(!hasConflictingReferenceFlags(N.getFlags()), "invalid reference flags", 885288943Sdim &N); 886288943Sdim} 887288943Sdim 888288943Sdimvoid Verifier::visitDIFile(const DIFile &N) { 889288943Sdim Assert(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N); 890288943Sdim} 891288943Sdim 892288943Sdimvoid Verifier::visitDICompileUnit(const DICompileUnit &N) { 893296417Sdim Assert(N.isDistinct(), "compile units must be distinct", &N); 894288943Sdim Assert(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N); 895288943Sdim 896288943Sdim // Don't bother verifying the compilation directory or producer string 897288943Sdim // as those could be empty. 898288943Sdim Assert(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N, 899288943Sdim N.getRawFile()); 900288943Sdim Assert(!N.getFile()->getFilename().empty(), "invalid filename", &N, 901288943Sdim N.getFile()); 902288943Sdim 903288943Sdim if (auto *Array = N.getRawEnumTypes()) { 904288943Sdim Assert(isa<MDTuple>(Array), "invalid enum list", &N, Array); 905288943Sdim for (Metadata *Op : N.getEnumTypes()->operands()) { 906288943Sdim auto *Enum = dyn_cast_or_null<DICompositeType>(Op); 907288943Sdim Assert(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type, 908288943Sdim "invalid enum type", &N, N.getEnumTypes(), Op); 909288943Sdim } 910288943Sdim } 911288943Sdim if (auto *Array = N.getRawRetainedTypes()) { 912288943Sdim Assert(isa<MDTuple>(Array), "invalid retained type list", &N, Array); 913288943Sdim for (Metadata *Op : N.getRetainedTypes()->operands()) { 914288943Sdim Assert(Op && isa<DIType>(Op), "invalid retained type", &N, Op); 915288943Sdim } 916288943Sdim } 917288943Sdim if (auto *Array = N.getRawSubprograms()) { 918288943Sdim Assert(isa<MDTuple>(Array), "invalid subprogram list", &N, Array); 919288943Sdim for (Metadata *Op : N.getSubprograms()->operands()) { 920288943Sdim Assert(Op && isa<DISubprogram>(Op), "invalid subprogram ref", &N, Op); 921288943Sdim } 922288943Sdim } 923288943Sdim if (auto *Array = N.getRawGlobalVariables()) { 924288943Sdim Assert(isa<MDTuple>(Array), "invalid global variable list", &N, Array); 925288943Sdim for (Metadata *Op : N.getGlobalVariables()->operands()) { 926288943Sdim Assert(Op && isa<DIGlobalVariable>(Op), "invalid global variable ref", &N, 927288943Sdim Op); 928288943Sdim } 929288943Sdim } 930288943Sdim if (auto *Array = N.getRawImportedEntities()) { 931288943Sdim Assert(isa<MDTuple>(Array), "invalid imported entity list", &N, Array); 932288943Sdim for (Metadata *Op : N.getImportedEntities()->operands()) { 933288943Sdim Assert(Op && isa<DIImportedEntity>(Op), "invalid imported entity ref", &N, 934288943Sdim Op); 935288943Sdim } 936288943Sdim } 937296417Sdim if (auto *Array = N.getRawMacros()) { 938296417Sdim Assert(isa<MDTuple>(Array), "invalid macro list", &N, Array); 939296417Sdim for (Metadata *Op : N.getMacros()->operands()) { 940296417Sdim Assert(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op); 941296417Sdim } 942296417Sdim } 943288943Sdim} 944288943Sdim 945288943Sdimvoid Verifier::visitDISubprogram(const DISubprogram &N) { 946288943Sdim Assert(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N); 947288943Sdim Assert(isScopeRef(N, N.getRawScope()), "invalid scope", &N, N.getRawScope()); 948288943Sdim if (auto *T = N.getRawType()) 949288943Sdim Assert(isa<DISubroutineType>(T), "invalid subroutine type", &N, T); 950288943Sdim Assert(isTypeRef(N, N.getRawContainingType()), "invalid containing type", &N, 951288943Sdim N.getRawContainingType()); 952288943Sdim if (auto *Params = N.getRawTemplateParams()) 953288943Sdim visitTemplateParams(N, *Params); 954288943Sdim if (auto *S = N.getRawDeclaration()) { 955288943Sdim Assert(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(), 956288943Sdim "invalid subprogram declaration", &N, S); 957288943Sdim } 958288943Sdim if (auto *RawVars = N.getRawVariables()) { 959288943Sdim auto *Vars = dyn_cast<MDTuple>(RawVars); 960288943Sdim Assert(Vars, "invalid variable list", &N, RawVars); 961288943Sdim for (Metadata *Op : Vars->operands()) { 962288943Sdim Assert(Op && isa<DILocalVariable>(Op), "invalid local variable", &N, Vars, 963288943Sdim Op); 964288943Sdim } 965288943Sdim } 966288943Sdim Assert(!hasConflictingReferenceFlags(N.getFlags()), "invalid reference flags", 967288943Sdim &N); 968288943Sdim 969296417Sdim if (N.isDefinition()) 970296417Sdim Assert(N.isDistinct(), "subprogram definitions must be distinct", &N); 971288943Sdim} 972288943Sdim 973288943Sdimvoid Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) { 974288943Sdim Assert(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N); 975288943Sdim Assert(N.getRawScope() && isa<DILocalScope>(N.getRawScope()), 976288943Sdim "invalid local scope", &N, N.getRawScope()); 977288943Sdim} 978288943Sdim 979288943Sdimvoid Verifier::visitDILexicalBlock(const DILexicalBlock &N) { 980288943Sdim visitDILexicalBlockBase(N); 981288943Sdim 982288943Sdim Assert(N.getLine() || !N.getColumn(), 983288943Sdim "cannot have column info without line info", &N); 984288943Sdim} 985288943Sdim 986288943Sdimvoid Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) { 987288943Sdim visitDILexicalBlockBase(N); 988288943Sdim} 989288943Sdim 990288943Sdimvoid Verifier::visitDINamespace(const DINamespace &N) { 991288943Sdim Assert(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N); 992288943Sdim if (auto *S = N.getRawScope()) 993288943Sdim Assert(isa<DIScope>(S), "invalid scope ref", &N, S); 994288943Sdim} 995288943Sdim 996296417Sdimvoid Verifier::visitDIMacro(const DIMacro &N) { 997296417Sdim Assert(N.getMacinfoType() == dwarf::DW_MACINFO_define || 998296417Sdim N.getMacinfoType() == dwarf::DW_MACINFO_undef, 999296417Sdim "invalid macinfo type", &N); 1000296417Sdim Assert(!N.getName().empty(), "anonymous macro", &N); 1001296417Sdim if (!N.getValue().empty()) { 1002296417Sdim assert(N.getValue().data()[0] != ' ' && "Macro value has a space prefix"); 1003296417Sdim } 1004296417Sdim} 1005296417Sdim 1006296417Sdimvoid Verifier::visitDIMacroFile(const DIMacroFile &N) { 1007296417Sdim Assert(N.getMacinfoType() == dwarf::DW_MACINFO_start_file, 1008296417Sdim "invalid macinfo type", &N); 1009296417Sdim if (auto *F = N.getRawFile()) 1010296417Sdim Assert(isa<DIFile>(F), "invalid file", &N, F); 1011296417Sdim 1012296417Sdim if (auto *Array = N.getRawElements()) { 1013296417Sdim Assert(isa<MDTuple>(Array), "invalid macro list", &N, Array); 1014296417Sdim for (Metadata *Op : N.getElements()->operands()) { 1015296417Sdim Assert(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op); 1016296417Sdim } 1017296417Sdim } 1018296417Sdim} 1019296417Sdim 1020288943Sdimvoid Verifier::visitDIModule(const DIModule &N) { 1021288943Sdim Assert(N.getTag() == dwarf::DW_TAG_module, "invalid tag", &N); 1022288943Sdim Assert(!N.getName().empty(), "anonymous module", &N); 1023288943Sdim} 1024288943Sdim 1025288943Sdimvoid Verifier::visitDITemplateParameter(const DITemplateParameter &N) { 1026288943Sdim Assert(isTypeRef(N, N.getType()), "invalid type ref", &N, N.getType()); 1027288943Sdim} 1028288943Sdim 1029288943Sdimvoid Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) { 1030288943Sdim visitDITemplateParameter(N); 1031288943Sdim 1032288943Sdim Assert(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag", 1033288943Sdim &N); 1034288943Sdim} 1035288943Sdim 1036288943Sdimvoid Verifier::visitDITemplateValueParameter( 1037288943Sdim const DITemplateValueParameter &N) { 1038288943Sdim visitDITemplateParameter(N); 1039288943Sdim 1040288943Sdim Assert(N.getTag() == dwarf::DW_TAG_template_value_parameter || 1041288943Sdim N.getTag() == dwarf::DW_TAG_GNU_template_template_param || 1042288943Sdim N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack, 1043288943Sdim "invalid tag", &N); 1044288943Sdim} 1045288943Sdim 1046288943Sdimvoid Verifier::visitDIVariable(const DIVariable &N) { 1047288943Sdim if (auto *S = N.getRawScope()) 1048288943Sdim Assert(isa<DIScope>(S), "invalid scope", &N, S); 1049288943Sdim Assert(isTypeRef(N, N.getRawType()), "invalid type ref", &N, N.getRawType()); 1050288943Sdim if (auto *F = N.getRawFile()) 1051288943Sdim Assert(isa<DIFile>(F), "invalid file", &N, F); 1052288943Sdim} 1053288943Sdim 1054288943Sdimvoid Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) { 1055288943Sdim // Checks common to all variables. 1056288943Sdim visitDIVariable(N); 1057288943Sdim 1058288943Sdim Assert(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N); 1059288943Sdim Assert(!N.getName().empty(), "missing global variable name", &N); 1060288943Sdim if (auto *V = N.getRawVariable()) { 1061288943Sdim Assert(isa<ConstantAsMetadata>(V) && 1062288943Sdim !isa<Function>(cast<ConstantAsMetadata>(V)->getValue()), 1063288943Sdim "invalid global varaible ref", &N, V); 1064288943Sdim } 1065288943Sdim if (auto *Member = N.getRawStaticDataMemberDeclaration()) { 1066288943Sdim Assert(isa<DIDerivedType>(Member), "invalid static data member declaration", 1067288943Sdim &N, Member); 1068288943Sdim } 1069288943Sdim} 1070288943Sdim 1071288943Sdimvoid Verifier::visitDILocalVariable(const DILocalVariable &N) { 1072288943Sdim // Checks common to all variables. 1073288943Sdim visitDIVariable(N); 1074288943Sdim 1075296417Sdim Assert(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N); 1076288943Sdim Assert(N.getRawScope() && isa<DILocalScope>(N.getRawScope()), 1077288943Sdim "local variable requires a valid scope", &N, N.getRawScope()); 1078288943Sdim} 1079288943Sdim 1080288943Sdimvoid Verifier::visitDIExpression(const DIExpression &N) { 1081288943Sdim Assert(N.isValid(), "invalid expression", &N); 1082288943Sdim} 1083288943Sdim 1084288943Sdimvoid Verifier::visitDIObjCProperty(const DIObjCProperty &N) { 1085288943Sdim Assert(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N); 1086288943Sdim if (auto *T = N.getRawType()) 1087288943Sdim Assert(isTypeRef(N, T), "invalid type ref", &N, T); 1088288943Sdim if (auto *F = N.getRawFile()) 1089288943Sdim Assert(isa<DIFile>(F), "invalid file", &N, F); 1090288943Sdim} 1091288943Sdim 1092288943Sdimvoid Verifier::visitDIImportedEntity(const DIImportedEntity &N) { 1093288943Sdim Assert(N.getTag() == dwarf::DW_TAG_imported_module || 1094288943Sdim N.getTag() == dwarf::DW_TAG_imported_declaration, 1095288943Sdim "invalid tag", &N); 1096288943Sdim if (auto *S = N.getRawScope()) 1097288943Sdim Assert(isa<DIScope>(S), "invalid scope for imported entity", &N, S); 1098288943Sdim Assert(isDIRef(N, N.getEntity()), "invalid imported entity", &N, 1099288943Sdim N.getEntity()); 1100288943Sdim} 1101288943Sdim 1102276479Sdimvoid Verifier::visitComdat(const Comdat &C) { 1103276479Sdim // The Module is invalid if the GlobalValue has private linkage. Entities 1104276479Sdim // with private linkage don't have entries in the symbol table. 1105288943Sdim if (const GlobalValue *GV = M->getNamedValue(C.getName())) 1106288943Sdim Assert(!GV->hasPrivateLinkage(), "comdat global value has private linkage", 1107288943Sdim GV); 1108276479Sdim} 1109276479Sdim 1110276479Sdimvoid Verifier::visitModuleIdents(const Module &M) { 1111261991Sdim const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident"); 1112261991Sdim if (!Idents) 1113261991Sdim return; 1114261991Sdim 1115261991Sdim // llvm.ident takes a list of metadata entry. Each entry has only one string. 1116261991Sdim // Scan each llvm.ident entry and make sure that this requirement is met. 1117261991Sdim for (unsigned i = 0, e = Idents->getNumOperands(); i != e; ++i) { 1118261991Sdim const MDNode *N = Idents->getOperand(i); 1119288943Sdim Assert(N->getNumOperands() == 1, 1120288943Sdim "incorrect number of operands in llvm.ident metadata", N); 1121288943Sdim Assert(dyn_cast_or_null<MDString>(N->getOperand(0)), 1122288943Sdim ("invalid value for llvm.ident metadata entry operand" 1123288943Sdim "(the operand should be a string)"), 1124288943Sdim N->getOperand(0)); 1125261991Sdim } 1126261991Sdim} 1127261991Sdim 1128276479Sdimvoid Verifier::visitModuleFlags(const Module &M) { 1129249259Sdim const NamedMDNode *Flags = M.getModuleFlagsMetadata(); 1130249259Sdim if (!Flags) return; 1131249259Sdim 1132249259Sdim // Scan each flag, and track the flags and requirements. 1133276479Sdim DenseMap<const MDString*, const MDNode*> SeenIDs; 1134276479Sdim SmallVector<const MDNode*, 16> Requirements; 1135249259Sdim for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) { 1136249259Sdim visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements); 1137249259Sdim } 1138249259Sdim 1139249259Sdim // Validate that the requirements in the module are valid. 1140249259Sdim for (unsigned I = 0, E = Requirements.size(); I != E; ++I) { 1141276479Sdim const MDNode *Requirement = Requirements[I]; 1142276479Sdim const MDString *Flag = cast<MDString>(Requirement->getOperand(0)); 1143280031Sdim const Metadata *ReqValue = Requirement->getOperand(1); 1144249259Sdim 1145276479Sdim const MDNode *Op = SeenIDs.lookup(Flag); 1146249259Sdim if (!Op) { 1147249259Sdim CheckFailed("invalid requirement on flag, flag is not present in module", 1148249259Sdim Flag); 1149249259Sdim continue; 1150249259Sdim } 1151249259Sdim 1152249259Sdim if (Op->getOperand(2) != ReqValue) { 1153249259Sdim CheckFailed(("invalid requirement on flag, " 1154249259Sdim "flag does not have the required value"), 1155249259Sdim Flag); 1156249259Sdim continue; 1157249259Sdim } 1158249259Sdim } 1159249259Sdim} 1160249259Sdim 1161276479Sdimvoid 1162276479SdimVerifier::visitModuleFlag(const MDNode *Op, 1163276479Sdim DenseMap<const MDString *, const MDNode *> &SeenIDs, 1164276479Sdim SmallVectorImpl<const MDNode *> &Requirements) { 1165249259Sdim // Each module flag should have three arguments, the merge behavior (a 1166249259Sdim // constant int), the flag ID (an MDString), and the value. 1167288943Sdim Assert(Op->getNumOperands() == 3, 1168288943Sdim "incorrect number of operands in module flag", Op); 1169280031Sdim Module::ModFlagBehavior MFB; 1170280031Sdim if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) { 1171288943Sdim Assert( 1172288943Sdim mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)), 1173280031Sdim "invalid behavior operand in module flag (expected constant integer)", 1174280031Sdim Op->getOperand(0)); 1175288943Sdim Assert(false, 1176288943Sdim "invalid behavior operand in module flag (unexpected constant)", 1177288943Sdim Op->getOperand(0)); 1178280031Sdim } 1179288943Sdim MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1)); 1180288943Sdim Assert(ID, "invalid ID operand in module flag (expected metadata string)", 1181288943Sdim Op->getOperand(1)); 1182249259Sdim 1183249259Sdim // Sanity check the values for behaviors with additional requirements. 1184280031Sdim switch (MFB) { 1185249259Sdim case Module::Error: 1186249259Sdim case Module::Warning: 1187249259Sdim case Module::Override: 1188249259Sdim // These behavior types accept any value. 1189249259Sdim break; 1190249259Sdim 1191249259Sdim case Module::Require: { 1192249259Sdim // The value should itself be an MDNode with two operands, a flag ID (an 1193249259Sdim // MDString), and a value. 1194249259Sdim MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2)); 1195288943Sdim Assert(Value && Value->getNumOperands() == 2, 1196288943Sdim "invalid value for 'require' module flag (expected metadata pair)", 1197288943Sdim Op->getOperand(2)); 1198288943Sdim Assert(isa<MDString>(Value->getOperand(0)), 1199288943Sdim ("invalid value for 'require' module flag " 1200288943Sdim "(first value operand should be a string)"), 1201288943Sdim Value->getOperand(0)); 1202249259Sdim 1203249259Sdim // Append it to the list of requirements, to check once all module flags are 1204249259Sdim // scanned. 1205249259Sdim Requirements.push_back(Value); 1206249259Sdim break; 1207249259Sdim } 1208249259Sdim 1209249259Sdim case Module::Append: 1210249259Sdim case Module::AppendUnique: { 1211249259Sdim // These behavior types require the operand be an MDNode. 1212288943Sdim Assert(isa<MDNode>(Op->getOperand(2)), 1213288943Sdim "invalid value for 'append'-type module flag " 1214288943Sdim "(expected a metadata node)", 1215288943Sdim Op->getOperand(2)); 1216249259Sdim break; 1217249259Sdim } 1218249259Sdim } 1219249259Sdim 1220249259Sdim // Unless this is a "requires" flag, check the ID is unique. 1221280031Sdim if (MFB != Module::Require) { 1222249259Sdim bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second; 1223288943Sdim Assert(Inserted, 1224288943Sdim "module flag identifiers must be unique (or of 'require' type)", ID); 1225249259Sdim } 1226249259Sdim} 1227249259Sdim 1228251662Sdimvoid Verifier::VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx, 1229261991Sdim bool isFunction, const Value *V) { 1230251662Sdim unsigned Slot = ~0U; 1231251662Sdim for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I) 1232251662Sdim if (Attrs.getSlotIndex(I) == Idx) { 1233251662Sdim Slot = I; 1234251662Sdim break; 1235251662Sdim } 1236251662Sdim 1237251662Sdim assert(Slot != ~0U && "Attribute set inconsistency!"); 1238251662Sdim 1239251662Sdim for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot); 1240251662Sdim I != E; ++I) { 1241251662Sdim if (I->isStringAttribute()) 1242251662Sdim continue; 1243251662Sdim 1244251662Sdim if (I->getKindAsEnum() == Attribute::NoReturn || 1245251662Sdim I->getKindAsEnum() == Attribute::NoUnwind || 1246251662Sdim I->getKindAsEnum() == Attribute::NoInline || 1247251662Sdim I->getKindAsEnum() == Attribute::AlwaysInline || 1248251662Sdim I->getKindAsEnum() == Attribute::OptimizeForSize || 1249251662Sdim I->getKindAsEnum() == Attribute::StackProtect || 1250251662Sdim I->getKindAsEnum() == Attribute::StackProtectReq || 1251251662Sdim I->getKindAsEnum() == Attribute::StackProtectStrong || 1252288943Sdim I->getKindAsEnum() == Attribute::SafeStack || 1253251662Sdim I->getKindAsEnum() == Attribute::NoRedZone || 1254251662Sdim I->getKindAsEnum() == Attribute::NoImplicitFloat || 1255251662Sdim I->getKindAsEnum() == Attribute::Naked || 1256251662Sdim I->getKindAsEnum() == Attribute::InlineHint || 1257251662Sdim I->getKindAsEnum() == Attribute::StackAlignment || 1258251662Sdim I->getKindAsEnum() == Attribute::UWTable || 1259251662Sdim I->getKindAsEnum() == Attribute::NonLazyBind || 1260251662Sdim I->getKindAsEnum() == Attribute::ReturnsTwice || 1261251662Sdim I->getKindAsEnum() == Attribute::SanitizeAddress || 1262251662Sdim I->getKindAsEnum() == Attribute::SanitizeThread || 1263251662Sdim I->getKindAsEnum() == Attribute::SanitizeMemory || 1264251662Sdim I->getKindAsEnum() == Attribute::MinSize || 1265251662Sdim I->getKindAsEnum() == Attribute::NoDuplicate || 1266261991Sdim I->getKindAsEnum() == Attribute::Builtin || 1267261991Sdim I->getKindAsEnum() == Attribute::NoBuiltin || 1268261991Sdim I->getKindAsEnum() == Attribute::Cold || 1269276479Sdim I->getKindAsEnum() == Attribute::OptimizeNone || 1270288943Sdim I->getKindAsEnum() == Attribute::JumpTable || 1271288943Sdim I->getKindAsEnum() == Attribute::Convergent || 1272296417Sdim I->getKindAsEnum() == Attribute::ArgMemOnly || 1273296417Sdim I->getKindAsEnum() == Attribute::NoRecurse || 1274296417Sdim I->getKindAsEnum() == Attribute::InaccessibleMemOnly || 1275296417Sdim I->getKindAsEnum() == Attribute::InaccessibleMemOrArgMemOnly) { 1276261991Sdim if (!isFunction) { 1277261991Sdim CheckFailed("Attribute '" + I->getAsString() + 1278261991Sdim "' only applies to functions!", V); 1279261991Sdim return; 1280261991Sdim } 1281261991Sdim } else if (I->getKindAsEnum() == Attribute::ReadOnly || 1282261991Sdim I->getKindAsEnum() == Attribute::ReadNone) { 1283261991Sdim if (Idx == 0) { 1284261991Sdim CheckFailed("Attribute '" + I->getAsString() + 1285261991Sdim "' does not apply to function returns"); 1286261991Sdim return; 1287261991Sdim } 1288251662Sdim } else if (isFunction) { 1289261991Sdim CheckFailed("Attribute '" + I->getAsString() + 1290261991Sdim "' does not apply to functions!", V); 1291261991Sdim return; 1292251662Sdim } 1293251662Sdim } 1294251662Sdim} 1295251662Sdim 1296249259Sdim// VerifyParameterAttrs - Check the given attributes for an argument or return 1297249259Sdim// value of the specified type. The value V is printed in error messages. 1298251662Sdimvoid Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty, 1299249259Sdim bool isReturnValue, const Value *V) { 1300249259Sdim if (!Attrs.hasAttributes(Idx)) 1301249259Sdim return; 1302249259Sdim 1303251662Sdim VerifyAttributeTypes(Attrs, Idx, false, V); 1304249259Sdim 1305249259Sdim if (isReturnValue) 1306288943Sdim Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) && 1307288943Sdim !Attrs.hasAttribute(Idx, Attribute::Nest) && 1308288943Sdim !Attrs.hasAttribute(Idx, Attribute::StructRet) && 1309288943Sdim !Attrs.hasAttribute(Idx, Attribute::NoCapture) && 1310288943Sdim !Attrs.hasAttribute(Idx, Attribute::Returned) && 1311288943Sdim !Attrs.hasAttribute(Idx, Attribute::InAlloca), 1312288943Sdim "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', and " 1313288943Sdim "'returned' do not apply to return values!", 1314288943Sdim V); 1315249259Sdim 1316276479Sdim // Check for mutually incompatible attributes. Only inreg is compatible with 1317276479Sdim // sret. 1318276479Sdim unsigned AttrCount = 0; 1319276479Sdim AttrCount += Attrs.hasAttribute(Idx, Attribute::ByVal); 1320276479Sdim AttrCount += Attrs.hasAttribute(Idx, Attribute::InAlloca); 1321276479Sdim AttrCount += Attrs.hasAttribute(Idx, Attribute::StructRet) || 1322276479Sdim Attrs.hasAttribute(Idx, Attribute::InReg); 1323276479Sdim AttrCount += Attrs.hasAttribute(Idx, Attribute::Nest); 1324288943Sdim Assert(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', " 1325288943Sdim "and 'sret' are incompatible!", 1326288943Sdim V); 1327249259Sdim 1328288943Sdim Assert(!(Attrs.hasAttribute(Idx, Attribute::InAlloca) && 1329288943Sdim Attrs.hasAttribute(Idx, Attribute::ReadOnly)), 1330288943Sdim "Attributes " 1331288943Sdim "'inalloca and readonly' are incompatible!", 1332288943Sdim V); 1333249259Sdim 1334288943Sdim Assert(!(Attrs.hasAttribute(Idx, Attribute::StructRet) && 1335288943Sdim Attrs.hasAttribute(Idx, Attribute::Returned)), 1336288943Sdim "Attributes " 1337288943Sdim "'sret and returned' are incompatible!", 1338288943Sdim V); 1339251662Sdim 1340288943Sdim Assert(!(Attrs.hasAttribute(Idx, Attribute::ZExt) && 1341288943Sdim Attrs.hasAttribute(Idx, Attribute::SExt)), 1342288943Sdim "Attributes " 1343288943Sdim "'zeroext and signext' are incompatible!", 1344288943Sdim V); 1345249259Sdim 1346288943Sdim Assert(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) && 1347288943Sdim Attrs.hasAttribute(Idx, Attribute::ReadOnly)), 1348288943Sdim "Attributes " 1349288943Sdim "'readnone and readonly' are incompatible!", 1350288943Sdim V); 1351249259Sdim 1352288943Sdim Assert(!(Attrs.hasAttribute(Idx, Attribute::NoInline) && 1353288943Sdim Attrs.hasAttribute(Idx, Attribute::AlwaysInline)), 1354288943Sdim "Attributes " 1355288943Sdim "'noinline and alwaysinline' are incompatible!", 1356288943Sdim V); 1357249259Sdim 1358288943Sdim Assert(!AttrBuilder(Attrs, Idx) 1359288943Sdim .overlaps(AttributeFuncs::typeIncompatible(Ty)), 1360288943Sdim "Wrong types for attribute: " + 1361288943Sdim AttributeSet::get(*Context, Idx, 1362288943Sdim AttributeFuncs::typeIncompatible(Ty)).getAsString(Idx), 1363288943Sdim V); 1364249259Sdim 1365276479Sdim if (PointerType *PTy = dyn_cast<PointerType>(Ty)) { 1366296417Sdim SmallPtrSet<Type*, 4> Visited; 1367288943Sdim if (!PTy->getElementType()->isSized(&Visited)) { 1368288943Sdim Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) && 1369288943Sdim !Attrs.hasAttribute(Idx, Attribute::InAlloca), 1370288943Sdim "Attributes 'byval' and 'inalloca' do not support unsized types!", 1371288943Sdim V); 1372276479Sdim } 1373276479Sdim } else { 1374288943Sdim Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal), 1375288943Sdim "Attribute 'byval' only applies to parameters with pointer type!", 1376288943Sdim V); 1377276479Sdim } 1378249259Sdim} 1379249259Sdim 1380249259Sdim// VerifyFunctionAttrs - Check parameter attributes against a function type. 1381249259Sdim// The value V is printed in error messages. 1382251662Sdimvoid Verifier::VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs, 1383249259Sdim const Value *V) { 1384249259Sdim if (Attrs.isEmpty()) 1385249259Sdim return; 1386249259Sdim 1387249259Sdim bool SawNest = false; 1388251662Sdim bool SawReturned = false; 1389276479Sdim bool SawSRet = false; 1390249259Sdim 1391249259Sdim for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) { 1392251662Sdim unsigned Idx = Attrs.getSlotIndex(i); 1393249259Sdim 1394249259Sdim Type *Ty; 1395251662Sdim if (Idx == 0) 1396249259Sdim Ty = FT->getReturnType(); 1397251662Sdim else if (Idx-1 < FT->getNumParams()) 1398251662Sdim Ty = FT->getParamType(Idx-1); 1399249259Sdim else 1400249259Sdim break; // VarArgs attributes, verified elsewhere. 1401249259Sdim 1402251662Sdim VerifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V); 1403249259Sdim 1404251662Sdim if (Idx == 0) 1405251662Sdim continue; 1406251662Sdim 1407251662Sdim if (Attrs.hasAttribute(Idx, Attribute::Nest)) { 1408288943Sdim Assert(!SawNest, "More than one parameter has attribute nest!", V); 1409249259Sdim SawNest = true; 1410249259Sdim } 1411249259Sdim 1412251662Sdim if (Attrs.hasAttribute(Idx, Attribute::Returned)) { 1413288943Sdim Assert(!SawReturned, "More than one parameter has attribute returned!", 1414288943Sdim V); 1415288943Sdim Assert(Ty->canLosslesslyBitCastTo(FT->getReturnType()), 1416288943Sdim "Incompatible " 1417288943Sdim "argument and return types for 'returned' attribute", 1418288943Sdim V); 1419251662Sdim SawReturned = true; 1420251662Sdim } 1421251662Sdim 1422276479Sdim if (Attrs.hasAttribute(Idx, Attribute::StructRet)) { 1423288943Sdim Assert(!SawSRet, "Cannot have multiple 'sret' parameters!", V); 1424288943Sdim Assert(Idx == 1 || Idx == 2, 1425288943Sdim "Attribute 'sret' is not on first or second parameter!", V); 1426276479Sdim SawSRet = true; 1427276479Sdim } 1428276479Sdim 1429276479Sdim if (Attrs.hasAttribute(Idx, Attribute::InAlloca)) { 1430288943Sdim Assert(Idx == FT->getNumParams(), "inalloca isn't on the last parameter!", 1431288943Sdim V); 1432276479Sdim } 1433249259Sdim } 1434249259Sdim 1435249259Sdim if (!Attrs.hasAttributes(AttributeSet::FunctionIndex)) 1436249259Sdim return; 1437249259Sdim 1438251662Sdim VerifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V); 1439249259Sdim 1440288943Sdim Assert( 1441288943Sdim !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone) && 1442288943Sdim Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly)), 1443288943Sdim "Attributes 'readnone and readonly' are incompatible!", V); 1444249259Sdim 1445288943Sdim Assert( 1446296417Sdim !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone) && 1447296417Sdim Attrs.hasAttribute(AttributeSet::FunctionIndex, 1448296417Sdim Attribute::InaccessibleMemOrArgMemOnly)), 1449296417Sdim "Attributes 'readnone and inaccessiblemem_or_argmemonly' are incompatible!", V); 1450296417Sdim 1451296417Sdim Assert( 1452296417Sdim !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone) && 1453296417Sdim Attrs.hasAttribute(AttributeSet::FunctionIndex, 1454296417Sdim Attribute::InaccessibleMemOnly)), 1455296417Sdim "Attributes 'readnone and inaccessiblememonly' are incompatible!", V); 1456296417Sdim 1457296417Sdim Assert( 1458288943Sdim !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline) && 1459288943Sdim Attrs.hasAttribute(AttributeSet::FunctionIndex, 1460288943Sdim Attribute::AlwaysInline)), 1461288943Sdim "Attributes 'noinline and alwaysinline' are incompatible!", V); 1462261991Sdim 1463261991Sdim if (Attrs.hasAttribute(AttributeSet::FunctionIndex, 1464261991Sdim Attribute::OptimizeNone)) { 1465288943Sdim Assert(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline), 1466288943Sdim "Attribute 'optnone' requires 'noinline'!", V); 1467261991Sdim 1468288943Sdim Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, 1469288943Sdim Attribute::OptimizeForSize), 1470288943Sdim "Attributes 'optsize and optnone' are incompatible!", V); 1471261991Sdim 1472288943Sdim Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize), 1473288943Sdim "Attributes 'minsize and optnone' are incompatible!", V); 1474261991Sdim } 1475276479Sdim 1476276479Sdim if (Attrs.hasAttribute(AttributeSet::FunctionIndex, 1477276479Sdim Attribute::JumpTable)) { 1478276479Sdim const GlobalValue *GV = cast<GlobalValue>(V); 1479288943Sdim Assert(GV->hasUnnamedAddr(), 1480288943Sdim "Attribute 'jumptable' requires 'unnamed_addr'", V); 1481288943Sdim } 1482288943Sdim} 1483276479Sdim 1484288943Sdimvoid Verifier::VerifyFunctionMetadata( 1485288943Sdim const SmallVector<std::pair<unsigned, MDNode *>, 4> MDs) { 1486288943Sdim if (MDs.empty()) 1487288943Sdim return; 1488288943Sdim 1489288943Sdim for (unsigned i = 0; i < MDs.size(); i++) { 1490288943Sdim if (MDs[i].first == LLVMContext::MD_prof) { 1491288943Sdim MDNode *MD = MDs[i].second; 1492288943Sdim Assert(MD->getNumOperands() == 2, 1493288943Sdim "!prof annotations should have exactly 2 operands", MD); 1494288943Sdim 1495288943Sdim // Check first operand. 1496288943Sdim Assert(MD->getOperand(0) != nullptr, "first operand should not be null", 1497288943Sdim MD); 1498288943Sdim Assert(isa<MDString>(MD->getOperand(0)), 1499288943Sdim "expected string with name of the !prof annotation", MD); 1500288943Sdim MDString *MDS = cast<MDString>(MD->getOperand(0)); 1501288943Sdim StringRef ProfName = MDS->getString(); 1502288943Sdim Assert(ProfName.equals("function_entry_count"), 1503288943Sdim "first operand should be 'function_entry_count'", MD); 1504288943Sdim 1505288943Sdim // Check second operand. 1506288943Sdim Assert(MD->getOperand(1) != nullptr, "second operand should not be null", 1507288943Sdim MD); 1508288943Sdim Assert(isa<ConstantAsMetadata>(MD->getOperand(1)), 1509288943Sdim "expected integer argument to function_entry_count", MD); 1510288943Sdim } 1511276479Sdim } 1512249259Sdim} 1513249259Sdim 1514296417Sdimvoid Verifier::visitConstantExprsRecursively(const Constant *EntryC) { 1515296417Sdim if (!ConstantExprVisited.insert(EntryC).second) 1516296417Sdim return; 1517296417Sdim 1518296417Sdim SmallVector<const Constant *, 16> Stack; 1519296417Sdim Stack.push_back(EntryC); 1520296417Sdim 1521296417Sdim while (!Stack.empty()) { 1522296417Sdim const Constant *C = Stack.pop_back_val(); 1523296417Sdim 1524296417Sdim // Check this constant expression. 1525296417Sdim if (const auto *CE = dyn_cast<ConstantExpr>(C)) 1526296417Sdim visitConstantExpr(CE); 1527296417Sdim 1528296417Sdim // Visit all sub-expressions. 1529296417Sdim for (const Use &U : C->operands()) { 1530296417Sdim const auto *OpC = dyn_cast<Constant>(U); 1531296417Sdim if (!OpC) 1532296417Sdim continue; 1533296417Sdim if (isa<GlobalValue>(OpC)) 1534296417Sdim continue; // Global values get visited separately. 1535296417Sdim if (!ConstantExprVisited.insert(OpC).second) 1536296417Sdim continue; 1537296417Sdim Stack.push_back(OpC); 1538296417Sdim } 1539296417Sdim } 1540296417Sdim} 1541296417Sdim 1542296417Sdimvoid Verifier::visitConstantExpr(const ConstantExpr *CE) { 1543280031Sdim if (CE->getOpcode() != Instruction::BitCast) 1544261991Sdim return; 1545261991Sdim 1546288943Sdim Assert(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0), 1547288943Sdim CE->getType()), 1548288943Sdim "Invalid bitcast", CE); 1549261991Sdim} 1550261991Sdim 1551251662Sdimbool Verifier::VerifyAttributeCount(AttributeSet Attrs, unsigned Params) { 1552249259Sdim if (Attrs.getNumSlots() == 0) 1553249259Sdim return true; 1554249259Sdim 1555249259Sdim unsigned LastSlot = Attrs.getNumSlots() - 1; 1556249259Sdim unsigned LastIndex = Attrs.getSlotIndex(LastSlot); 1557249259Sdim if (LastIndex <= Params 1558249259Sdim || (LastIndex == AttributeSet::FunctionIndex 1559249259Sdim && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params))) 1560249259Sdim return true; 1561261991Sdim 1562249259Sdim return false; 1563249259Sdim} 1564249259Sdim 1565288943Sdim/// \brief Verify that statepoint intrinsic is well formed. 1566288943Sdimvoid Verifier::VerifyStatepoint(ImmutableCallSite CS) { 1567288943Sdim assert(CS.getCalledFunction() && 1568288943Sdim CS.getCalledFunction()->getIntrinsicID() == 1569288943Sdim Intrinsic::experimental_gc_statepoint); 1570288943Sdim 1571288943Sdim const Instruction &CI = *CS.getInstruction(); 1572288943Sdim 1573288943Sdim Assert(!CS.doesNotAccessMemory() && !CS.onlyReadsMemory() && 1574288943Sdim !CS.onlyAccessesArgMemory(), 1575288943Sdim "gc.statepoint must read and write all memory to preserve " 1576288943Sdim "reordering restrictions required by safepoint semantics", 1577288943Sdim &CI); 1578288943Sdim 1579288943Sdim const Value *IDV = CS.getArgument(0); 1580288943Sdim Assert(isa<ConstantInt>(IDV), "gc.statepoint ID must be a constant integer", 1581288943Sdim &CI); 1582288943Sdim 1583288943Sdim const Value *NumPatchBytesV = CS.getArgument(1); 1584288943Sdim Assert(isa<ConstantInt>(NumPatchBytesV), 1585288943Sdim "gc.statepoint number of patchable bytes must be a constant integer", 1586288943Sdim &CI); 1587288943Sdim const int64_t NumPatchBytes = 1588288943Sdim cast<ConstantInt>(NumPatchBytesV)->getSExtValue(); 1589288943Sdim assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!"); 1590288943Sdim Assert(NumPatchBytes >= 0, "gc.statepoint number of patchable bytes must be " 1591288943Sdim "positive", 1592288943Sdim &CI); 1593288943Sdim 1594288943Sdim const Value *Target = CS.getArgument(2); 1595296417Sdim auto *PT = dyn_cast<PointerType>(Target->getType()); 1596288943Sdim Assert(PT && PT->getElementType()->isFunctionTy(), 1597288943Sdim "gc.statepoint callee must be of function pointer type", &CI, Target); 1598288943Sdim FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType()); 1599288943Sdim 1600288943Sdim const Value *NumCallArgsV = CS.getArgument(3); 1601288943Sdim Assert(isa<ConstantInt>(NumCallArgsV), 1602288943Sdim "gc.statepoint number of arguments to underlying call " 1603288943Sdim "must be constant integer", 1604288943Sdim &CI); 1605288943Sdim const int NumCallArgs = cast<ConstantInt>(NumCallArgsV)->getZExtValue(); 1606288943Sdim Assert(NumCallArgs >= 0, 1607288943Sdim "gc.statepoint number of arguments to underlying call " 1608288943Sdim "must be positive", 1609288943Sdim &CI); 1610288943Sdim const int NumParams = (int)TargetFuncType->getNumParams(); 1611288943Sdim if (TargetFuncType->isVarArg()) { 1612288943Sdim Assert(NumCallArgs >= NumParams, 1613288943Sdim "gc.statepoint mismatch in number of vararg call args", &CI); 1614288943Sdim 1615288943Sdim // TODO: Remove this limitation 1616288943Sdim Assert(TargetFuncType->getReturnType()->isVoidTy(), 1617288943Sdim "gc.statepoint doesn't support wrapping non-void " 1618288943Sdim "vararg functions yet", 1619288943Sdim &CI); 1620288943Sdim } else 1621288943Sdim Assert(NumCallArgs == NumParams, 1622288943Sdim "gc.statepoint mismatch in number of call args", &CI); 1623288943Sdim 1624288943Sdim const Value *FlagsV = CS.getArgument(4); 1625288943Sdim Assert(isa<ConstantInt>(FlagsV), 1626288943Sdim "gc.statepoint flags must be constant integer", &CI); 1627288943Sdim const uint64_t Flags = cast<ConstantInt>(FlagsV)->getZExtValue(); 1628288943Sdim Assert((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0, 1629288943Sdim "unknown flag used in gc.statepoint flags argument", &CI); 1630288943Sdim 1631288943Sdim // Verify that the types of the call parameter arguments match 1632288943Sdim // the type of the wrapped callee. 1633288943Sdim for (int i = 0; i < NumParams; i++) { 1634288943Sdim Type *ParamType = TargetFuncType->getParamType(i); 1635288943Sdim Type *ArgType = CS.getArgument(5 + i)->getType(); 1636288943Sdim Assert(ArgType == ParamType, 1637288943Sdim "gc.statepoint call argument does not match wrapped " 1638288943Sdim "function type", 1639288943Sdim &CI); 1640288943Sdim } 1641288943Sdim 1642288943Sdim const int EndCallArgsInx = 4 + NumCallArgs; 1643288943Sdim 1644288943Sdim const Value *NumTransitionArgsV = CS.getArgument(EndCallArgsInx+1); 1645288943Sdim Assert(isa<ConstantInt>(NumTransitionArgsV), 1646288943Sdim "gc.statepoint number of transition arguments " 1647288943Sdim "must be constant integer", 1648288943Sdim &CI); 1649288943Sdim const int NumTransitionArgs = 1650288943Sdim cast<ConstantInt>(NumTransitionArgsV)->getZExtValue(); 1651288943Sdim Assert(NumTransitionArgs >= 0, 1652288943Sdim "gc.statepoint number of transition arguments must be positive", &CI); 1653288943Sdim const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs; 1654288943Sdim 1655288943Sdim const Value *NumDeoptArgsV = CS.getArgument(EndTransitionArgsInx+1); 1656288943Sdim Assert(isa<ConstantInt>(NumDeoptArgsV), 1657288943Sdim "gc.statepoint number of deoptimization arguments " 1658288943Sdim "must be constant integer", 1659288943Sdim &CI); 1660288943Sdim const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue(); 1661288943Sdim Assert(NumDeoptArgs >= 0, "gc.statepoint number of deoptimization arguments " 1662288943Sdim "must be positive", 1663288943Sdim &CI); 1664288943Sdim 1665288943Sdim const int ExpectedNumArgs = 1666288943Sdim 7 + NumCallArgs + NumTransitionArgs + NumDeoptArgs; 1667288943Sdim Assert(ExpectedNumArgs <= (int)CS.arg_size(), 1668288943Sdim "gc.statepoint too few arguments according to length fields", &CI); 1669288943Sdim 1670288943Sdim // Check that the only uses of this gc.statepoint are gc.result or 1671288943Sdim // gc.relocate calls which are tied to this statepoint and thus part 1672288943Sdim // of the same statepoint sequence 1673288943Sdim for (const User *U : CI.users()) { 1674288943Sdim const CallInst *Call = dyn_cast<const CallInst>(U); 1675288943Sdim Assert(Call, "illegal use of statepoint token", &CI, U); 1676288943Sdim if (!Call) continue; 1677296417Sdim Assert(isa<GCRelocateInst>(Call) || isGCResult(Call), 1678288943Sdim "gc.result or gc.relocate are the only value uses" 1679288943Sdim "of a gc.statepoint", 1680288943Sdim &CI, U); 1681288943Sdim if (isGCResult(Call)) { 1682288943Sdim Assert(Call->getArgOperand(0) == &CI, 1683288943Sdim "gc.result connected to wrong gc.statepoint", &CI, Call); 1684296417Sdim } else if (isa<GCRelocateInst>(Call)) { 1685288943Sdim Assert(Call->getArgOperand(0) == &CI, 1686288943Sdim "gc.relocate connected to wrong gc.statepoint", &CI, Call); 1687288943Sdim } 1688288943Sdim } 1689288943Sdim 1690288943Sdim // Note: It is legal for a single derived pointer to be listed multiple 1691288943Sdim // times. It's non-optimal, but it is legal. It can also happen after 1692288943Sdim // insertion if we strip a bitcast away. 1693288943Sdim // Note: It is really tempting to check that each base is relocated and 1694288943Sdim // that a derived pointer is never reused as a base pointer. This turns 1695288943Sdim // out to be problematic since optimizations run after safepoint insertion 1696288943Sdim // can recognize equality properties that the insertion logic doesn't know 1697288943Sdim // about. See example statepoint.ll in the verifier subdirectory 1698288943Sdim} 1699288943Sdim 1700288943Sdimvoid Verifier::verifyFrameRecoverIndices() { 1701288943Sdim for (auto &Counts : FrameEscapeInfo) { 1702288943Sdim Function *F = Counts.first; 1703288943Sdim unsigned EscapedObjectCount = Counts.second.first; 1704288943Sdim unsigned MaxRecoveredIndex = Counts.second.second; 1705288943Sdim Assert(MaxRecoveredIndex <= EscapedObjectCount, 1706288943Sdim "all indices passed to llvm.localrecover must be less than the " 1707288943Sdim "number of arguments passed ot llvm.localescape in the parent " 1708288943Sdim "function", 1709288943Sdim F); 1710288943Sdim } 1711288943Sdim} 1712288943Sdim 1713296417Sdimstatic Instruction *getSuccPad(TerminatorInst *Terminator) { 1714296417Sdim BasicBlock *UnwindDest; 1715296417Sdim if (auto *II = dyn_cast<InvokeInst>(Terminator)) 1716296417Sdim UnwindDest = II->getUnwindDest(); 1717296417Sdim else if (auto *CSI = dyn_cast<CatchSwitchInst>(Terminator)) 1718296417Sdim UnwindDest = CSI->getUnwindDest(); 1719296417Sdim else 1720296417Sdim UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest(); 1721296417Sdim return UnwindDest->getFirstNonPHI(); 1722296417Sdim} 1723296417Sdim 1724296417Sdimvoid Verifier::verifySiblingFuncletUnwinds() { 1725296417Sdim SmallPtrSet<Instruction *, 8> Visited; 1726296417Sdim SmallPtrSet<Instruction *, 8> Active; 1727296417Sdim for (const auto &Pair : SiblingFuncletInfo) { 1728296417Sdim Instruction *PredPad = Pair.first; 1729296417Sdim if (Visited.count(PredPad)) 1730296417Sdim continue; 1731296417Sdim Active.insert(PredPad); 1732296417Sdim TerminatorInst *Terminator = Pair.second; 1733296417Sdim do { 1734296417Sdim Instruction *SuccPad = getSuccPad(Terminator); 1735296417Sdim if (Active.count(SuccPad)) { 1736296417Sdim // Found a cycle; report error 1737296417Sdim Instruction *CyclePad = SuccPad; 1738296417Sdim SmallVector<Instruction *, 8> CycleNodes; 1739296417Sdim do { 1740296417Sdim CycleNodes.push_back(CyclePad); 1741296417Sdim TerminatorInst *CycleTerminator = SiblingFuncletInfo[CyclePad]; 1742296417Sdim if (CycleTerminator != CyclePad) 1743296417Sdim CycleNodes.push_back(CycleTerminator); 1744296417Sdim CyclePad = getSuccPad(CycleTerminator); 1745296417Sdim } while (CyclePad != SuccPad); 1746296417Sdim Assert(false, "EH pads can't handle each other's exceptions", 1747296417Sdim ArrayRef<Instruction *>(CycleNodes)); 1748296417Sdim } 1749296417Sdim // Don't re-walk a node we've already checked 1750296417Sdim if (!Visited.insert(SuccPad).second) 1751296417Sdim break; 1752296417Sdim // Walk to this successor if it has a map entry. 1753296417Sdim PredPad = SuccPad; 1754296417Sdim auto TermI = SiblingFuncletInfo.find(PredPad); 1755296417Sdim if (TermI == SiblingFuncletInfo.end()) 1756296417Sdim break; 1757296417Sdim Terminator = TermI->second; 1758296417Sdim Active.insert(PredPad); 1759296417Sdim } while (true); 1760296417Sdim // Each node only has one successor, so we've walked all the active 1761296417Sdim // nodes' successors. 1762296417Sdim Active.clear(); 1763296417Sdim } 1764296417Sdim} 1765296417Sdim 1766249259Sdim// visitFunction - Verify that a function is ok. 1767249259Sdim// 1768276479Sdimvoid Verifier::visitFunction(const Function &F) { 1769249259Sdim // Check function arguments. 1770249259Sdim FunctionType *FT = F.getFunctionType(); 1771249259Sdim unsigned NumArgs = F.arg_size(); 1772249259Sdim 1773288943Sdim Assert(Context == &F.getContext(), 1774288943Sdim "Function context does not match Module context!", &F); 1775249259Sdim 1776288943Sdim Assert(!F.hasCommonLinkage(), "Functions may not have common linkage", &F); 1777288943Sdim Assert(FT->getNumParams() == NumArgs, 1778288943Sdim "# formal arguments must match # of arguments for function type!", &F, 1779288943Sdim FT); 1780288943Sdim Assert(F.getReturnType()->isFirstClassType() || 1781288943Sdim F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(), 1782288943Sdim "Functions cannot return aggregate values!", &F); 1783249259Sdim 1784288943Sdim Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(), 1785288943Sdim "Invalid struct return type!", &F); 1786249259Sdim 1787251662Sdim AttributeSet Attrs = F.getAttributes(); 1788249259Sdim 1789288943Sdim Assert(VerifyAttributeCount(Attrs, FT->getNumParams()), 1790288943Sdim "Attribute after last parameter!", &F); 1791249259Sdim 1792249259Sdim // Check function attributes. 1793249259Sdim VerifyFunctionAttrs(FT, Attrs, &F); 1794249259Sdim 1795261991Sdim // On function declarations/definitions, we do not support the builtin 1796261991Sdim // attribute. We do not check this in VerifyFunctionAttrs since that is 1797261991Sdim // checking for Attributes that can/can not ever be on functions. 1798288943Sdim Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::Builtin), 1799288943Sdim "Attribute 'builtin' can only be applied to a callsite.", &F); 1800261991Sdim 1801249259Sdim // Check that this function meets the restrictions on this calling convention. 1802280031Sdim // Sometimes varargs is used for perfectly forwarding thunks, so some of these 1803280031Sdim // restrictions can be lifted. 1804249259Sdim switch (F.getCallingConv()) { 1805249259Sdim default: 1806249259Sdim case CallingConv::C: 1807249259Sdim break; 1808249259Sdim case CallingConv::Fast: 1809249259Sdim case CallingConv::Cold: 1810249259Sdim case CallingConv::Intel_OCL_BI: 1811249259Sdim case CallingConv::PTX_Kernel: 1812249259Sdim case CallingConv::PTX_Device: 1813288943Sdim Assert(!F.isVarArg(), "Calling convention does not support varargs or " 1814288943Sdim "perfect forwarding!", 1815288943Sdim &F); 1816249259Sdim break; 1817249259Sdim } 1818249259Sdim 1819249259Sdim bool isLLVMdotName = F.getName().size() >= 5 && 1820249259Sdim F.getName().substr(0, 5) == "llvm."; 1821249259Sdim 1822249259Sdim // Check that the argument values match the function type for this function... 1823249259Sdim unsigned i = 0; 1824276479Sdim for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; 1825276479Sdim ++I, ++i) { 1826288943Sdim Assert(I->getType() == FT->getParamType(i), 1827288943Sdim "Argument value does not match function argument type!", I, 1828288943Sdim FT->getParamType(i)); 1829288943Sdim Assert(I->getType()->isFirstClassType(), 1830288943Sdim "Function arguments must have first-class types!", I); 1831296417Sdim if (!isLLVMdotName) { 1832288943Sdim Assert(!I->getType()->isMetadataTy(), 1833288943Sdim "Function takes metadata but isn't an intrinsic", I, &F); 1834296417Sdim Assert(!I->getType()->isTokenTy(), 1835296417Sdim "Function takes token but isn't an intrinsic", I, &F); 1836296417Sdim } 1837249259Sdim } 1838249259Sdim 1839296417Sdim if (!isLLVMdotName) 1840296417Sdim Assert(!F.getReturnType()->isTokenTy(), 1841296417Sdim "Functions returns a token but isn't an intrinsic", &F); 1842296417Sdim 1843288943Sdim // Get the function metadata attachments. 1844288943Sdim SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 1845288943Sdim F.getAllMetadata(MDs); 1846288943Sdim assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync"); 1847288943Sdim VerifyFunctionMetadata(MDs); 1848288943Sdim 1849296417Sdim // Check validity of the personality function 1850296417Sdim if (F.hasPersonalityFn()) { 1851296417Sdim auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts()); 1852296417Sdim if (Per) 1853296417Sdim Assert(Per->getParent() == F.getParent(), 1854296417Sdim "Referencing personality function in another module!", 1855296417Sdim &F, F.getParent(), Per, Per->getParent()); 1856296417Sdim } 1857296417Sdim 1858249259Sdim if (F.isMaterializable()) { 1859249259Sdim // Function has a body somewhere we can't see. 1860288943Sdim Assert(MDs.empty(), "unmaterialized function cannot have metadata", &F, 1861288943Sdim MDs.empty() ? nullptr : MDs.front().second); 1862249259Sdim } else if (F.isDeclaration()) { 1863288943Sdim Assert(F.hasExternalLinkage() || F.hasExternalWeakLinkage(), 1864288943Sdim "invalid linkage type for function declaration", &F); 1865288943Sdim Assert(MDs.empty(), "function without a body cannot have metadata", &F, 1866288943Sdim MDs.empty() ? nullptr : MDs.front().second); 1867288943Sdim Assert(!F.hasPersonalityFn(), 1868288943Sdim "Function declaration shouldn't have a personality routine", &F); 1869249259Sdim } else { 1870249259Sdim // Verify that this function (which has a body) is not named "llvm.*". It 1871249259Sdim // is not legal to define intrinsics. 1872288943Sdim Assert(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F); 1873261991Sdim 1874249259Sdim // Check the entry node 1875276479Sdim const BasicBlock *Entry = &F.getEntryBlock(); 1876288943Sdim Assert(pred_empty(Entry), 1877288943Sdim "Entry block to function must not have predecessors!", Entry); 1878261991Sdim 1879249259Sdim // The address of the entry block cannot be taken, unless it is dead. 1880249259Sdim if (Entry->hasAddressTaken()) { 1881288943Sdim Assert(!BlockAddress::lookup(Entry)->isConstantUsed(), 1882288943Sdim "blockaddress may not be used with the entry block!", Entry); 1883249259Sdim } 1884288943Sdim 1885288943Sdim // Visit metadata attachments. 1886296417Sdim for (const auto &I : MDs) { 1887296417Sdim // Verify that the attachment is legal. 1888296417Sdim switch (I.first) { 1889296417Sdim default: 1890296417Sdim break; 1891296417Sdim case LLVMContext::MD_dbg: 1892296417Sdim Assert(isa<DISubprogram>(I.second), 1893296417Sdim "function !dbg attachment must be a subprogram", &F, I.second); 1894296417Sdim break; 1895296417Sdim } 1896296417Sdim 1897296417Sdim // Verify the metadata itself. 1898288943Sdim visitMDNode(*I.second); 1899296417Sdim } 1900249259Sdim } 1901261991Sdim 1902249259Sdim // If this function is actually an intrinsic, verify that it is only used in 1903249259Sdim // direct call/invokes, never having its "address taken". 1904296417Sdim // Only do this if the module is materialized, otherwise we don't have all the 1905296417Sdim // uses. 1906296417Sdim if (F.getIntrinsicID() && F.getParent()->isMaterialized()) { 1907249259Sdim const User *U; 1908249259Sdim if (F.hasAddressTaken(&U)) 1909288943Sdim Assert(0, "Invalid user of intrinsic instruction!", U); 1910249259Sdim } 1911276479Sdim 1912288943Sdim Assert(!F.hasDLLImportStorageClass() || 1913288943Sdim (F.isDeclaration() && F.hasExternalLinkage()) || 1914288943Sdim F.hasAvailableExternallyLinkage(), 1915288943Sdim "Function is marked as dllimport, but not external.", &F); 1916296417Sdim 1917296417Sdim auto *N = F.getSubprogram(); 1918296417Sdim if (!N) 1919296417Sdim return; 1920296417Sdim 1921296417Sdim // Check that all !dbg attachments lead to back to N (or, at least, another 1922296417Sdim // subprogram that describes the same function). 1923296417Sdim // 1924296417Sdim // FIXME: Check this incrementally while visiting !dbg attachments. 1925296417Sdim // FIXME: Only check when N is the canonical subprogram for F. 1926296417Sdim SmallPtrSet<const MDNode *, 32> Seen; 1927296417Sdim for (auto &BB : F) 1928296417Sdim for (auto &I : BB) { 1929296417Sdim // Be careful about using DILocation here since we might be dealing with 1930296417Sdim // broken code (this is the Verifier after all). 1931296417Sdim DILocation *DL = 1932296417Sdim dyn_cast_or_null<DILocation>(I.getDebugLoc().getAsMDNode()); 1933296417Sdim if (!DL) 1934296417Sdim continue; 1935296417Sdim if (!Seen.insert(DL).second) 1936296417Sdim continue; 1937296417Sdim 1938296417Sdim DILocalScope *Scope = DL->getInlinedAtScope(); 1939296417Sdim if (Scope && !Seen.insert(Scope).second) 1940296417Sdim continue; 1941296417Sdim 1942296417Sdim DISubprogram *SP = Scope ? Scope->getSubprogram() : nullptr; 1943296417Sdim 1944296417Sdim // Scope and SP could be the same MDNode and we don't want to skip 1945296417Sdim // validation in that case 1946296417Sdim if (SP && ((Scope != SP) && !Seen.insert(SP).second)) 1947296417Sdim continue; 1948296417Sdim 1949296417Sdim // FIXME: Once N is canonical, check "SP == &N". 1950296417Sdim Assert(SP->describes(&F), 1951296417Sdim "!dbg attachment points at wrong subprogram for function", N, &F, 1952296417Sdim &I, DL, Scope, SP); 1953296417Sdim } 1954249259Sdim} 1955249259Sdim 1956249259Sdim// verifyBasicBlock - Verify that a basic block is well formed... 1957249259Sdim// 1958249259Sdimvoid Verifier::visitBasicBlock(BasicBlock &BB) { 1959249259Sdim InstsInThisBlock.clear(); 1960249259Sdim 1961249259Sdim // Ensure that basic blocks have terminators! 1962288943Sdim Assert(BB.getTerminator(), "Basic Block does not have terminator!", &BB); 1963249259Sdim 1964249259Sdim // Check constraints that this basic block imposes on all of the PHI nodes in 1965249259Sdim // it. 1966249259Sdim if (isa<PHINode>(BB.front())) { 1967249259Sdim SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB)); 1968249259Sdim SmallVector<std::pair<BasicBlock*, Value*>, 8> Values; 1969249259Sdim std::sort(Preds.begin(), Preds.end()); 1970249259Sdim PHINode *PN; 1971249259Sdim for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) { 1972249259Sdim // Ensure that PHI nodes have at least one entry! 1973288943Sdim Assert(PN->getNumIncomingValues() != 0, 1974288943Sdim "PHI nodes must have at least one entry. If the block is dead, " 1975288943Sdim "the PHI should be removed!", 1976288943Sdim PN); 1977288943Sdim Assert(PN->getNumIncomingValues() == Preds.size(), 1978288943Sdim "PHINode should have one entry for each predecessor of its " 1979288943Sdim "parent basic block!", 1980288943Sdim PN); 1981249259Sdim 1982249259Sdim // Get and sort all incoming values in the PHI node... 1983249259Sdim Values.clear(); 1984249259Sdim Values.reserve(PN->getNumIncomingValues()); 1985249259Sdim for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 1986249259Sdim Values.push_back(std::make_pair(PN->getIncomingBlock(i), 1987249259Sdim PN->getIncomingValue(i))); 1988249259Sdim std::sort(Values.begin(), Values.end()); 1989249259Sdim 1990249259Sdim for (unsigned i = 0, e = Values.size(); i != e; ++i) { 1991249259Sdim // Check to make sure that if there is more than one entry for a 1992249259Sdim // particular basic block in this PHI node, that the incoming values are 1993249259Sdim // all identical. 1994249259Sdim // 1995288943Sdim Assert(i == 0 || Values[i].first != Values[i - 1].first || 1996288943Sdim Values[i].second == Values[i - 1].second, 1997288943Sdim "PHI node has multiple entries for the same basic block with " 1998288943Sdim "different incoming values!", 1999288943Sdim PN, Values[i].first, Values[i].second, Values[i - 1].second); 2000249259Sdim 2001249259Sdim // Check to make sure that the predecessors and PHI node entries are 2002249259Sdim // matched up. 2003288943Sdim Assert(Values[i].first == Preds[i], 2004288943Sdim "PHI node entries do not match predecessors!", PN, 2005288943Sdim Values[i].first, Preds[i]); 2006249259Sdim } 2007249259Sdim } 2008249259Sdim } 2009280031Sdim 2010280031Sdim // Check that all instructions have their parent pointers set up correctly. 2011280031Sdim for (auto &I : BB) 2012280031Sdim { 2013280031Sdim Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!"); 2014280031Sdim } 2015249259Sdim} 2016249259Sdim 2017249259Sdimvoid Verifier::visitTerminatorInst(TerminatorInst &I) { 2018249259Sdim // Ensure that terminators only exist at the end of the basic block. 2019288943Sdim Assert(&I == I.getParent()->getTerminator(), 2020288943Sdim "Terminator found in the middle of a basic block!", I.getParent()); 2021249259Sdim visitInstruction(I); 2022249259Sdim} 2023249259Sdim 2024249259Sdimvoid Verifier::visitBranchInst(BranchInst &BI) { 2025249259Sdim if (BI.isConditional()) { 2026288943Sdim Assert(BI.getCondition()->getType()->isIntegerTy(1), 2027288943Sdim "Branch condition is not 'i1' type!", &BI, BI.getCondition()); 2028249259Sdim } 2029249259Sdim visitTerminatorInst(BI); 2030249259Sdim} 2031249259Sdim 2032249259Sdimvoid Verifier::visitReturnInst(ReturnInst &RI) { 2033249259Sdim Function *F = RI.getParent()->getParent(); 2034249259Sdim unsigned N = RI.getNumOperands(); 2035261991Sdim if (F->getReturnType()->isVoidTy()) 2036288943Sdim Assert(N == 0, 2037288943Sdim "Found return instr that returns non-void in Function of void " 2038288943Sdim "return type!", 2039288943Sdim &RI, F->getReturnType()); 2040249259Sdim else 2041288943Sdim Assert(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(), 2042288943Sdim "Function return type does not match operand " 2043288943Sdim "type of return inst!", 2044288943Sdim &RI, F->getReturnType()); 2045249259Sdim 2046249259Sdim // Check to make sure that the return value has necessary properties for 2047249259Sdim // terminators... 2048249259Sdim visitTerminatorInst(RI); 2049249259Sdim} 2050249259Sdim 2051249259Sdimvoid Verifier::visitSwitchInst(SwitchInst &SI) { 2052249259Sdim // Check to make sure that all of the constants in the switch instruction 2053249259Sdim // have the same type as the switched-on value. 2054249259Sdim Type *SwitchTy = SI.getCondition()->getType(); 2055261991Sdim SmallPtrSet<ConstantInt*, 32> Constants; 2056249259Sdim for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) { 2057288943Sdim Assert(i.getCaseValue()->getType() == SwitchTy, 2058288943Sdim "Switch constants must all be same type as switch value!", &SI); 2059288943Sdim Assert(Constants.insert(i.getCaseValue()).second, 2060288943Sdim "Duplicate integer as switch case", &SI, i.getCaseValue()); 2061249259Sdim } 2062261991Sdim 2063249259Sdim visitTerminatorInst(SI); 2064249259Sdim} 2065249259Sdim 2066249259Sdimvoid Verifier::visitIndirectBrInst(IndirectBrInst &BI) { 2067288943Sdim Assert(BI.getAddress()->getType()->isPointerTy(), 2068288943Sdim "Indirectbr operand must have pointer type!", &BI); 2069249259Sdim for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i) 2070288943Sdim Assert(BI.getDestination(i)->getType()->isLabelTy(), 2071288943Sdim "Indirectbr destinations must all have pointer type!", &BI); 2072249259Sdim 2073249259Sdim visitTerminatorInst(BI); 2074249259Sdim} 2075249259Sdim 2076249259Sdimvoid Verifier::visitSelectInst(SelectInst &SI) { 2077288943Sdim Assert(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1), 2078288943Sdim SI.getOperand(2)), 2079288943Sdim "Invalid operands for select instruction!", &SI); 2080249259Sdim 2081288943Sdim Assert(SI.getTrueValue()->getType() == SI.getType(), 2082288943Sdim "Select values must have same type as select instruction!", &SI); 2083249259Sdim visitInstruction(SI); 2084249259Sdim} 2085249259Sdim 2086249259Sdim/// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of 2087249259Sdim/// a pass, if any exist, it's an error. 2088249259Sdim/// 2089249259Sdimvoid Verifier::visitUserOp1(Instruction &I) { 2090288943Sdim Assert(0, "User-defined operators should not live outside of a pass!", &I); 2091249259Sdim} 2092249259Sdim 2093249259Sdimvoid Verifier::visitTruncInst(TruncInst &I) { 2094249259Sdim // Get the source and destination types 2095249259Sdim Type *SrcTy = I.getOperand(0)->getType(); 2096249259Sdim Type *DestTy = I.getType(); 2097249259Sdim 2098249259Sdim // Get the size of the types in bits, we'll need this later 2099249259Sdim unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2100249259Sdim unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2101249259Sdim 2102288943Sdim Assert(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I); 2103288943Sdim Assert(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I); 2104288943Sdim Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2105288943Sdim "trunc source and destination must both be a vector or neither", &I); 2106288943Sdim Assert(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I); 2107249259Sdim 2108249259Sdim visitInstruction(I); 2109249259Sdim} 2110249259Sdim 2111249259Sdimvoid Verifier::visitZExtInst(ZExtInst &I) { 2112249259Sdim // Get the source and destination types 2113249259Sdim Type *SrcTy = I.getOperand(0)->getType(); 2114249259Sdim Type *DestTy = I.getType(); 2115249259Sdim 2116249259Sdim // Get the size of the types in bits, we'll need this later 2117288943Sdim Assert(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I); 2118288943Sdim Assert(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I); 2119288943Sdim Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2120288943Sdim "zext source and destination must both be a vector or neither", &I); 2121249259Sdim unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2122249259Sdim unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2123249259Sdim 2124288943Sdim Assert(SrcBitSize < DestBitSize, "Type too small for ZExt", &I); 2125249259Sdim 2126249259Sdim visitInstruction(I); 2127249259Sdim} 2128249259Sdim 2129249259Sdimvoid Verifier::visitSExtInst(SExtInst &I) { 2130249259Sdim // Get the source and destination types 2131249259Sdim Type *SrcTy = I.getOperand(0)->getType(); 2132249259Sdim Type *DestTy = I.getType(); 2133249259Sdim 2134249259Sdim // Get the size of the types in bits, we'll need this later 2135249259Sdim unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2136249259Sdim unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2137249259Sdim 2138288943Sdim Assert(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I); 2139288943Sdim Assert(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I); 2140288943Sdim Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2141288943Sdim "sext source and destination must both be a vector or neither", &I); 2142288943Sdim Assert(SrcBitSize < DestBitSize, "Type too small for SExt", &I); 2143249259Sdim 2144249259Sdim visitInstruction(I); 2145249259Sdim} 2146249259Sdim 2147249259Sdimvoid Verifier::visitFPTruncInst(FPTruncInst &I) { 2148249259Sdim // Get the source and destination types 2149249259Sdim Type *SrcTy = I.getOperand(0)->getType(); 2150249259Sdim Type *DestTy = I.getType(); 2151249259Sdim // Get the size of the types in bits, we'll need this later 2152249259Sdim unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2153249259Sdim unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2154249259Sdim 2155288943Sdim Assert(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I); 2156288943Sdim Assert(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I); 2157288943Sdim Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2158288943Sdim "fptrunc source and destination must both be a vector or neither", &I); 2159288943Sdim Assert(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I); 2160249259Sdim 2161249259Sdim visitInstruction(I); 2162249259Sdim} 2163249259Sdim 2164249259Sdimvoid Verifier::visitFPExtInst(FPExtInst &I) { 2165249259Sdim // Get the source and destination types 2166249259Sdim Type *SrcTy = I.getOperand(0)->getType(); 2167249259Sdim Type *DestTy = I.getType(); 2168249259Sdim 2169249259Sdim // Get the size of the types in bits, we'll need this later 2170249259Sdim unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2171249259Sdim unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2172249259Sdim 2173288943Sdim Assert(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I); 2174288943Sdim Assert(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I); 2175288943Sdim Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2176288943Sdim "fpext source and destination must both be a vector or neither", &I); 2177288943Sdim Assert(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I); 2178249259Sdim 2179249259Sdim visitInstruction(I); 2180249259Sdim} 2181249259Sdim 2182249259Sdimvoid Verifier::visitUIToFPInst(UIToFPInst &I) { 2183249259Sdim // Get the source and destination types 2184249259Sdim Type *SrcTy = I.getOperand(0)->getType(); 2185249259Sdim Type *DestTy = I.getType(); 2186249259Sdim 2187249259Sdim bool SrcVec = SrcTy->isVectorTy(); 2188249259Sdim bool DstVec = DestTy->isVectorTy(); 2189249259Sdim 2190288943Sdim Assert(SrcVec == DstVec, 2191288943Sdim "UIToFP source and dest must both be vector or scalar", &I); 2192288943Sdim Assert(SrcTy->isIntOrIntVectorTy(), 2193288943Sdim "UIToFP source must be integer or integer vector", &I); 2194288943Sdim Assert(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector", 2195288943Sdim &I); 2196249259Sdim 2197249259Sdim if (SrcVec && DstVec) 2198288943Sdim Assert(cast<VectorType>(SrcTy)->getNumElements() == 2199288943Sdim cast<VectorType>(DestTy)->getNumElements(), 2200288943Sdim "UIToFP source and dest vector length mismatch", &I); 2201249259Sdim 2202249259Sdim visitInstruction(I); 2203249259Sdim} 2204249259Sdim 2205249259Sdimvoid Verifier::visitSIToFPInst(SIToFPInst &I) { 2206249259Sdim // Get the source and destination types 2207249259Sdim Type *SrcTy = I.getOperand(0)->getType(); 2208249259Sdim Type *DestTy = I.getType(); 2209249259Sdim 2210249259Sdim bool SrcVec = SrcTy->isVectorTy(); 2211249259Sdim bool DstVec = DestTy->isVectorTy(); 2212249259Sdim 2213288943Sdim Assert(SrcVec == DstVec, 2214288943Sdim "SIToFP source and dest must both be vector or scalar", &I); 2215288943Sdim Assert(SrcTy->isIntOrIntVectorTy(), 2216288943Sdim "SIToFP source must be integer or integer vector", &I); 2217288943Sdim Assert(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector", 2218288943Sdim &I); 2219249259Sdim 2220249259Sdim if (SrcVec && DstVec) 2221288943Sdim Assert(cast<VectorType>(SrcTy)->getNumElements() == 2222288943Sdim cast<VectorType>(DestTy)->getNumElements(), 2223288943Sdim "SIToFP source and dest vector length mismatch", &I); 2224249259Sdim 2225249259Sdim visitInstruction(I); 2226249259Sdim} 2227249259Sdim 2228249259Sdimvoid Verifier::visitFPToUIInst(FPToUIInst &I) { 2229249259Sdim // Get the source and destination types 2230249259Sdim Type *SrcTy = I.getOperand(0)->getType(); 2231249259Sdim Type *DestTy = I.getType(); 2232249259Sdim 2233249259Sdim bool SrcVec = SrcTy->isVectorTy(); 2234249259Sdim bool DstVec = DestTy->isVectorTy(); 2235249259Sdim 2236288943Sdim Assert(SrcVec == DstVec, 2237288943Sdim "FPToUI source and dest must both be vector or scalar", &I); 2238288943Sdim Assert(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector", 2239288943Sdim &I); 2240288943Sdim Assert(DestTy->isIntOrIntVectorTy(), 2241288943Sdim "FPToUI result must be integer or integer vector", &I); 2242249259Sdim 2243249259Sdim if (SrcVec && DstVec) 2244288943Sdim Assert(cast<VectorType>(SrcTy)->getNumElements() == 2245288943Sdim cast<VectorType>(DestTy)->getNumElements(), 2246288943Sdim "FPToUI source and dest vector length mismatch", &I); 2247249259Sdim 2248249259Sdim visitInstruction(I); 2249249259Sdim} 2250249259Sdim 2251249259Sdimvoid Verifier::visitFPToSIInst(FPToSIInst &I) { 2252249259Sdim // Get the source and destination types 2253249259Sdim Type *SrcTy = I.getOperand(0)->getType(); 2254249259Sdim Type *DestTy = I.getType(); 2255249259Sdim 2256249259Sdim bool SrcVec = SrcTy->isVectorTy(); 2257249259Sdim bool DstVec = DestTy->isVectorTy(); 2258249259Sdim 2259288943Sdim Assert(SrcVec == DstVec, 2260288943Sdim "FPToSI source and dest must both be vector or scalar", &I); 2261288943Sdim Assert(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector", 2262288943Sdim &I); 2263288943Sdim Assert(DestTy->isIntOrIntVectorTy(), 2264288943Sdim "FPToSI result must be integer or integer vector", &I); 2265249259Sdim 2266249259Sdim if (SrcVec && DstVec) 2267288943Sdim Assert(cast<VectorType>(SrcTy)->getNumElements() == 2268288943Sdim cast<VectorType>(DestTy)->getNumElements(), 2269288943Sdim "FPToSI source and dest vector length mismatch", &I); 2270249259Sdim 2271249259Sdim visitInstruction(I); 2272249259Sdim} 2273249259Sdim 2274249259Sdimvoid Verifier::visitPtrToIntInst(PtrToIntInst &I) { 2275249259Sdim // Get the source and destination types 2276249259Sdim Type *SrcTy = I.getOperand(0)->getType(); 2277249259Sdim Type *DestTy = I.getType(); 2278249259Sdim 2279288943Sdim Assert(SrcTy->getScalarType()->isPointerTy(), 2280288943Sdim "PtrToInt source must be pointer", &I); 2281288943Sdim Assert(DestTy->getScalarType()->isIntegerTy(), 2282288943Sdim "PtrToInt result must be integral", &I); 2283288943Sdim Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch", 2284288943Sdim &I); 2285249259Sdim 2286249259Sdim if (SrcTy->isVectorTy()) { 2287249259Sdim VectorType *VSrc = dyn_cast<VectorType>(SrcTy); 2288249259Sdim VectorType *VDest = dyn_cast<VectorType>(DestTy); 2289288943Sdim Assert(VSrc->getNumElements() == VDest->getNumElements(), 2290288943Sdim "PtrToInt Vector width mismatch", &I); 2291249259Sdim } 2292249259Sdim 2293249259Sdim visitInstruction(I); 2294249259Sdim} 2295249259Sdim 2296249259Sdimvoid Verifier::visitIntToPtrInst(IntToPtrInst &I) { 2297249259Sdim // Get the source and destination types 2298249259Sdim Type *SrcTy = I.getOperand(0)->getType(); 2299249259Sdim Type *DestTy = I.getType(); 2300249259Sdim 2301288943Sdim Assert(SrcTy->getScalarType()->isIntegerTy(), 2302288943Sdim "IntToPtr source must be an integral", &I); 2303288943Sdim Assert(DestTy->getScalarType()->isPointerTy(), 2304288943Sdim "IntToPtr result must be a pointer", &I); 2305288943Sdim Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch", 2306288943Sdim &I); 2307249259Sdim if (SrcTy->isVectorTy()) { 2308249259Sdim VectorType *VSrc = dyn_cast<VectorType>(SrcTy); 2309249259Sdim VectorType *VDest = dyn_cast<VectorType>(DestTy); 2310288943Sdim Assert(VSrc->getNumElements() == VDest->getNumElements(), 2311288943Sdim "IntToPtr Vector width mismatch", &I); 2312249259Sdim } 2313249259Sdim visitInstruction(I); 2314249259Sdim} 2315249259Sdim 2316249259Sdimvoid Verifier::visitBitCastInst(BitCastInst &I) { 2317288943Sdim Assert( 2318280031Sdim CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()), 2319280031Sdim "Invalid bitcast", &I); 2320261991Sdim visitInstruction(I); 2321261991Sdim} 2322249259Sdim 2323261991Sdimvoid Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) { 2324261991Sdim Type *SrcTy = I.getOperand(0)->getType(); 2325261991Sdim Type *DestTy = I.getType(); 2326249259Sdim 2327288943Sdim Assert(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer", 2328288943Sdim &I); 2329288943Sdim Assert(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer", 2330288943Sdim &I); 2331288943Sdim Assert(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(), 2332288943Sdim "AddrSpaceCast must be between different address spaces", &I); 2333261991Sdim if (SrcTy->isVectorTy()) 2334288943Sdim Assert(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(), 2335288943Sdim "AddrSpaceCast vector pointer number of elements mismatch", &I); 2336249259Sdim visitInstruction(I); 2337249259Sdim} 2338249259Sdim 2339249259Sdim/// visitPHINode - Ensure that a PHI node is well formed. 2340249259Sdim/// 2341249259Sdimvoid Verifier::visitPHINode(PHINode &PN) { 2342249259Sdim // Ensure that the PHI nodes are all grouped together at the top of the block. 2343249259Sdim // This can be tested by checking whether the instruction before this is 2344249259Sdim // either nonexistent (because this is begin()) or is a PHI node. If not, 2345249259Sdim // then there is some other instruction before a PHI. 2346288943Sdim Assert(&PN == &PN.getParent()->front() || 2347288943Sdim isa<PHINode>(--BasicBlock::iterator(&PN)), 2348288943Sdim "PHI nodes not grouped at top of basic block!", &PN, PN.getParent()); 2349249259Sdim 2350296417Sdim // Check that a PHI doesn't yield a Token. 2351296417Sdim Assert(!PN.getType()->isTokenTy(), "PHI nodes cannot have token type!"); 2352296417Sdim 2353249259Sdim // Check that all of the values of the PHI node have the same type as the 2354249259Sdim // result, and that the incoming blocks are really basic blocks. 2355288943Sdim for (Value *IncValue : PN.incoming_values()) { 2356288943Sdim Assert(PN.getType() == IncValue->getType(), 2357288943Sdim "PHI node operands are not the same type as the result!", &PN); 2358249259Sdim } 2359249259Sdim 2360249259Sdim // All other PHI node constraints are checked in the visitBasicBlock method. 2361249259Sdim 2362249259Sdim visitInstruction(PN); 2363249259Sdim} 2364249259Sdim 2365249259Sdimvoid Verifier::VerifyCallSite(CallSite CS) { 2366249259Sdim Instruction *I = CS.getInstruction(); 2367249259Sdim 2368288943Sdim Assert(CS.getCalledValue()->getType()->isPointerTy(), 2369288943Sdim "Called function must be a pointer!", I); 2370249259Sdim PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType()); 2371249259Sdim 2372288943Sdim Assert(FPTy->getElementType()->isFunctionTy(), 2373288943Sdim "Called function is not pointer to function type!", I); 2374249259Sdim 2375288943Sdim Assert(FPTy->getElementType() == CS.getFunctionType(), 2376288943Sdim "Called function is not the same type as the call!", I); 2377288943Sdim 2378288943Sdim FunctionType *FTy = CS.getFunctionType(); 2379288943Sdim 2380249259Sdim // Verify that the correct number of arguments are being passed 2381249259Sdim if (FTy->isVarArg()) 2382288943Sdim Assert(CS.arg_size() >= FTy->getNumParams(), 2383288943Sdim "Called function requires more parameters than were provided!", I); 2384249259Sdim else 2385288943Sdim Assert(CS.arg_size() == FTy->getNumParams(), 2386288943Sdim "Incorrect number of arguments passed to called function!", I); 2387249259Sdim 2388249259Sdim // Verify that all arguments to the call match the function type. 2389249259Sdim for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 2390288943Sdim Assert(CS.getArgument(i)->getType() == FTy->getParamType(i), 2391288943Sdim "Call parameter type does not match function signature!", 2392288943Sdim CS.getArgument(i), FTy->getParamType(i), I); 2393249259Sdim 2394251662Sdim AttributeSet Attrs = CS.getAttributes(); 2395249259Sdim 2396288943Sdim Assert(VerifyAttributeCount(Attrs, CS.arg_size()), 2397288943Sdim "Attribute after last parameter!", I); 2398249259Sdim 2399249259Sdim // Verify call attributes. 2400249259Sdim VerifyFunctionAttrs(FTy, Attrs, I); 2401249259Sdim 2402276479Sdim // Conservatively check the inalloca argument. 2403276479Sdim // We have a bug if we can find that there is an underlying alloca without 2404276479Sdim // inalloca. 2405276479Sdim if (CS.hasInAllocaArgument()) { 2406276479Sdim Value *InAllocaArg = CS.getArgument(FTy->getNumParams() - 1); 2407276479Sdim if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets())) 2408288943Sdim Assert(AI->isUsedWithInAlloca(), 2409288943Sdim "inalloca argument for call has mismatched alloca", AI, I); 2410276479Sdim } 2411276479Sdim 2412251662Sdim if (FTy->isVarArg()) { 2413251662Sdim // FIXME? is 'nest' even legal here? 2414251662Sdim bool SawNest = false; 2415251662Sdim bool SawReturned = false; 2416251662Sdim 2417251662Sdim for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) { 2418251662Sdim if (Attrs.hasAttribute(Idx, Attribute::Nest)) 2419251662Sdim SawNest = true; 2420251662Sdim if (Attrs.hasAttribute(Idx, Attribute::Returned)) 2421251662Sdim SawReturned = true; 2422251662Sdim } 2423251662Sdim 2424249259Sdim // Check attributes on the varargs part. 2425249259Sdim for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) { 2426261991Sdim Type *Ty = CS.getArgument(Idx-1)->getType(); 2427251662Sdim VerifyParameterAttrs(Attrs, Idx, Ty, false, I); 2428261991Sdim 2429251662Sdim if (Attrs.hasAttribute(Idx, Attribute::Nest)) { 2430288943Sdim Assert(!SawNest, "More than one parameter has attribute nest!", I); 2431251662Sdim SawNest = true; 2432251662Sdim } 2433249259Sdim 2434251662Sdim if (Attrs.hasAttribute(Idx, Attribute::Returned)) { 2435288943Sdim Assert(!SawReturned, "More than one parameter has attribute returned!", 2436288943Sdim I); 2437288943Sdim Assert(Ty->canLosslesslyBitCastTo(FTy->getReturnType()), 2438288943Sdim "Incompatible argument and return types for 'returned' " 2439288943Sdim "attribute", 2440288943Sdim I); 2441251662Sdim SawReturned = true; 2442251662Sdim } 2443251662Sdim 2444288943Sdim Assert(!Attrs.hasAttribute(Idx, Attribute::StructRet), 2445288943Sdim "Attribute 'sret' cannot be used for vararg call arguments!", I); 2446276479Sdim 2447276479Sdim if (Attrs.hasAttribute(Idx, Attribute::InAlloca)) 2448288943Sdim Assert(Idx == CS.arg_size(), "inalloca isn't on the last argument!", I); 2449249259Sdim } 2450251662Sdim } 2451249259Sdim 2452249259Sdim // Verify that there's no metadata unless it's a direct call to an intrinsic. 2453276479Sdim if (CS.getCalledFunction() == nullptr || 2454249259Sdim !CS.getCalledFunction()->getName().startswith("llvm.")) { 2455296417Sdim for (Type *ParamTy : FTy->params()) { 2456296417Sdim Assert(!ParamTy->isMetadataTy(), 2457288943Sdim "Function has metadata parameter but isn't an intrinsic", I); 2458296417Sdim Assert(!ParamTy->isTokenTy(), 2459296417Sdim "Function has token parameter but isn't an intrinsic", I); 2460296417Sdim } 2461249259Sdim } 2462249259Sdim 2463296417Sdim // Verify that indirect calls don't return tokens. 2464296417Sdim if (CS.getCalledFunction() == nullptr) 2465296417Sdim Assert(!FTy->getReturnType()->isTokenTy(), 2466296417Sdim "Return type cannot be token for indirect call!"); 2467296417Sdim 2468288943Sdim if (Function *F = CS.getCalledFunction()) 2469288943Sdim if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) 2470288943Sdim visitIntrinsicCallSite(ID, CS); 2471288943Sdim 2472296417Sdim // Verify that a callsite has at most one "deopt" and one "funclet" operand 2473296417Sdim // bundle. 2474296417Sdim bool FoundDeoptBundle = false, FoundFuncletBundle = false; 2475296417Sdim for (unsigned i = 0, e = CS.getNumOperandBundles(); i < e; ++i) { 2476296417Sdim OperandBundleUse BU = CS.getOperandBundleAt(i); 2477296417Sdim uint32_t Tag = BU.getTagID(); 2478296417Sdim if (Tag == LLVMContext::OB_deopt) { 2479296417Sdim Assert(!FoundDeoptBundle, "Multiple deopt operand bundles", I); 2480296417Sdim FoundDeoptBundle = true; 2481296417Sdim } 2482296417Sdim if (Tag == LLVMContext::OB_funclet) { 2483296417Sdim Assert(!FoundFuncletBundle, "Multiple funclet operand bundles", I); 2484296417Sdim FoundFuncletBundle = true; 2485296417Sdim Assert(BU.Inputs.size() == 1, 2486296417Sdim "Expected exactly one funclet bundle operand", I); 2487296417Sdim Assert(isa<FuncletPadInst>(BU.Inputs.front()), 2488296417Sdim "Funclet bundle operands should correspond to a FuncletPadInst", 2489296417Sdim I); 2490296417Sdim } 2491296417Sdim } 2492296417Sdim 2493249259Sdim visitInstruction(*I); 2494249259Sdim} 2495249259Sdim 2496276479Sdim/// Two types are "congruent" if they are identical, or if they are both pointer 2497276479Sdim/// types with different pointee types and the same address space. 2498276479Sdimstatic bool isTypeCongruent(Type *L, Type *R) { 2499276479Sdim if (L == R) 2500276479Sdim return true; 2501276479Sdim PointerType *PL = dyn_cast<PointerType>(L); 2502276479Sdim PointerType *PR = dyn_cast<PointerType>(R); 2503276479Sdim if (!PL || !PR) 2504276479Sdim return false; 2505276479Sdim return PL->getAddressSpace() == PR->getAddressSpace(); 2506276479Sdim} 2507276479Sdim 2508276479Sdimstatic AttrBuilder getParameterABIAttributes(int I, AttributeSet Attrs) { 2509276479Sdim static const Attribute::AttrKind ABIAttrs[] = { 2510276479Sdim Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca, 2511276479Sdim Attribute::InReg, Attribute::Returned}; 2512276479Sdim AttrBuilder Copy; 2513276479Sdim for (auto AK : ABIAttrs) { 2514276479Sdim if (Attrs.hasAttribute(I + 1, AK)) 2515276479Sdim Copy.addAttribute(AK); 2516276479Sdim } 2517276479Sdim if (Attrs.hasAttribute(I + 1, Attribute::Alignment)) 2518276479Sdim Copy.addAlignmentAttr(Attrs.getParamAlignment(I + 1)); 2519276479Sdim return Copy; 2520276479Sdim} 2521276479Sdim 2522276479Sdimvoid Verifier::verifyMustTailCall(CallInst &CI) { 2523288943Sdim Assert(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI); 2524276479Sdim 2525276479Sdim // - The caller and callee prototypes must match. Pointer types of 2526276479Sdim // parameters or return types may differ in pointee type, but not 2527276479Sdim // address space. 2528276479Sdim Function *F = CI.getParent()->getParent(); 2529288943Sdim FunctionType *CallerTy = F->getFunctionType(); 2530288943Sdim FunctionType *CalleeTy = CI.getFunctionType(); 2531288943Sdim Assert(CallerTy->getNumParams() == CalleeTy->getNumParams(), 2532288943Sdim "cannot guarantee tail call due to mismatched parameter counts", &CI); 2533288943Sdim Assert(CallerTy->isVarArg() == CalleeTy->isVarArg(), 2534288943Sdim "cannot guarantee tail call due to mismatched varargs", &CI); 2535288943Sdim Assert(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()), 2536288943Sdim "cannot guarantee tail call due to mismatched return types", &CI); 2537276479Sdim for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) { 2538288943Sdim Assert( 2539276479Sdim isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)), 2540276479Sdim "cannot guarantee tail call due to mismatched parameter types", &CI); 2541276479Sdim } 2542276479Sdim 2543276479Sdim // - The calling conventions of the caller and callee must match. 2544288943Sdim Assert(F->getCallingConv() == CI.getCallingConv(), 2545288943Sdim "cannot guarantee tail call due to mismatched calling conv", &CI); 2546276479Sdim 2547276479Sdim // - All ABI-impacting function attributes, such as sret, byval, inreg, 2548276479Sdim // returned, and inalloca, must match. 2549276479Sdim AttributeSet CallerAttrs = F->getAttributes(); 2550276479Sdim AttributeSet CalleeAttrs = CI.getAttributes(); 2551276479Sdim for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) { 2552276479Sdim AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs); 2553276479Sdim AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs); 2554288943Sdim Assert(CallerABIAttrs == CalleeABIAttrs, 2555288943Sdim "cannot guarantee tail call due to mismatched ABI impacting " 2556288943Sdim "function attributes", 2557288943Sdim &CI, CI.getOperand(I)); 2558276479Sdim } 2559276479Sdim 2560276479Sdim // - The call must immediately precede a :ref:`ret <i_ret>` instruction, 2561276479Sdim // or a pointer bitcast followed by a ret instruction. 2562276479Sdim // - The ret instruction must return the (possibly bitcasted) value 2563276479Sdim // produced by the call or void. 2564276479Sdim Value *RetVal = &CI; 2565276479Sdim Instruction *Next = CI.getNextNode(); 2566276479Sdim 2567276479Sdim // Handle the optional bitcast. 2568276479Sdim if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) { 2569288943Sdim Assert(BI->getOperand(0) == RetVal, 2570288943Sdim "bitcast following musttail call must use the call", BI); 2571276479Sdim RetVal = BI; 2572276479Sdim Next = BI->getNextNode(); 2573276479Sdim } 2574276479Sdim 2575276479Sdim // Check the return. 2576276479Sdim ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next); 2577288943Sdim Assert(Ret, "musttail call must be precede a ret with an optional bitcast", 2578288943Sdim &CI); 2579288943Sdim Assert(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal, 2580288943Sdim "musttail call result must be returned", Ret); 2581276479Sdim} 2582276479Sdim 2583249259Sdimvoid Verifier::visitCallInst(CallInst &CI) { 2584249259Sdim VerifyCallSite(&CI); 2585249259Sdim 2586276479Sdim if (CI.isMustTailCall()) 2587276479Sdim verifyMustTailCall(CI); 2588249259Sdim} 2589249259Sdim 2590249259Sdimvoid Verifier::visitInvokeInst(InvokeInst &II) { 2591249259Sdim VerifyCallSite(&II); 2592249259Sdim 2593296417Sdim // Verify that the first non-PHI instruction of the unwind destination is an 2594296417Sdim // exception handling instruction. 2595296417Sdim Assert( 2596296417Sdim II.getUnwindDest()->isEHPad(), 2597296417Sdim "The unwind destination does not have an exception handling instruction!", 2598296417Sdim &II); 2599249259Sdim 2600249259Sdim visitTerminatorInst(II); 2601249259Sdim} 2602249259Sdim 2603249259Sdim/// visitBinaryOperator - Check that both arguments to the binary operator are 2604249259Sdim/// of the same type! 2605249259Sdim/// 2606249259Sdimvoid Verifier::visitBinaryOperator(BinaryOperator &B) { 2607288943Sdim Assert(B.getOperand(0)->getType() == B.getOperand(1)->getType(), 2608288943Sdim "Both operands to a binary operator are not of the same type!", &B); 2609249259Sdim 2610249259Sdim switch (B.getOpcode()) { 2611249259Sdim // Check that integer arithmetic operators are only used with 2612249259Sdim // integral operands. 2613249259Sdim case Instruction::Add: 2614249259Sdim case Instruction::Sub: 2615249259Sdim case Instruction::Mul: 2616249259Sdim case Instruction::SDiv: 2617249259Sdim case Instruction::UDiv: 2618249259Sdim case Instruction::SRem: 2619249259Sdim case Instruction::URem: 2620288943Sdim Assert(B.getType()->isIntOrIntVectorTy(), 2621288943Sdim "Integer arithmetic operators only work with integral types!", &B); 2622288943Sdim Assert(B.getType() == B.getOperand(0)->getType(), 2623288943Sdim "Integer arithmetic operators must have same type " 2624288943Sdim "for operands and result!", 2625288943Sdim &B); 2626249259Sdim break; 2627249259Sdim // Check that floating-point arithmetic operators are only used with 2628249259Sdim // floating-point operands. 2629249259Sdim case Instruction::FAdd: 2630249259Sdim case Instruction::FSub: 2631249259Sdim case Instruction::FMul: 2632249259Sdim case Instruction::FDiv: 2633249259Sdim case Instruction::FRem: 2634288943Sdim Assert(B.getType()->isFPOrFPVectorTy(), 2635288943Sdim "Floating-point arithmetic operators only work with " 2636288943Sdim "floating-point types!", 2637288943Sdim &B); 2638288943Sdim Assert(B.getType() == B.getOperand(0)->getType(), 2639288943Sdim "Floating-point arithmetic operators must have same type " 2640288943Sdim "for operands and result!", 2641288943Sdim &B); 2642249259Sdim break; 2643249259Sdim // Check that logical operators are only used with integral operands. 2644249259Sdim case Instruction::And: 2645249259Sdim case Instruction::Or: 2646249259Sdim case Instruction::Xor: 2647288943Sdim Assert(B.getType()->isIntOrIntVectorTy(), 2648288943Sdim "Logical operators only work with integral types!", &B); 2649288943Sdim Assert(B.getType() == B.getOperand(0)->getType(), 2650288943Sdim "Logical operators must have same type for operands and result!", 2651288943Sdim &B); 2652249259Sdim break; 2653249259Sdim case Instruction::Shl: 2654249259Sdim case Instruction::LShr: 2655249259Sdim case Instruction::AShr: 2656288943Sdim Assert(B.getType()->isIntOrIntVectorTy(), 2657288943Sdim "Shifts only work with integral types!", &B); 2658288943Sdim Assert(B.getType() == B.getOperand(0)->getType(), 2659288943Sdim "Shift return type must be same as operands!", &B); 2660249259Sdim break; 2661249259Sdim default: 2662249259Sdim llvm_unreachable("Unknown BinaryOperator opcode!"); 2663249259Sdim } 2664249259Sdim 2665249259Sdim visitInstruction(B); 2666249259Sdim} 2667249259Sdim 2668249259Sdimvoid Verifier::visitICmpInst(ICmpInst &IC) { 2669249259Sdim // Check that the operands are the same type 2670249259Sdim Type *Op0Ty = IC.getOperand(0)->getType(); 2671249259Sdim Type *Op1Ty = IC.getOperand(1)->getType(); 2672288943Sdim Assert(Op0Ty == Op1Ty, 2673288943Sdim "Both operands to ICmp instruction are not of the same type!", &IC); 2674249259Sdim // Check that the operands are the right type 2675288943Sdim Assert(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(), 2676288943Sdim "Invalid operand types for ICmp instruction", &IC); 2677249259Sdim // Check that the predicate is valid. 2678288943Sdim Assert(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE && 2679288943Sdim IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE, 2680288943Sdim "Invalid predicate in ICmp instruction!", &IC); 2681249259Sdim 2682249259Sdim visitInstruction(IC); 2683249259Sdim} 2684249259Sdim 2685249259Sdimvoid Verifier::visitFCmpInst(FCmpInst &FC) { 2686249259Sdim // Check that the operands are the same type 2687249259Sdim Type *Op0Ty = FC.getOperand(0)->getType(); 2688249259Sdim Type *Op1Ty = FC.getOperand(1)->getType(); 2689288943Sdim Assert(Op0Ty == Op1Ty, 2690288943Sdim "Both operands to FCmp instruction are not of the same type!", &FC); 2691249259Sdim // Check that the operands are the right type 2692288943Sdim Assert(Op0Ty->isFPOrFPVectorTy(), 2693288943Sdim "Invalid operand types for FCmp instruction", &FC); 2694249259Sdim // Check that the predicate is valid. 2695288943Sdim Assert(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE && 2696288943Sdim FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE, 2697288943Sdim "Invalid predicate in FCmp instruction!", &FC); 2698249259Sdim 2699249259Sdim visitInstruction(FC); 2700249259Sdim} 2701249259Sdim 2702249259Sdimvoid Verifier::visitExtractElementInst(ExtractElementInst &EI) { 2703288943Sdim Assert( 2704288943Sdim ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)), 2705288943Sdim "Invalid extractelement operands!", &EI); 2706249259Sdim visitInstruction(EI); 2707249259Sdim} 2708249259Sdim 2709249259Sdimvoid Verifier::visitInsertElementInst(InsertElementInst &IE) { 2710288943Sdim Assert(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1), 2711288943Sdim IE.getOperand(2)), 2712288943Sdim "Invalid insertelement operands!", &IE); 2713249259Sdim visitInstruction(IE); 2714249259Sdim} 2715249259Sdim 2716249259Sdimvoid Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) { 2717288943Sdim Assert(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1), 2718288943Sdim SV.getOperand(2)), 2719288943Sdim "Invalid shufflevector operands!", &SV); 2720249259Sdim visitInstruction(SV); 2721249259Sdim} 2722249259Sdim 2723249259Sdimvoid Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) { 2724249259Sdim Type *TargetTy = GEP.getPointerOperandType()->getScalarType(); 2725249259Sdim 2726288943Sdim Assert(isa<PointerType>(TargetTy), 2727288943Sdim "GEP base pointer is not a vector or a vector of pointers", &GEP); 2728288943Sdim Assert(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP); 2729249259Sdim SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end()); 2730249259Sdim Type *ElTy = 2731288943Sdim GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs); 2732288943Sdim Assert(ElTy, "Invalid indices for GEP pointer type!", &GEP); 2733249259Sdim 2734288943Sdim Assert(GEP.getType()->getScalarType()->isPointerTy() && 2735288943Sdim GEP.getResultElementType() == ElTy, 2736288943Sdim "GEP is not of right type for indices!", &GEP, ElTy); 2737249259Sdim 2738288943Sdim if (GEP.getType()->isVectorTy()) { 2739249259Sdim // Additional checks for vector GEPs. 2740288943Sdim unsigned GEPWidth = GEP.getType()->getVectorNumElements(); 2741288943Sdim if (GEP.getPointerOperandType()->isVectorTy()) 2742288943Sdim Assert(GEPWidth == GEP.getPointerOperandType()->getVectorNumElements(), 2743288943Sdim "Vector GEP result width doesn't match operand's", &GEP); 2744249259Sdim for (unsigned i = 0, e = Idxs.size(); i != e; ++i) { 2745249259Sdim Type *IndexTy = Idxs[i]->getType(); 2746288943Sdim if (IndexTy->isVectorTy()) { 2747288943Sdim unsigned IndexWidth = IndexTy->getVectorNumElements(); 2748288943Sdim Assert(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP); 2749288943Sdim } 2750288943Sdim Assert(IndexTy->getScalarType()->isIntegerTy(), 2751288943Sdim "All GEP indices should be of integer type"); 2752249259Sdim } 2753249259Sdim } 2754249259Sdim visitInstruction(GEP); 2755249259Sdim} 2756249259Sdim 2757249259Sdimstatic bool isContiguous(const ConstantRange &A, const ConstantRange &B) { 2758249259Sdim return A.getUpper() == B.getLower() || A.getLower() == B.getUpper(); 2759249259Sdim} 2760249259Sdim 2761280031Sdimvoid Verifier::visitRangeMetadata(Instruction& I, 2762280031Sdim MDNode* Range, Type* Ty) { 2763280031Sdim assert(Range && 2764280031Sdim Range == I.getMetadata(LLVMContext::MD_range) && 2765280031Sdim "precondition violation"); 2766280031Sdim 2767280031Sdim unsigned NumOperands = Range->getNumOperands(); 2768288943Sdim Assert(NumOperands % 2 == 0, "Unfinished range!", Range); 2769280031Sdim unsigned NumRanges = NumOperands / 2; 2770288943Sdim Assert(NumRanges >= 1, "It should have at least one range!", Range); 2771288943Sdim 2772280031Sdim ConstantRange LastRange(1); // Dummy initial value 2773280031Sdim for (unsigned i = 0; i < NumRanges; ++i) { 2774280031Sdim ConstantInt *Low = 2775280031Sdim mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i)); 2776288943Sdim Assert(Low, "The lower limit must be an integer!", Low); 2777280031Sdim ConstantInt *High = 2778280031Sdim mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1)); 2779288943Sdim Assert(High, "The upper limit must be an integer!", High); 2780288943Sdim Assert(High->getType() == Low->getType() && High->getType() == Ty, 2781288943Sdim "Range types must match instruction type!", &I); 2782288943Sdim 2783280031Sdim APInt HighV = High->getValue(); 2784280031Sdim APInt LowV = Low->getValue(); 2785280031Sdim ConstantRange CurRange(LowV, HighV); 2786288943Sdim Assert(!CurRange.isEmptySet() && !CurRange.isFullSet(), 2787288943Sdim "Range must not be empty!", Range); 2788280031Sdim if (i != 0) { 2789288943Sdim Assert(CurRange.intersectWith(LastRange).isEmptySet(), 2790288943Sdim "Intervals are overlapping", Range); 2791288943Sdim Assert(LowV.sgt(LastRange.getLower()), "Intervals are not in order", 2792288943Sdim Range); 2793288943Sdim Assert(!isContiguous(CurRange, LastRange), "Intervals are contiguous", 2794288943Sdim Range); 2795280031Sdim } 2796280031Sdim LastRange = ConstantRange(LowV, HighV); 2797280031Sdim } 2798280031Sdim if (NumRanges > 2) { 2799280031Sdim APInt FirstLow = 2800280031Sdim mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue(); 2801280031Sdim APInt FirstHigh = 2802280031Sdim mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue(); 2803280031Sdim ConstantRange FirstRange(FirstLow, FirstHigh); 2804288943Sdim Assert(FirstRange.intersectWith(LastRange).isEmptySet(), 2805288943Sdim "Intervals are overlapping", Range); 2806288943Sdim Assert(!isContiguous(FirstRange, LastRange), "Intervals are contiguous", 2807288943Sdim Range); 2808280031Sdim } 2809280031Sdim} 2810280031Sdim 2811296417Sdimvoid Verifier::checkAtomicMemAccessSize(const Module *M, Type *Ty, 2812296417Sdim const Instruction *I) { 2813296417Sdim unsigned Size = M->getDataLayout().getTypeSizeInBits(Ty); 2814296417Sdim Assert(Size >= 8, "atomic memory access' size must be byte-sized", Ty, I); 2815296417Sdim Assert(!(Size & (Size - 1)), 2816296417Sdim "atomic memory access' operand must have a power-of-two size", Ty, I); 2817296417Sdim} 2818296417Sdim 2819249259Sdimvoid Verifier::visitLoadInst(LoadInst &LI) { 2820249259Sdim PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType()); 2821288943Sdim Assert(PTy, "Load operand must be a pointer.", &LI); 2822288943Sdim Type *ElTy = LI.getType(); 2823288943Sdim Assert(LI.getAlignment() <= Value::MaximumAlignment, 2824288943Sdim "huge alignment values are unsupported", &LI); 2825249259Sdim if (LI.isAtomic()) { 2826288943Sdim Assert(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease, 2827288943Sdim "Load cannot have Release ordering", &LI); 2828288943Sdim Assert(LI.getAlignment() != 0, 2829288943Sdim "Atomic load must specify explicit alignment", &LI); 2830296417Sdim Assert(ElTy->isIntegerTy() || ElTy->isPointerTy() || 2831296417Sdim ElTy->isFloatingPointTy(), 2832296417Sdim "atomic load operand must have integer, pointer, or floating point " 2833296417Sdim "type!", 2834296417Sdim ElTy, &LI); 2835296417Sdim checkAtomicMemAccessSize(M, ElTy, &LI); 2836249259Sdim } else { 2837288943Sdim Assert(LI.getSynchScope() == CrossThread, 2838288943Sdim "Non-atomic load cannot have SynchronizationScope specified", &LI); 2839249259Sdim } 2840249259Sdim 2841249259Sdim visitInstruction(LI); 2842249259Sdim} 2843249259Sdim 2844249259Sdimvoid Verifier::visitStoreInst(StoreInst &SI) { 2845249259Sdim PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType()); 2846288943Sdim Assert(PTy, "Store operand must be a pointer.", &SI); 2847249259Sdim Type *ElTy = PTy->getElementType(); 2848288943Sdim Assert(ElTy == SI.getOperand(0)->getType(), 2849288943Sdim "Stored value type does not match pointer operand type!", &SI, ElTy); 2850288943Sdim Assert(SI.getAlignment() <= Value::MaximumAlignment, 2851288943Sdim "huge alignment values are unsupported", &SI); 2852249259Sdim if (SI.isAtomic()) { 2853288943Sdim Assert(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease, 2854288943Sdim "Store cannot have Acquire ordering", &SI); 2855288943Sdim Assert(SI.getAlignment() != 0, 2856288943Sdim "Atomic store must specify explicit alignment", &SI); 2857296417Sdim Assert(ElTy->isIntegerTy() || ElTy->isPointerTy() || 2858296417Sdim ElTy->isFloatingPointTy(), 2859296417Sdim "atomic store operand must have integer, pointer, or floating point " 2860296417Sdim "type!", 2861296417Sdim ElTy, &SI); 2862296417Sdim checkAtomicMemAccessSize(M, ElTy, &SI); 2863249259Sdim } else { 2864288943Sdim Assert(SI.getSynchScope() == CrossThread, 2865288943Sdim "Non-atomic store cannot have SynchronizationScope specified", &SI); 2866249259Sdim } 2867249259Sdim visitInstruction(SI); 2868249259Sdim} 2869249259Sdim 2870249259Sdimvoid Verifier::visitAllocaInst(AllocaInst &AI) { 2871296417Sdim SmallPtrSet<Type*, 4> Visited; 2872249259Sdim PointerType *PTy = AI.getType(); 2873288943Sdim Assert(PTy->getAddressSpace() == 0, 2874288943Sdim "Allocation instruction pointer not in the generic address space!", 2875288943Sdim &AI); 2876288943Sdim Assert(AI.getAllocatedType()->isSized(&Visited), 2877288943Sdim "Cannot allocate unsized type", &AI); 2878288943Sdim Assert(AI.getArraySize()->getType()->isIntegerTy(), 2879288943Sdim "Alloca array size must have integer type", &AI); 2880288943Sdim Assert(AI.getAlignment() <= Value::MaximumAlignment, 2881288943Sdim "huge alignment values are unsupported", &AI); 2882276479Sdim 2883249259Sdim visitInstruction(AI); 2884249259Sdim} 2885249259Sdim 2886249259Sdimvoid Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) { 2887276479Sdim 2888276479Sdim // FIXME: more conditions??? 2889288943Sdim Assert(CXI.getSuccessOrdering() != NotAtomic, 2890288943Sdim "cmpxchg instructions must be atomic.", &CXI); 2891288943Sdim Assert(CXI.getFailureOrdering() != NotAtomic, 2892288943Sdim "cmpxchg instructions must be atomic.", &CXI); 2893288943Sdim Assert(CXI.getSuccessOrdering() != Unordered, 2894288943Sdim "cmpxchg instructions cannot be unordered.", &CXI); 2895288943Sdim Assert(CXI.getFailureOrdering() != Unordered, 2896288943Sdim "cmpxchg instructions cannot be unordered.", &CXI); 2897288943Sdim Assert(CXI.getSuccessOrdering() >= CXI.getFailureOrdering(), 2898288943Sdim "cmpxchg instructions be at least as constrained on success as fail", 2899288943Sdim &CXI); 2900288943Sdim Assert(CXI.getFailureOrdering() != Release && 2901288943Sdim CXI.getFailureOrdering() != AcquireRelease, 2902288943Sdim "cmpxchg failure ordering cannot include release semantics", &CXI); 2903276479Sdim 2904249259Sdim PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType()); 2905288943Sdim Assert(PTy, "First cmpxchg operand must be a pointer.", &CXI); 2906249259Sdim Type *ElTy = PTy->getElementType(); 2907288943Sdim Assert(ElTy->isIntegerTy(), "cmpxchg operand must have integer type!", &CXI, 2908288943Sdim ElTy); 2909296417Sdim checkAtomicMemAccessSize(M, ElTy, &CXI); 2910288943Sdim Assert(ElTy == CXI.getOperand(1)->getType(), 2911288943Sdim "Expected value type does not match pointer operand type!", &CXI, 2912288943Sdim ElTy); 2913288943Sdim Assert(ElTy == CXI.getOperand(2)->getType(), 2914288943Sdim "Stored value type does not match pointer operand type!", &CXI, ElTy); 2915249259Sdim visitInstruction(CXI); 2916249259Sdim} 2917249259Sdim 2918249259Sdimvoid Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) { 2919288943Sdim Assert(RMWI.getOrdering() != NotAtomic, 2920288943Sdim "atomicrmw instructions must be atomic.", &RMWI); 2921288943Sdim Assert(RMWI.getOrdering() != Unordered, 2922288943Sdim "atomicrmw instructions cannot be unordered.", &RMWI); 2923249259Sdim PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType()); 2924288943Sdim Assert(PTy, "First atomicrmw operand must be a pointer.", &RMWI); 2925249259Sdim Type *ElTy = PTy->getElementType(); 2926288943Sdim Assert(ElTy->isIntegerTy(), "atomicrmw operand must have integer type!", 2927288943Sdim &RMWI, ElTy); 2928296417Sdim checkAtomicMemAccessSize(M, ElTy, &RMWI); 2929288943Sdim Assert(ElTy == RMWI.getOperand(1)->getType(), 2930288943Sdim "Argument value type does not match pointer operand type!", &RMWI, 2931288943Sdim ElTy); 2932288943Sdim Assert(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() && 2933288943Sdim RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP, 2934288943Sdim "Invalid binary operation!", &RMWI); 2935249259Sdim visitInstruction(RMWI); 2936249259Sdim} 2937249259Sdim 2938249259Sdimvoid Verifier::visitFenceInst(FenceInst &FI) { 2939249259Sdim const AtomicOrdering Ordering = FI.getOrdering(); 2940288943Sdim Assert(Ordering == Acquire || Ordering == Release || 2941288943Sdim Ordering == AcquireRelease || Ordering == SequentiallyConsistent, 2942288943Sdim "fence instructions may only have " 2943288943Sdim "acquire, release, acq_rel, or seq_cst ordering.", 2944288943Sdim &FI); 2945249259Sdim visitInstruction(FI); 2946249259Sdim} 2947249259Sdim 2948249259Sdimvoid Verifier::visitExtractValueInst(ExtractValueInst &EVI) { 2949288943Sdim Assert(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(), 2950288943Sdim EVI.getIndices()) == EVI.getType(), 2951288943Sdim "Invalid ExtractValueInst operands!", &EVI); 2952261991Sdim 2953249259Sdim visitInstruction(EVI); 2954249259Sdim} 2955249259Sdim 2956249259Sdimvoid Verifier::visitInsertValueInst(InsertValueInst &IVI) { 2957288943Sdim Assert(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(), 2958288943Sdim IVI.getIndices()) == 2959288943Sdim IVI.getOperand(1)->getType(), 2960288943Sdim "Invalid InsertValueInst operands!", &IVI); 2961261991Sdim 2962249259Sdim visitInstruction(IVI); 2963249259Sdim} 2964249259Sdim 2965296417Sdimstatic Value *getParentPad(Value *EHPad) { 2966296417Sdim if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad)) 2967296417Sdim return FPI->getParentPad(); 2968296417Sdim 2969296417Sdim return cast<CatchSwitchInst>(EHPad)->getParentPad(); 2970296417Sdim} 2971296417Sdim 2972296417Sdimvoid Verifier::visitEHPadPredecessors(Instruction &I) { 2973296417Sdim assert(I.isEHPad()); 2974296417Sdim 2975296417Sdim BasicBlock *BB = I.getParent(); 2976296417Sdim Function *F = BB->getParent(); 2977296417Sdim 2978296417Sdim Assert(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I); 2979296417Sdim 2980296417Sdim if (auto *LPI = dyn_cast<LandingPadInst>(&I)) { 2981296417Sdim // The landingpad instruction defines its parent as a landing pad block. The 2982296417Sdim // landing pad block may be branched to only by the unwind edge of an 2983296417Sdim // invoke. 2984296417Sdim for (BasicBlock *PredBB : predecessors(BB)) { 2985296417Sdim const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator()); 2986296417Sdim Assert(II && II->getUnwindDest() == BB && II->getNormalDest() != BB, 2987296417Sdim "Block containing LandingPadInst must be jumped to " 2988296417Sdim "only by the unwind edge of an invoke.", 2989296417Sdim LPI); 2990296417Sdim } 2991296417Sdim return; 2992296417Sdim } 2993296417Sdim if (auto *CPI = dyn_cast<CatchPadInst>(&I)) { 2994296417Sdim if (!pred_empty(BB)) 2995296417Sdim Assert(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(), 2996296417Sdim "Block containg CatchPadInst must be jumped to " 2997296417Sdim "only by its catchswitch.", 2998296417Sdim CPI); 2999296417Sdim Assert(BB != CPI->getCatchSwitch()->getUnwindDest(), 3000296417Sdim "Catchswitch cannot unwind to one of its catchpads", 3001296417Sdim CPI->getCatchSwitch(), CPI); 3002296417Sdim return; 3003296417Sdim } 3004296417Sdim 3005296417Sdim // Verify that each pred has a legal terminator with a legal to/from EH 3006296417Sdim // pad relationship. 3007296417Sdim Instruction *ToPad = &I; 3008296417Sdim Value *ToPadParent = getParentPad(ToPad); 3009296417Sdim for (BasicBlock *PredBB : predecessors(BB)) { 3010296417Sdim TerminatorInst *TI = PredBB->getTerminator(); 3011296417Sdim Value *FromPad; 3012296417Sdim if (auto *II = dyn_cast<InvokeInst>(TI)) { 3013296417Sdim Assert(II->getUnwindDest() == BB && II->getNormalDest() != BB, 3014296417Sdim "EH pad must be jumped to via an unwind edge", ToPad, II); 3015296417Sdim if (auto Bundle = II->getOperandBundle(LLVMContext::OB_funclet)) 3016296417Sdim FromPad = Bundle->Inputs[0]; 3017296417Sdim else 3018296417Sdim FromPad = ConstantTokenNone::get(II->getContext()); 3019296417Sdim } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) { 3020296417Sdim FromPad = CRI->getCleanupPad(); 3021296417Sdim Assert(FromPad != ToPadParent, "A cleanupret must exit its cleanup", CRI); 3022296417Sdim } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) { 3023296417Sdim FromPad = CSI; 3024296417Sdim } else { 3025296417Sdim Assert(false, "EH pad must be jumped to via an unwind edge", ToPad, TI); 3026296417Sdim } 3027296417Sdim 3028296417Sdim // The edge may exit from zero or more nested pads. 3029296417Sdim for (;; FromPad = getParentPad(FromPad)) { 3030296417Sdim Assert(FromPad != ToPad, 3031296417Sdim "EH pad cannot handle exceptions raised within it", FromPad, TI); 3032296417Sdim if (FromPad == ToPadParent) { 3033296417Sdim // This is a legal unwind edge. 3034296417Sdim break; 3035296417Sdim } 3036296417Sdim Assert(!isa<ConstantTokenNone>(FromPad), 3037296417Sdim "A single unwind edge may only enter one EH pad", TI); 3038296417Sdim } 3039296417Sdim } 3040296417Sdim} 3041296417Sdim 3042249259Sdimvoid Verifier::visitLandingPadInst(LandingPadInst &LPI) { 3043249259Sdim // The landingpad instruction is ill-formed if it doesn't have any clauses and 3044249259Sdim // isn't a cleanup. 3045288943Sdim Assert(LPI.getNumClauses() > 0 || LPI.isCleanup(), 3046288943Sdim "LandingPadInst needs at least one clause or to be a cleanup.", &LPI); 3047249259Sdim 3048296417Sdim visitEHPadPredecessors(LPI); 3049296417Sdim 3050296417Sdim if (!LandingPadResultTy) 3051296417Sdim LandingPadResultTy = LPI.getType(); 3052296417Sdim else 3053296417Sdim Assert(LandingPadResultTy == LPI.getType(), 3054296417Sdim "The landingpad instruction should have a consistent result type " 3055296417Sdim "inside a function.", 3056288943Sdim &LPI); 3057249259Sdim 3058288943Sdim Function *F = LPI.getParent()->getParent(); 3059288943Sdim Assert(F->hasPersonalityFn(), 3060288943Sdim "LandingPadInst needs to be in a function with a personality.", &LPI); 3061288943Sdim 3062249259Sdim // The landingpad instruction must be the first non-PHI instruction in the 3063249259Sdim // block. 3064288943Sdim Assert(LPI.getParent()->getLandingPadInst() == &LPI, 3065288943Sdim "LandingPadInst not the first non-PHI instruction in the block.", 3066288943Sdim &LPI); 3067249259Sdim 3068249259Sdim for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) { 3069276479Sdim Constant *Clause = LPI.getClause(i); 3070249259Sdim if (LPI.isCatch(i)) { 3071288943Sdim Assert(isa<PointerType>(Clause->getType()), 3072288943Sdim "Catch operand does not have pointer type!", &LPI); 3073249259Sdim } else { 3074288943Sdim Assert(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI); 3075288943Sdim Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause), 3076288943Sdim "Filter operand is not an array of constants!", &LPI); 3077249259Sdim } 3078249259Sdim } 3079249259Sdim 3080249259Sdim visitInstruction(LPI); 3081249259Sdim} 3082249259Sdim 3083296417Sdimvoid Verifier::visitCatchPadInst(CatchPadInst &CPI) { 3084296417Sdim visitEHPadPredecessors(CPI); 3085296417Sdim 3086296417Sdim BasicBlock *BB = CPI.getParent(); 3087296417Sdim 3088296417Sdim Function *F = BB->getParent(); 3089296417Sdim Assert(F->hasPersonalityFn(), 3090296417Sdim "CatchPadInst needs to be in a function with a personality.", &CPI); 3091296417Sdim 3092296417Sdim Assert(isa<CatchSwitchInst>(CPI.getParentPad()), 3093296417Sdim "CatchPadInst needs to be directly nested in a CatchSwitchInst.", 3094296417Sdim CPI.getParentPad()); 3095296417Sdim 3096296417Sdim // The catchpad instruction must be the first non-PHI instruction in the 3097296417Sdim // block. 3098296417Sdim Assert(BB->getFirstNonPHI() == &CPI, 3099296417Sdim "CatchPadInst not the first non-PHI instruction in the block.", &CPI); 3100296417Sdim 3101296417Sdim visitFuncletPadInst(CPI); 3102296417Sdim} 3103296417Sdim 3104296417Sdimvoid Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) { 3105296417Sdim Assert(isa<CatchPadInst>(CatchReturn.getOperand(0)), 3106296417Sdim "CatchReturnInst needs to be provided a CatchPad", &CatchReturn, 3107296417Sdim CatchReturn.getOperand(0)); 3108296417Sdim 3109296417Sdim visitTerminatorInst(CatchReturn); 3110296417Sdim} 3111296417Sdim 3112296417Sdimvoid Verifier::visitCleanupPadInst(CleanupPadInst &CPI) { 3113296417Sdim visitEHPadPredecessors(CPI); 3114296417Sdim 3115296417Sdim BasicBlock *BB = CPI.getParent(); 3116296417Sdim 3117296417Sdim Function *F = BB->getParent(); 3118296417Sdim Assert(F->hasPersonalityFn(), 3119296417Sdim "CleanupPadInst needs to be in a function with a personality.", &CPI); 3120296417Sdim 3121296417Sdim // The cleanuppad instruction must be the first non-PHI instruction in the 3122296417Sdim // block. 3123296417Sdim Assert(BB->getFirstNonPHI() == &CPI, 3124296417Sdim "CleanupPadInst not the first non-PHI instruction in the block.", 3125296417Sdim &CPI); 3126296417Sdim 3127296417Sdim auto *ParentPad = CPI.getParentPad(); 3128296417Sdim Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad), 3129296417Sdim "CleanupPadInst has an invalid parent.", &CPI); 3130296417Sdim 3131296417Sdim visitFuncletPadInst(CPI); 3132296417Sdim} 3133296417Sdim 3134296417Sdimvoid Verifier::visitFuncletPadInst(FuncletPadInst &FPI) { 3135296417Sdim User *FirstUser = nullptr; 3136296417Sdim Value *FirstUnwindPad = nullptr; 3137296417Sdim SmallVector<FuncletPadInst *, 8> Worklist({&FPI}); 3138296417Sdim while (!Worklist.empty()) { 3139296417Sdim FuncletPadInst *CurrentPad = Worklist.pop_back_val(); 3140296417Sdim Value *UnresolvedAncestorPad = nullptr; 3141296417Sdim for (User *U : CurrentPad->users()) { 3142296417Sdim BasicBlock *UnwindDest; 3143296417Sdim if (auto *CRI = dyn_cast<CleanupReturnInst>(U)) { 3144296417Sdim UnwindDest = CRI->getUnwindDest(); 3145296417Sdim } else if (auto *CSI = dyn_cast<CatchSwitchInst>(U)) { 3146296417Sdim // We allow catchswitch unwind to caller to nest 3147296417Sdim // within an outer pad that unwinds somewhere else, 3148296417Sdim // because catchswitch doesn't have a nounwind variant. 3149296417Sdim // See e.g. SimplifyCFGOpt::SimplifyUnreachable. 3150296417Sdim if (CSI->unwindsToCaller()) 3151296417Sdim continue; 3152296417Sdim UnwindDest = CSI->getUnwindDest(); 3153296417Sdim } else if (auto *II = dyn_cast<InvokeInst>(U)) { 3154296417Sdim UnwindDest = II->getUnwindDest(); 3155296417Sdim } else if (isa<CallInst>(U)) { 3156296417Sdim // Calls which don't unwind may be found inside funclet 3157296417Sdim // pads that unwind somewhere else. We don't *require* 3158296417Sdim // such calls to be annotated nounwind. 3159296417Sdim continue; 3160296417Sdim } else if (auto *CPI = dyn_cast<CleanupPadInst>(U)) { 3161296417Sdim // The unwind dest for a cleanup can only be found by 3162296417Sdim // recursive search. Add it to the worklist, and we'll 3163296417Sdim // search for its first use that determines where it unwinds. 3164296417Sdim Worklist.push_back(CPI); 3165296417Sdim continue; 3166296417Sdim } else { 3167296417Sdim Assert(isa<CatchReturnInst>(U), "Bogus funclet pad use", U); 3168296417Sdim continue; 3169296417Sdim } 3170296417Sdim 3171296417Sdim Value *UnwindPad; 3172296417Sdim bool ExitsFPI; 3173296417Sdim if (UnwindDest) { 3174296417Sdim UnwindPad = UnwindDest->getFirstNonPHI(); 3175296417Sdim Value *UnwindParent = getParentPad(UnwindPad); 3176296417Sdim // Ignore unwind edges that don't exit CurrentPad. 3177296417Sdim if (UnwindParent == CurrentPad) 3178296417Sdim continue; 3179296417Sdim // Determine whether the original funclet pad is exited, 3180296417Sdim // and if we are scanning nested pads determine how many 3181296417Sdim // of them are exited so we can stop searching their 3182296417Sdim // children. 3183296417Sdim Value *ExitedPad = CurrentPad; 3184296417Sdim ExitsFPI = false; 3185296417Sdim do { 3186296417Sdim if (ExitedPad == &FPI) { 3187296417Sdim ExitsFPI = true; 3188296417Sdim // Now we can resolve any ancestors of CurrentPad up to 3189296417Sdim // FPI, but not including FPI since we need to make sure 3190296417Sdim // to check all direct users of FPI for consistency. 3191296417Sdim UnresolvedAncestorPad = &FPI; 3192296417Sdim break; 3193296417Sdim } 3194296417Sdim Value *ExitedParent = getParentPad(ExitedPad); 3195296417Sdim if (ExitedParent == UnwindParent) { 3196296417Sdim // ExitedPad is the ancestor-most pad which this unwind 3197296417Sdim // edge exits, so we can resolve up to it, meaning that 3198296417Sdim // ExitedParent is the first ancestor still unresolved. 3199296417Sdim UnresolvedAncestorPad = ExitedParent; 3200296417Sdim break; 3201296417Sdim } 3202296417Sdim ExitedPad = ExitedParent; 3203296417Sdim } while (!isa<ConstantTokenNone>(ExitedPad)); 3204296417Sdim } else { 3205296417Sdim // Unwinding to caller exits all pads. 3206296417Sdim UnwindPad = ConstantTokenNone::get(FPI.getContext()); 3207296417Sdim ExitsFPI = true; 3208296417Sdim UnresolvedAncestorPad = &FPI; 3209296417Sdim } 3210296417Sdim 3211296417Sdim if (ExitsFPI) { 3212296417Sdim // This unwind edge exits FPI. Make sure it agrees with other 3213296417Sdim // such edges. 3214296417Sdim if (FirstUser) { 3215296417Sdim Assert(UnwindPad == FirstUnwindPad, "Unwind edges out of a funclet " 3216296417Sdim "pad must have the same unwind " 3217296417Sdim "dest", 3218296417Sdim &FPI, U, FirstUser); 3219296417Sdim } else { 3220296417Sdim FirstUser = U; 3221296417Sdim FirstUnwindPad = UnwindPad; 3222296417Sdim // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds 3223296417Sdim if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) && 3224296417Sdim getParentPad(UnwindPad) == getParentPad(&FPI)) 3225296417Sdim SiblingFuncletInfo[&FPI] = cast<TerminatorInst>(U); 3226296417Sdim } 3227296417Sdim } 3228296417Sdim // Make sure we visit all uses of FPI, but for nested pads stop as 3229296417Sdim // soon as we know where they unwind to. 3230296417Sdim if (CurrentPad != &FPI) 3231296417Sdim break; 3232296417Sdim } 3233296417Sdim if (UnresolvedAncestorPad) { 3234296417Sdim if (CurrentPad == UnresolvedAncestorPad) { 3235296417Sdim // When CurrentPad is FPI itself, we don't mark it as resolved even if 3236296417Sdim // we've found an unwind edge that exits it, because we need to verify 3237296417Sdim // all direct uses of FPI. 3238296417Sdim assert(CurrentPad == &FPI); 3239296417Sdim continue; 3240296417Sdim } 3241296417Sdim // Pop off the worklist any nested pads that we've found an unwind 3242296417Sdim // destination for. The pads on the worklist are the uncles, 3243296417Sdim // great-uncles, etc. of CurrentPad. We've found an unwind destination 3244296417Sdim // for all ancestors of CurrentPad up to but not including 3245296417Sdim // UnresolvedAncestorPad. 3246296417Sdim Value *ResolvedPad = CurrentPad; 3247296417Sdim while (!Worklist.empty()) { 3248296417Sdim Value *UnclePad = Worklist.back(); 3249296417Sdim Value *AncestorPad = getParentPad(UnclePad); 3250296417Sdim // Walk ResolvedPad up the ancestor list until we either find the 3251296417Sdim // uncle's parent or the last resolved ancestor. 3252296417Sdim while (ResolvedPad != AncestorPad) { 3253296417Sdim Value *ResolvedParent = getParentPad(ResolvedPad); 3254296417Sdim if (ResolvedParent == UnresolvedAncestorPad) { 3255296417Sdim break; 3256296417Sdim } 3257296417Sdim ResolvedPad = ResolvedParent; 3258296417Sdim } 3259296417Sdim // If the resolved ancestor search didn't find the uncle's parent, 3260296417Sdim // then the uncle is not yet resolved. 3261296417Sdim if (ResolvedPad != AncestorPad) 3262296417Sdim break; 3263296417Sdim // This uncle is resolved, so pop it from the worklist. 3264296417Sdim Worklist.pop_back(); 3265296417Sdim } 3266296417Sdim } 3267296417Sdim } 3268296417Sdim 3269296417Sdim if (FirstUnwindPad) { 3270296417Sdim if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.getParentPad())) { 3271296417Sdim BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest(); 3272296417Sdim Value *SwitchUnwindPad; 3273296417Sdim if (SwitchUnwindDest) 3274296417Sdim SwitchUnwindPad = SwitchUnwindDest->getFirstNonPHI(); 3275296417Sdim else 3276296417Sdim SwitchUnwindPad = ConstantTokenNone::get(FPI.getContext()); 3277296417Sdim Assert(SwitchUnwindPad == FirstUnwindPad, 3278296417Sdim "Unwind edges out of a catch must have the same unwind dest as " 3279296417Sdim "the parent catchswitch", 3280296417Sdim &FPI, FirstUser, CatchSwitch); 3281296417Sdim } 3282296417Sdim } 3283296417Sdim 3284296417Sdim visitInstruction(FPI); 3285296417Sdim} 3286296417Sdim 3287296417Sdimvoid Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) { 3288296417Sdim visitEHPadPredecessors(CatchSwitch); 3289296417Sdim 3290296417Sdim BasicBlock *BB = CatchSwitch.getParent(); 3291296417Sdim 3292296417Sdim Function *F = BB->getParent(); 3293296417Sdim Assert(F->hasPersonalityFn(), 3294296417Sdim "CatchSwitchInst needs to be in a function with a personality.", 3295296417Sdim &CatchSwitch); 3296296417Sdim 3297296417Sdim // The catchswitch instruction must be the first non-PHI instruction in the 3298296417Sdim // block. 3299296417Sdim Assert(BB->getFirstNonPHI() == &CatchSwitch, 3300296417Sdim "CatchSwitchInst not the first non-PHI instruction in the block.", 3301296417Sdim &CatchSwitch); 3302296417Sdim 3303296417Sdim auto *ParentPad = CatchSwitch.getParentPad(); 3304296417Sdim Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad), 3305296417Sdim "CatchSwitchInst has an invalid parent.", ParentPad); 3306296417Sdim 3307296417Sdim if (BasicBlock *UnwindDest = CatchSwitch.getUnwindDest()) { 3308296417Sdim Instruction *I = UnwindDest->getFirstNonPHI(); 3309296417Sdim Assert(I->isEHPad() && !isa<LandingPadInst>(I), 3310296417Sdim "CatchSwitchInst must unwind to an EH block which is not a " 3311296417Sdim "landingpad.", 3312296417Sdim &CatchSwitch); 3313296417Sdim 3314296417Sdim // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds 3315296417Sdim if (getParentPad(I) == ParentPad) 3316296417Sdim SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch; 3317296417Sdim } 3318296417Sdim 3319296417Sdim Assert(CatchSwitch.getNumHandlers() != 0, 3320296417Sdim "CatchSwitchInst cannot have empty handler list", &CatchSwitch); 3321296417Sdim 3322296417Sdim for (BasicBlock *Handler : CatchSwitch.handlers()) { 3323296417Sdim Assert(isa<CatchPadInst>(Handler->getFirstNonPHI()), 3324296417Sdim "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler); 3325296417Sdim } 3326296417Sdim 3327296417Sdim visitTerminatorInst(CatchSwitch); 3328296417Sdim} 3329296417Sdim 3330296417Sdimvoid Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) { 3331296417Sdim Assert(isa<CleanupPadInst>(CRI.getOperand(0)), 3332296417Sdim "CleanupReturnInst needs to be provided a CleanupPad", &CRI, 3333296417Sdim CRI.getOperand(0)); 3334296417Sdim 3335296417Sdim if (BasicBlock *UnwindDest = CRI.getUnwindDest()) { 3336296417Sdim Instruction *I = UnwindDest->getFirstNonPHI(); 3337296417Sdim Assert(I->isEHPad() && !isa<LandingPadInst>(I), 3338296417Sdim "CleanupReturnInst must unwind to an EH block which is not a " 3339296417Sdim "landingpad.", 3340296417Sdim &CRI); 3341296417Sdim } 3342296417Sdim 3343296417Sdim visitTerminatorInst(CRI); 3344296417Sdim} 3345296417Sdim 3346249259Sdimvoid Verifier::verifyDominatesUse(Instruction &I, unsigned i) { 3347249259Sdim Instruction *Op = cast<Instruction>(I.getOperand(i)); 3348249259Sdim // If the we have an invalid invoke, don't try to compute the dominance. 3349249259Sdim // We already reject it in the invoke specific checks and the dominance 3350249259Sdim // computation doesn't handle multiple edges. 3351249259Sdim if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) { 3352249259Sdim if (II->getNormalDest() == II->getUnwindDest()) 3353249259Sdim return; 3354249259Sdim } 3355249259Sdim 3356249259Sdim const Use &U = I.getOperandUse(i); 3357288943Sdim Assert(InstsInThisBlock.count(Op) || DT.dominates(Op, U), 3358288943Sdim "Instruction does not dominate all uses!", Op, &I); 3359249259Sdim} 3360249259Sdim 3361296417Sdimvoid Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) { 3362296417Sdim Assert(I.getType()->isPointerTy(), "dereferenceable, dereferenceable_or_null " 3363296417Sdim "apply only to pointer types", &I); 3364296417Sdim Assert(isa<LoadInst>(I), 3365296417Sdim "dereferenceable, dereferenceable_or_null apply only to load" 3366296417Sdim " instructions, use attributes for calls or invokes", &I); 3367296417Sdim Assert(MD->getNumOperands() == 1, "dereferenceable, dereferenceable_or_null " 3368296417Sdim "take one operand!", &I); 3369296417Sdim ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0)); 3370296417Sdim Assert(CI && CI->getType()->isIntegerTy(64), "dereferenceable, " 3371296417Sdim "dereferenceable_or_null metadata value must be an i64!", &I); 3372296417Sdim} 3373296417Sdim 3374249259Sdim/// verifyInstruction - Verify that an instruction is well formed. 3375249259Sdim/// 3376249259Sdimvoid Verifier::visitInstruction(Instruction &I) { 3377249259Sdim BasicBlock *BB = I.getParent(); 3378288943Sdim Assert(BB, "Instruction not embedded in basic block!", &I); 3379249259Sdim 3380249259Sdim if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential 3381276479Sdim for (User *U : I.users()) { 3382288943Sdim Assert(U != (User *)&I || !DT.isReachableFromEntry(BB), 3383288943Sdim "Only PHI nodes may reference their own value!", &I); 3384276479Sdim } 3385249259Sdim } 3386249259Sdim 3387249259Sdim // Check that void typed values don't have names 3388288943Sdim Assert(!I.getType()->isVoidTy() || !I.hasName(), 3389288943Sdim "Instruction has a name, but provides a void value!", &I); 3390249259Sdim 3391249259Sdim // Check that the return value of the instruction is either void or a legal 3392249259Sdim // value type. 3393288943Sdim Assert(I.getType()->isVoidTy() || I.getType()->isFirstClassType(), 3394288943Sdim "Instruction returns a non-scalar type!", &I); 3395249259Sdim 3396249259Sdim // Check that the instruction doesn't produce metadata. Calls are already 3397249259Sdim // checked against the callee type. 3398288943Sdim Assert(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I), 3399288943Sdim "Invalid use of metadata!", &I); 3400249259Sdim 3401249259Sdim // Check that all uses of the instruction, if they are instructions 3402249259Sdim // themselves, actually have parent basic blocks. If the use is not an 3403249259Sdim // instruction, it is an error! 3404276479Sdim for (Use &U : I.uses()) { 3405276479Sdim if (Instruction *Used = dyn_cast<Instruction>(U.getUser())) 3406288943Sdim Assert(Used->getParent() != nullptr, 3407288943Sdim "Instruction referencing" 3408288943Sdim " instruction not embedded in a basic block!", 3409288943Sdim &I, Used); 3410249259Sdim else { 3411276479Sdim CheckFailed("Use of instruction is not an instruction!", U); 3412249259Sdim return; 3413249259Sdim } 3414249259Sdim } 3415249259Sdim 3416249259Sdim for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) { 3417288943Sdim Assert(I.getOperand(i) != nullptr, "Instruction has null operand!", &I); 3418249259Sdim 3419249259Sdim // Check to make sure that only first-class-values are operands to 3420249259Sdim // instructions. 3421249259Sdim if (!I.getOperand(i)->getType()->isFirstClassType()) { 3422288943Sdim Assert(0, "Instruction operands must be first-class values!", &I); 3423249259Sdim } 3424249259Sdim 3425249259Sdim if (Function *F = dyn_cast<Function>(I.getOperand(i))) { 3426249259Sdim // Check to make sure that the "address of" an intrinsic function is never 3427249259Sdim // taken. 3428288943Sdim Assert( 3429288943Sdim !F->isIntrinsic() || 3430288943Sdim i == (isa<CallInst>(I) ? e - 1 : isa<InvokeInst>(I) ? e - 3 : 0), 3431288943Sdim "Cannot take the address of an intrinsic!", &I); 3432288943Sdim Assert( 3433288943Sdim !F->isIntrinsic() || isa<CallInst>(I) || 3434280031Sdim F->getIntrinsicID() == Intrinsic::donothing || 3435280031Sdim F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void || 3436288943Sdim F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 || 3437288943Sdim F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint, 3438288943Sdim "Cannot invoke an intrinsinc other than" 3439288943Sdim " donothing or patchpoint", 3440288943Sdim &I); 3441288943Sdim Assert(F->getParent() == M, "Referencing function in another module!", 3442296417Sdim &I, M, F, F->getParent()); 3443249259Sdim } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) { 3444288943Sdim Assert(OpBB->getParent() == BB->getParent(), 3445288943Sdim "Referring to a basic block in another function!", &I); 3446249259Sdim } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) { 3447288943Sdim Assert(OpArg->getParent() == BB->getParent(), 3448288943Sdim "Referring to an argument in another function!", &I); 3449249259Sdim } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) { 3450296417Sdim Assert(GV->getParent() == M, "Referencing global in another module!", &I, M, GV, GV->getParent()); 3451249259Sdim } else if (isa<Instruction>(I.getOperand(i))) { 3452249259Sdim verifyDominatesUse(I, i); 3453249259Sdim } else if (isa<InlineAsm>(I.getOperand(i))) { 3454288943Sdim Assert((i + 1 == e && isa<CallInst>(I)) || 3455288943Sdim (i + 3 == e && isa<InvokeInst>(I)), 3456288943Sdim "Cannot take the address of an inline asm!", &I); 3457261991Sdim } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) { 3458261991Sdim if (CE->getType()->isPtrOrPtrVectorTy()) { 3459261991Sdim // If we have a ConstantExpr pointer, we need to see if it came from an 3460261991Sdim // illegal bitcast (inttoptr <constant int> ) 3461296417Sdim visitConstantExprsRecursively(CE); 3462261991Sdim } 3463249259Sdim } 3464249259Sdim } 3465249259Sdim 3466249259Sdim if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) { 3467288943Sdim Assert(I.getType()->isFPOrFPVectorTy(), 3468288943Sdim "fpmath requires a floating point result!", &I); 3469288943Sdim Assert(MD->getNumOperands() == 1, "fpmath takes one operand!", &I); 3470280031Sdim if (ConstantFP *CFP0 = 3471280031Sdim mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) { 3472249259Sdim APFloat Accuracy = CFP0->getValueAPF(); 3473288943Sdim Assert(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(), 3474288943Sdim "fpmath accuracy not a positive number!", &I); 3475249259Sdim } else { 3476288943Sdim Assert(false, "invalid fpmath accuracy!", &I); 3477249259Sdim } 3478249259Sdim } 3479249259Sdim 3480280031Sdim if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) { 3481288943Sdim Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I), 3482288943Sdim "Ranges are only for loads, calls and invokes!", &I); 3483280031Sdim visitRangeMetadata(I, Range, I.getType()); 3484280031Sdim } 3485249259Sdim 3486280031Sdim if (I.getMetadata(LLVMContext::MD_nonnull)) { 3487288943Sdim Assert(I.getType()->isPointerTy(), "nonnull applies only to pointer types", 3488288943Sdim &I); 3489288943Sdim Assert(isa<LoadInst>(I), 3490288943Sdim "nonnull applies only to load instructions, use attributes" 3491288943Sdim " for calls or invokes", 3492288943Sdim &I); 3493280031Sdim } 3494280031Sdim 3495296417Sdim if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable)) 3496296417Sdim visitDereferenceableMetadata(I, MD); 3497296417Sdim 3498296417Sdim if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable_or_null)) 3499296417Sdim visitDereferenceableMetadata(I, MD); 3500296417Sdim 3501296417Sdim if (MDNode *AlignMD = I.getMetadata(LLVMContext::MD_align)) { 3502296417Sdim Assert(I.getType()->isPointerTy(), "align applies only to pointer types", 3503296417Sdim &I); 3504296417Sdim Assert(isa<LoadInst>(I), "align applies only to load instructions, " 3505296417Sdim "use attributes for calls or invokes", &I); 3506296417Sdim Assert(AlignMD->getNumOperands() == 1, "align takes one operand!", &I); 3507296417Sdim ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0)); 3508296417Sdim Assert(CI && CI->getType()->isIntegerTy(64), 3509296417Sdim "align metadata value must be an i64!", &I); 3510296417Sdim uint64_t Align = CI->getZExtValue(); 3511296417Sdim Assert(isPowerOf2_64(Align), 3512296417Sdim "align metadata value must be a power of 2!", &I); 3513296417Sdim Assert(Align <= Value::MaximumAlignment, 3514296417Sdim "alignment is larger that implementation defined limit", &I); 3515296417Sdim } 3516296417Sdim 3517288943Sdim if (MDNode *N = I.getDebugLoc().getAsMDNode()) { 3518288943Sdim Assert(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N); 3519288943Sdim visitMDNode(*N); 3520288943Sdim } 3521288943Sdim 3522249259Sdim InstsInThisBlock.insert(&I); 3523249259Sdim} 3524249259Sdim 3525249259Sdim/// VerifyIntrinsicType - Verify that the specified type (which comes from an 3526249259Sdim/// intrinsic argument or return value) matches the type constraints specified 3527249259Sdim/// by the .td file (e.g. an "any integer" argument really is an integer). 3528249259Sdim/// 3529249259Sdim/// This return true on error but does not print a message. 3530249259Sdimbool Verifier::VerifyIntrinsicType(Type *Ty, 3531249259Sdim ArrayRef<Intrinsic::IITDescriptor> &Infos, 3532249259Sdim SmallVectorImpl<Type*> &ArgTys) { 3533249259Sdim using namespace Intrinsic; 3534249259Sdim 3535249259Sdim // If we ran out of descriptors, there are too many arguments. 3536261991Sdim if (Infos.empty()) return true; 3537249259Sdim IITDescriptor D = Infos.front(); 3538249259Sdim Infos = Infos.slice(1); 3539261991Sdim 3540249259Sdim switch (D.Kind) { 3541249259Sdim case IITDescriptor::Void: return !Ty->isVoidTy(); 3542261991Sdim case IITDescriptor::VarArg: return true; 3543249259Sdim case IITDescriptor::MMX: return !Ty->isX86_MMXTy(); 3544296417Sdim case IITDescriptor::Token: return !Ty->isTokenTy(); 3545249259Sdim case IITDescriptor::Metadata: return !Ty->isMetadataTy(); 3546249259Sdim case IITDescriptor::Half: return !Ty->isHalfTy(); 3547249259Sdim case IITDescriptor::Float: return !Ty->isFloatTy(); 3548249259Sdim case IITDescriptor::Double: return !Ty->isDoubleTy(); 3549249259Sdim case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width); 3550249259Sdim case IITDescriptor::Vector: { 3551249259Sdim VectorType *VT = dyn_cast<VectorType>(Ty); 3552276479Sdim return !VT || VT->getNumElements() != D.Vector_Width || 3553249259Sdim VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys); 3554249259Sdim } 3555249259Sdim case IITDescriptor::Pointer: { 3556249259Sdim PointerType *PT = dyn_cast<PointerType>(Ty); 3557276479Sdim return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace || 3558249259Sdim VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys); 3559249259Sdim } 3560261991Sdim 3561249259Sdim case IITDescriptor::Struct: { 3562249259Sdim StructType *ST = dyn_cast<StructType>(Ty); 3563276479Sdim if (!ST || ST->getNumElements() != D.Struct_NumElements) 3564249259Sdim return true; 3565261991Sdim 3566249259Sdim for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i) 3567249259Sdim if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys)) 3568249259Sdim return true; 3569249259Sdim return false; 3570249259Sdim } 3571261991Sdim 3572249259Sdim case IITDescriptor::Argument: 3573249259Sdim // Two cases here - If this is the second occurrence of an argument, verify 3574261991Sdim // that the later instance matches the previous instance. 3575249259Sdim if (D.getArgumentNumber() < ArgTys.size()) 3576261991Sdim return Ty != ArgTys[D.getArgumentNumber()]; 3577261991Sdim 3578249259Sdim // Otherwise, if this is the first instance of an argument, record it and 3579249259Sdim // verify the "Any" kind. 3580249259Sdim assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error"); 3581249259Sdim ArgTys.push_back(Ty); 3582261991Sdim 3583249259Sdim switch (D.getArgumentKind()) { 3584288943Sdim case IITDescriptor::AK_Any: return false; // Success 3585249259Sdim case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy(); 3586249259Sdim case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy(); 3587249259Sdim case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty); 3588249259Sdim case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty); 3589249259Sdim } 3590249259Sdim llvm_unreachable("all argument kinds not covered"); 3591261991Sdim 3592276479Sdim case IITDescriptor::ExtendArgument: { 3593249259Sdim // This may only be used when referring to a previous vector argument. 3594276479Sdim if (D.getArgumentNumber() >= ArgTys.size()) 3595276479Sdim return true; 3596249259Sdim 3597276479Sdim Type *NewTy = ArgTys[D.getArgumentNumber()]; 3598276479Sdim if (VectorType *VTy = dyn_cast<VectorType>(NewTy)) 3599276479Sdim NewTy = VectorType::getExtendedElementVectorType(VTy); 3600276479Sdim else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy)) 3601276479Sdim NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth()); 3602276479Sdim else 3603276479Sdim return true; 3604276479Sdim 3605276479Sdim return Ty != NewTy; 3606276479Sdim } 3607276479Sdim case IITDescriptor::TruncArgument: { 3608249259Sdim // This may only be used when referring to a previous vector argument. 3609276479Sdim if (D.getArgumentNumber() >= ArgTys.size()) 3610276479Sdim return true; 3611276479Sdim 3612276479Sdim Type *NewTy = ArgTys[D.getArgumentNumber()]; 3613276479Sdim if (VectorType *VTy = dyn_cast<VectorType>(NewTy)) 3614276479Sdim NewTy = VectorType::getTruncatedElementVectorType(VTy); 3615276479Sdim else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy)) 3616276479Sdim NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2); 3617276479Sdim else 3618276479Sdim return true; 3619276479Sdim 3620276479Sdim return Ty != NewTy; 3621276479Sdim } 3622276479Sdim case IITDescriptor::HalfVecArgument: 3623276479Sdim // This may only be used when referring to a previous vector argument. 3624249259Sdim return D.getArgumentNumber() >= ArgTys.size() || 3625249259Sdim !isa<VectorType>(ArgTys[D.getArgumentNumber()]) || 3626276479Sdim VectorType::getHalfElementsVectorType( 3627249259Sdim cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty; 3628280031Sdim case IITDescriptor::SameVecWidthArgument: { 3629280031Sdim if (D.getArgumentNumber() >= ArgTys.size()) 3630280031Sdim return true; 3631280031Sdim VectorType * ReferenceType = 3632280031Sdim dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]); 3633280031Sdim VectorType *ThisArgType = dyn_cast<VectorType>(Ty); 3634280031Sdim if (!ThisArgType || !ReferenceType || 3635280031Sdim (ReferenceType->getVectorNumElements() != 3636280031Sdim ThisArgType->getVectorNumElements())) 3637280031Sdim return true; 3638280031Sdim return VerifyIntrinsicType(ThisArgType->getVectorElementType(), 3639280031Sdim Infos, ArgTys); 3640249259Sdim } 3641280031Sdim case IITDescriptor::PtrToArgument: { 3642280031Sdim if (D.getArgumentNumber() >= ArgTys.size()) 3643280031Sdim return true; 3644280031Sdim Type * ReferenceType = ArgTys[D.getArgumentNumber()]; 3645280031Sdim PointerType *ThisArgType = dyn_cast<PointerType>(Ty); 3646280031Sdim return (!ThisArgType || ThisArgType->getElementType() != ReferenceType); 3647280031Sdim } 3648288943Sdim case IITDescriptor::VecOfPtrsToElt: { 3649288943Sdim if (D.getArgumentNumber() >= ArgTys.size()) 3650288943Sdim return true; 3651288943Sdim VectorType * ReferenceType = 3652288943Sdim dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]); 3653288943Sdim VectorType *ThisArgVecTy = dyn_cast<VectorType>(Ty); 3654288943Sdim if (!ThisArgVecTy || !ReferenceType || 3655288943Sdim (ReferenceType->getVectorNumElements() != 3656288943Sdim ThisArgVecTy->getVectorNumElements())) 3657288943Sdim return true; 3658288943Sdim PointerType *ThisArgEltTy = 3659288943Sdim dyn_cast<PointerType>(ThisArgVecTy->getVectorElementType()); 3660288943Sdim if (!ThisArgEltTy) 3661288943Sdim return true; 3662288943Sdim return ThisArgEltTy->getElementType() != 3663288943Sdim ReferenceType->getVectorElementType(); 3664280031Sdim } 3665288943Sdim } 3666249259Sdim llvm_unreachable("unhandled"); 3667249259Sdim} 3668249259Sdim 3669261991Sdim/// \brief Verify if the intrinsic has variable arguments. 3670261991Sdim/// This method is intended to be called after all the fixed arguments have been 3671261991Sdim/// verified first. 3672261991Sdim/// 3673261991Sdim/// This method returns true on error and does not print an error message. 3674261991Sdimbool 3675261991SdimVerifier::VerifyIntrinsicIsVarArg(bool isVarArg, 3676261991Sdim ArrayRef<Intrinsic::IITDescriptor> &Infos) { 3677261991Sdim using namespace Intrinsic; 3678261991Sdim 3679261991Sdim // If there are no descriptors left, then it can't be a vararg. 3680261991Sdim if (Infos.empty()) 3681288943Sdim return isVarArg; 3682261991Sdim 3683261991Sdim // There should be only one descriptor remaining at this point. 3684261991Sdim if (Infos.size() != 1) 3685261991Sdim return true; 3686261991Sdim 3687261991Sdim // Check and verify the descriptor. 3688261991Sdim IITDescriptor D = Infos.front(); 3689261991Sdim Infos = Infos.slice(1); 3690261991Sdim if (D.Kind == IITDescriptor::VarArg) 3691288943Sdim return !isVarArg; 3692261991Sdim 3693261991Sdim return true; 3694261991Sdim} 3695261991Sdim 3696288943Sdim/// Allow intrinsics to be verified in different ways. 3697288943Sdimvoid Verifier::visitIntrinsicCallSite(Intrinsic::ID ID, CallSite CS) { 3698288943Sdim Function *IF = CS.getCalledFunction(); 3699288943Sdim Assert(IF->isDeclaration(), "Intrinsic functions should never be defined!", 3700288943Sdim IF); 3701249259Sdim 3702249259Sdim // Verify that the intrinsic prototype lines up with what the .td files 3703249259Sdim // describe. 3704249259Sdim FunctionType *IFTy = IF->getFunctionType(); 3705261991Sdim bool IsVarArg = IFTy->isVarArg(); 3706261991Sdim 3707249259Sdim SmallVector<Intrinsic::IITDescriptor, 8> Table; 3708249259Sdim getIntrinsicInfoTableEntries(ID, Table); 3709249259Sdim ArrayRef<Intrinsic::IITDescriptor> TableRef = Table; 3710249259Sdim 3711249259Sdim SmallVector<Type *, 4> ArgTys; 3712288943Sdim Assert(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys), 3713288943Sdim "Intrinsic has incorrect return type!", IF); 3714249259Sdim for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i) 3715288943Sdim Assert(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys), 3716288943Sdim "Intrinsic has incorrect argument type!", IF); 3717261991Sdim 3718261991Sdim // Verify if the intrinsic call matches the vararg property. 3719261991Sdim if (IsVarArg) 3720288943Sdim Assert(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef), 3721288943Sdim "Intrinsic was not defined with variable arguments!", IF); 3722261991Sdim else 3723288943Sdim Assert(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef), 3724288943Sdim "Callsite was not defined with variable arguments!", IF); 3725261991Sdim 3726261991Sdim // All descriptors should be absorbed by now. 3727288943Sdim Assert(TableRef.empty(), "Intrinsic has too few arguments!", IF); 3728249259Sdim 3729249259Sdim // Now that we have the intrinsic ID and the actual argument types (and we 3730249259Sdim // know they are legal for the intrinsic!) get the intrinsic name through the 3731249259Sdim // usual means. This allows us to verify the mangling of argument types into 3732249259Sdim // the name. 3733276479Sdim const std::string ExpectedName = Intrinsic::getName(ID, ArgTys); 3734288943Sdim Assert(ExpectedName == IF->getName(), 3735288943Sdim "Intrinsic name not mangled correctly for type arguments! " 3736288943Sdim "Should be: " + 3737288943Sdim ExpectedName, 3738288943Sdim IF); 3739261991Sdim 3740249259Sdim // If the intrinsic takes MDNode arguments, verify that they are either global 3741249259Sdim // or are local to *this* function. 3742288943Sdim for (Value *V : CS.args()) 3743288943Sdim if (auto *MD = dyn_cast<MetadataAsValue>(V)) 3744288943Sdim visitMetadataAsValue(*MD, CS.getCaller()); 3745249259Sdim 3746249259Sdim switch (ID) { 3747249259Sdim default: 3748249259Sdim break; 3749249259Sdim case Intrinsic::ctlz: // llvm.ctlz 3750249259Sdim case Intrinsic::cttz: // llvm.cttz 3751288943Sdim Assert(isa<ConstantInt>(CS.getArgOperand(1)), 3752288943Sdim "is_zero_undef argument of bit counting intrinsics must be a " 3753288943Sdim "constant int", 3754288943Sdim CS); 3755249259Sdim break; 3756288943Sdim case Intrinsic::dbg_declare: // llvm.dbg.declare 3757288943Sdim Assert(isa<MetadataAsValue>(CS.getArgOperand(0)), 3758288943Sdim "invalid llvm.dbg.declare intrinsic call 1", CS); 3759288943Sdim visitDbgIntrinsic("declare", cast<DbgDeclareInst>(*CS.getInstruction())); 3760288943Sdim break; 3761288943Sdim case Intrinsic::dbg_value: // llvm.dbg.value 3762288943Sdim visitDbgIntrinsic("value", cast<DbgValueInst>(*CS.getInstruction())); 3763288943Sdim break; 3764249259Sdim case Intrinsic::memcpy: 3765249259Sdim case Intrinsic::memmove: 3766288943Sdim case Intrinsic::memset: { 3767288943Sdim ConstantInt *AlignCI = dyn_cast<ConstantInt>(CS.getArgOperand(3)); 3768288943Sdim Assert(AlignCI, 3769288943Sdim "alignment argument of memory intrinsics must be a constant int", 3770288943Sdim CS); 3771288943Sdim const APInt &AlignVal = AlignCI->getValue(); 3772288943Sdim Assert(AlignCI->isZero() || AlignVal.isPowerOf2(), 3773288943Sdim "alignment argument of memory intrinsics must be a power of 2", CS); 3774288943Sdim Assert(isa<ConstantInt>(CS.getArgOperand(4)), 3775288943Sdim "isvolatile argument of memory intrinsics must be a constant int", 3776288943Sdim CS); 3777249259Sdim break; 3778288943Sdim } 3779249259Sdim case Intrinsic::gcroot: 3780249259Sdim case Intrinsic::gcwrite: 3781249259Sdim case Intrinsic::gcread: 3782249259Sdim if (ID == Intrinsic::gcroot) { 3783249259Sdim AllocaInst *AI = 3784288943Sdim dyn_cast<AllocaInst>(CS.getArgOperand(0)->stripPointerCasts()); 3785288943Sdim Assert(AI, "llvm.gcroot parameter #1 must be an alloca.", CS); 3786288943Sdim Assert(isa<Constant>(CS.getArgOperand(1)), 3787288943Sdim "llvm.gcroot parameter #2 must be a constant.", CS); 3788288943Sdim if (!AI->getAllocatedType()->isPointerTy()) { 3789288943Sdim Assert(!isa<ConstantPointerNull>(CS.getArgOperand(1)), 3790288943Sdim "llvm.gcroot parameter #1 must either be a pointer alloca, " 3791288943Sdim "or argument #2 must be a non-null constant.", 3792288943Sdim CS); 3793249259Sdim } 3794249259Sdim } 3795249259Sdim 3796288943Sdim Assert(CS.getParent()->getParent()->hasGC(), 3797288943Sdim "Enclosing function does not use GC.", CS); 3798249259Sdim break; 3799249259Sdim case Intrinsic::init_trampoline: 3800288943Sdim Assert(isa<Function>(CS.getArgOperand(1)->stripPointerCasts()), 3801288943Sdim "llvm.init_trampoline parameter #2 must resolve to a function.", 3802288943Sdim CS); 3803249259Sdim break; 3804249259Sdim case Intrinsic::prefetch: 3805288943Sdim Assert(isa<ConstantInt>(CS.getArgOperand(1)) && 3806288943Sdim isa<ConstantInt>(CS.getArgOperand(2)) && 3807288943Sdim cast<ConstantInt>(CS.getArgOperand(1))->getZExtValue() < 2 && 3808288943Sdim cast<ConstantInt>(CS.getArgOperand(2))->getZExtValue() < 4, 3809288943Sdim "invalid arguments to llvm.prefetch", CS); 3810249259Sdim break; 3811249259Sdim case Intrinsic::stackprotector: 3812288943Sdim Assert(isa<AllocaInst>(CS.getArgOperand(1)->stripPointerCasts()), 3813288943Sdim "llvm.stackprotector parameter #2 must resolve to an alloca.", CS); 3814249259Sdim break; 3815249259Sdim case Intrinsic::lifetime_start: 3816249259Sdim case Intrinsic::lifetime_end: 3817249259Sdim case Intrinsic::invariant_start: 3818288943Sdim Assert(isa<ConstantInt>(CS.getArgOperand(0)), 3819288943Sdim "size argument of memory use markers must be a constant integer", 3820288943Sdim CS); 3821249259Sdim break; 3822249259Sdim case Intrinsic::invariant_end: 3823288943Sdim Assert(isa<ConstantInt>(CS.getArgOperand(1)), 3824288943Sdim "llvm.invariant.end parameter #2 must be a constant integer", CS); 3825249259Sdim break; 3826280031Sdim 3827288943Sdim case Intrinsic::localescape: { 3828288943Sdim BasicBlock *BB = CS.getParent(); 3829288943Sdim Assert(BB == &BB->getParent()->front(), 3830288943Sdim "llvm.localescape used outside of entry block", CS); 3831288943Sdim Assert(!SawFrameEscape, 3832288943Sdim "multiple calls to llvm.localescape in one function", CS); 3833288943Sdim for (Value *Arg : CS.args()) { 3834288943Sdim if (isa<ConstantPointerNull>(Arg)) 3835288943Sdim continue; // Null values are allowed as placeholders. 3836288943Sdim auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts()); 3837288943Sdim Assert(AI && AI->isStaticAlloca(), 3838288943Sdim "llvm.localescape only accepts static allocas", CS); 3839288943Sdim } 3840288943Sdim FrameEscapeInfo[BB->getParent()].first = CS.getNumArgOperands(); 3841288943Sdim SawFrameEscape = true; 3842280031Sdim break; 3843249259Sdim } 3844288943Sdim case Intrinsic::localrecover: { 3845288943Sdim Value *FnArg = CS.getArgOperand(0)->stripPointerCasts(); 3846280031Sdim Function *Fn = dyn_cast<Function>(FnArg); 3847288943Sdim Assert(Fn && !Fn->isDeclaration(), 3848288943Sdim "llvm.localrecover first " 3849288943Sdim "argument must be function defined in this module", 3850288943Sdim CS); 3851288943Sdim auto *IdxArg = dyn_cast<ConstantInt>(CS.getArgOperand(2)); 3852288943Sdim Assert(IdxArg, "idx argument of llvm.localrecover must be a constant int", 3853288943Sdim CS); 3854288943Sdim auto &Entry = FrameEscapeInfo[Fn]; 3855288943Sdim Entry.second = unsigned( 3856288943Sdim std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1)); 3857280031Sdim break; 3858280031Sdim } 3859280031Sdim 3860288943Sdim case Intrinsic::experimental_gc_statepoint: 3861288943Sdim Assert(!CS.isInlineAsm(), 3862288943Sdim "gc.statepoint support for inline assembly unimplemented", CS); 3863288943Sdim Assert(CS.getParent()->getParent()->hasGC(), 3864288943Sdim "Enclosing function does not use GC.", CS); 3865280031Sdim 3866288943Sdim VerifyStatepoint(CS); 3867280031Sdim break; 3868288943Sdim case Intrinsic::experimental_gc_result: { 3869288943Sdim Assert(CS.getParent()->getParent()->hasGC(), 3870288943Sdim "Enclosing function does not use GC.", CS); 3871280031Sdim // Are we tied to a statepoint properly? 3872288943Sdim CallSite StatepointCS(CS.getArgOperand(0)); 3873280031Sdim const Function *StatepointFn = 3874280031Sdim StatepointCS.getInstruction() ? StatepointCS.getCalledFunction() : nullptr; 3875288943Sdim Assert(StatepointFn && StatepointFn->isDeclaration() && 3876288943Sdim StatepointFn->getIntrinsicID() == 3877288943Sdim Intrinsic::experimental_gc_statepoint, 3878288943Sdim "gc.result operand #1 must be from a statepoint", CS, 3879288943Sdim CS.getArgOperand(0)); 3880280031Sdim 3881280031Sdim // Assert that result type matches wrapped callee. 3882288943Sdim const Value *Target = StatepointCS.getArgument(2); 3883296417Sdim auto *PT = cast<PointerType>(Target->getType()); 3884296417Sdim auto *TargetFuncType = cast<FunctionType>(PT->getElementType()); 3885288943Sdim Assert(CS.getType() == TargetFuncType->getReturnType(), 3886288943Sdim "gc.result result type does not match wrapped callee", CS); 3887280031Sdim break; 3888280031Sdim } 3889280031Sdim case Intrinsic::experimental_gc_relocate: { 3890288943Sdim Assert(CS.getNumArgOperands() == 3, "wrong number of arguments", CS); 3891280031Sdim 3892296417Sdim Assert(isa<PointerType>(CS.getType()->getScalarType()), 3893296417Sdim "gc.relocate must return a pointer or a vector of pointers", CS); 3894296417Sdim 3895288943Sdim // Check that this relocate is correctly tied to the statepoint 3896288943Sdim 3897288943Sdim // This is case for relocate on the unwinding path of an invoke statepoint 3898296417Sdim if (LandingPadInst *LandingPad = 3899296417Sdim dyn_cast<LandingPadInst>(CS.getArgOperand(0))) { 3900288943Sdim 3901288943Sdim const BasicBlock *InvokeBB = 3902296417Sdim LandingPad->getParent()->getUniquePredecessor(); 3903288943Sdim 3904288943Sdim // Landingpad relocates should have only one predecessor with invoke 3905288943Sdim // statepoint terminator 3906288943Sdim Assert(InvokeBB, "safepoints should have unique landingpads", 3907296417Sdim LandingPad->getParent()); 3908288943Sdim Assert(InvokeBB->getTerminator(), "safepoint block should be well formed", 3909288943Sdim InvokeBB); 3910288943Sdim Assert(isStatepoint(InvokeBB->getTerminator()), 3911288943Sdim "gc relocate should be linked to a statepoint", InvokeBB); 3912288943Sdim } 3913288943Sdim else { 3914288943Sdim // In all other cases relocate should be tied to the statepoint directly. 3915288943Sdim // This covers relocates on a normal return path of invoke statepoint and 3916288943Sdim // relocates of a call statepoint 3917288943Sdim auto Token = CS.getArgOperand(0); 3918288943Sdim Assert(isa<Instruction>(Token) && isStatepoint(cast<Instruction>(Token)), 3919288943Sdim "gc relocate is incorrectly tied to the statepoint", CS, Token); 3920288943Sdim } 3921288943Sdim 3922288943Sdim // Verify rest of the relocate arguments 3923288943Sdim 3924296417Sdim ImmutableCallSite StatepointCS( 3925296417Sdim cast<GCRelocateInst>(*CS.getInstruction()).getStatepoint()); 3926288943Sdim 3927280031Sdim // Both the base and derived must be piped through the safepoint 3928288943Sdim Value* Base = CS.getArgOperand(1); 3929288943Sdim Assert(isa<ConstantInt>(Base), 3930288943Sdim "gc.relocate operand #2 must be integer offset", CS); 3931280031Sdim 3932288943Sdim Value* Derived = CS.getArgOperand(2); 3933288943Sdim Assert(isa<ConstantInt>(Derived), 3934288943Sdim "gc.relocate operand #3 must be integer offset", CS); 3935288943Sdim 3936280031Sdim const int BaseIndex = cast<ConstantInt>(Base)->getZExtValue(); 3937280031Sdim const int DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue(); 3938280031Sdim // Check the bounds 3939288943Sdim Assert(0 <= BaseIndex && BaseIndex < (int)StatepointCS.arg_size(), 3940288943Sdim "gc.relocate: statepoint base index out of bounds", CS); 3941288943Sdim Assert(0 <= DerivedIndex && DerivedIndex < (int)StatepointCS.arg_size(), 3942288943Sdim "gc.relocate: statepoint derived index out of bounds", CS); 3943280031Sdim 3944280031Sdim // Check that BaseIndex and DerivedIndex fall within the 'gc parameters' 3945280031Sdim // section of the statepoint's argument 3946288943Sdim Assert(StatepointCS.arg_size() > 0, 3947288943Sdim "gc.statepoint: insufficient arguments"); 3948288943Sdim Assert(isa<ConstantInt>(StatepointCS.getArgument(3)), 3949288943Sdim "gc.statement: number of call arguments must be constant integer"); 3950288943Sdim const unsigned NumCallArgs = 3951288943Sdim cast<ConstantInt>(StatepointCS.getArgument(3))->getZExtValue(); 3952288943Sdim Assert(StatepointCS.arg_size() > NumCallArgs + 5, 3953288943Sdim "gc.statepoint: mismatch in number of call arguments"); 3954288943Sdim Assert(isa<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 5)), 3955288943Sdim "gc.statepoint: number of transition arguments must be " 3956288943Sdim "a constant integer"); 3957288943Sdim const int NumTransitionArgs = 3958288943Sdim cast<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 5)) 3959288943Sdim ->getZExtValue(); 3960288943Sdim const int DeoptArgsStart = 4 + NumCallArgs + 1 + NumTransitionArgs + 1; 3961288943Sdim Assert(isa<ConstantInt>(StatepointCS.getArgument(DeoptArgsStart)), 3962288943Sdim "gc.statepoint: number of deoptimization arguments must be " 3963288943Sdim "a constant integer"); 3964280031Sdim const int NumDeoptArgs = 3965288943Sdim cast<ConstantInt>(StatepointCS.getArgument(DeoptArgsStart))->getZExtValue(); 3966288943Sdim const int GCParamArgsStart = DeoptArgsStart + 1 + NumDeoptArgs; 3967280031Sdim const int GCParamArgsEnd = StatepointCS.arg_size(); 3968288943Sdim Assert(GCParamArgsStart <= BaseIndex && BaseIndex < GCParamArgsEnd, 3969288943Sdim "gc.relocate: statepoint base index doesn't fall within the " 3970288943Sdim "'gc parameters' section of the statepoint call", 3971288943Sdim CS); 3972288943Sdim Assert(GCParamArgsStart <= DerivedIndex && DerivedIndex < GCParamArgsEnd, 3973288943Sdim "gc.relocate: statepoint derived index doesn't fall within the " 3974288943Sdim "'gc parameters' section of the statepoint call", 3975288943Sdim CS); 3976280031Sdim 3977296417Sdim // Relocated value must be either a pointer type or vector-of-pointer type, 3978296417Sdim // but gc_relocate does not need to return the same pointer type as the 3979296417Sdim // relocated pointer. It can be casted to the correct type later if it's 3980296417Sdim // desired. However, they must have the same address space and 'vectorness' 3981296417Sdim GCRelocateInst &Relocate = cast<GCRelocateInst>(*CS.getInstruction()); 3982296417Sdim Assert(Relocate.getDerivedPtr()->getType()->getScalarType()->isPointerTy(), 3983288943Sdim "gc.relocate: relocated value must be a gc pointer", CS); 3984280031Sdim 3985296417Sdim auto ResultType = CS.getType(); 3986296417Sdim auto DerivedType = Relocate.getDerivedPtr()->getType(); 3987296417Sdim Assert(ResultType->isVectorTy() == DerivedType->isVectorTy(), 3988296417Sdim "gc.relocate: vector relocates to vector and pointer to pointer", CS); 3989296417Sdim Assert(ResultType->getPointerAddressSpace() == 3990296417Sdim DerivedType->getPointerAddressSpace(), 3991288943Sdim "gc.relocate: relocating a pointer shouldn't change its address space", CS); 3992280031Sdim break; 3993280031Sdim } 3994296417Sdim case Intrinsic::eh_exceptioncode: 3995296417Sdim case Intrinsic::eh_exceptionpointer: { 3996296417Sdim Assert(isa<CatchPadInst>(CS.getArgOperand(0)), 3997296417Sdim "eh.exceptionpointer argument must be a catchpad", CS); 3998296417Sdim break; 3999296417Sdim } 4000280031Sdim }; 4001249259Sdim} 4002249259Sdim 4003288943Sdim/// \brief Carefully grab the subprogram from a local scope. 4004288943Sdim/// 4005288943Sdim/// This carefully grabs the subprogram from a local scope, avoiding the 4006288943Sdim/// built-in assertions that would typically fire. 4007288943Sdimstatic DISubprogram *getSubprogram(Metadata *LocalScope) { 4008288943Sdim if (!LocalScope) 4009288943Sdim return nullptr; 4010276479Sdim 4011288943Sdim if (auto *SP = dyn_cast<DISubprogram>(LocalScope)) 4012288943Sdim return SP; 4013276479Sdim 4014288943Sdim if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope)) 4015288943Sdim return getSubprogram(LB->getRawScope()); 4016288943Sdim 4017288943Sdim // Just return null; broken scope chains are checked elsewhere. 4018288943Sdim assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope"); 4019288943Sdim return nullptr; 4020288943Sdim} 4021288943Sdim 4022288943Sdimtemplate <class DbgIntrinsicTy> 4023288943Sdimvoid Verifier::visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII) { 4024288943Sdim auto *MD = cast<MetadataAsValue>(DII.getArgOperand(0))->getMetadata(); 4025288943Sdim Assert(isa<ValueAsMetadata>(MD) || 4026288943Sdim (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()), 4027288943Sdim "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD); 4028288943Sdim Assert(isa<DILocalVariable>(DII.getRawVariable()), 4029288943Sdim "invalid llvm.dbg." + Kind + " intrinsic variable", &DII, 4030288943Sdim DII.getRawVariable()); 4031288943Sdim Assert(isa<DIExpression>(DII.getRawExpression()), 4032288943Sdim "invalid llvm.dbg." + Kind + " intrinsic expression", &DII, 4033288943Sdim DII.getRawExpression()); 4034288943Sdim 4035288943Sdim // Ignore broken !dbg attachments; they're checked elsewhere. 4036288943Sdim if (MDNode *N = DII.getDebugLoc().getAsMDNode()) 4037288943Sdim if (!isa<DILocation>(N)) 4038288943Sdim return; 4039288943Sdim 4040288943Sdim BasicBlock *BB = DII.getParent(); 4041288943Sdim Function *F = BB ? BB->getParent() : nullptr; 4042288943Sdim 4043288943Sdim // The scopes for variables and !dbg attachments must agree. 4044288943Sdim DILocalVariable *Var = DII.getVariable(); 4045288943Sdim DILocation *Loc = DII.getDebugLoc(); 4046288943Sdim Assert(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment", 4047288943Sdim &DII, BB, F); 4048288943Sdim 4049288943Sdim DISubprogram *VarSP = getSubprogram(Var->getRawScope()); 4050288943Sdim DISubprogram *LocSP = getSubprogram(Loc->getRawScope()); 4051288943Sdim if (!VarSP || !LocSP) 4052288943Sdim return; // Broken scope chains are checked elsewhere. 4053288943Sdim 4054288943Sdim Assert(VarSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind + 4055288943Sdim " variable and !dbg attachment", 4056288943Sdim &DII, BB, F, Var, Var->getScope()->getSubprogram(), Loc, 4057288943Sdim Loc->getScope()->getSubprogram()); 4058288943Sdim} 4059288943Sdim 4060288943Sdimtemplate <class MapTy> 4061288943Sdimstatic uint64_t getVariableSize(const DILocalVariable &V, const MapTy &Map) { 4062288943Sdim // Be careful of broken types (checked elsewhere). 4063288943Sdim const Metadata *RawType = V.getRawType(); 4064288943Sdim while (RawType) { 4065288943Sdim // Try to get the size directly. 4066288943Sdim if (auto *T = dyn_cast<DIType>(RawType)) 4067288943Sdim if (uint64_t Size = T->getSizeInBits()) 4068288943Sdim return Size; 4069288943Sdim 4070288943Sdim if (auto *DT = dyn_cast<DIDerivedType>(RawType)) { 4071288943Sdim // Look at the base type. 4072288943Sdim RawType = DT->getRawBaseType(); 4073288943Sdim continue; 4074288943Sdim } 4075288943Sdim 4076288943Sdim if (auto *S = dyn_cast<MDString>(RawType)) { 4077288943Sdim // Don't error on missing types (checked elsewhere). 4078288943Sdim RawType = Map.lookup(S); 4079288943Sdim continue; 4080288943Sdim } 4081288943Sdim 4082288943Sdim // Missing type or size. 4083288943Sdim break; 4084261991Sdim } 4085288943Sdim 4086288943Sdim // Fail gracefully. 4087288943Sdim return 0; 4088288943Sdim} 4089288943Sdim 4090288943Sdimtemplate <class MapTy> 4091288943Sdimvoid Verifier::verifyBitPieceExpression(const DbgInfoIntrinsic &I, 4092288943Sdim const MapTy &TypeRefs) { 4093288943Sdim DILocalVariable *V; 4094288943Sdim DIExpression *E; 4095288943Sdim if (auto *DVI = dyn_cast<DbgValueInst>(&I)) { 4096288943Sdim V = dyn_cast_or_null<DILocalVariable>(DVI->getRawVariable()); 4097288943Sdim E = dyn_cast_or_null<DIExpression>(DVI->getRawExpression()); 4098288943Sdim } else { 4099288943Sdim auto *DDI = cast<DbgDeclareInst>(&I); 4100288943Sdim V = dyn_cast_or_null<DILocalVariable>(DDI->getRawVariable()); 4101288943Sdim E = dyn_cast_or_null<DIExpression>(DDI->getRawExpression()); 4102276479Sdim } 4103288943Sdim 4104288943Sdim // We don't know whether this intrinsic verified correctly. 4105288943Sdim if (!V || !E || !E->isValid()) 4106288943Sdim return; 4107288943Sdim 4108288943Sdim // Nothing to do if this isn't a bit piece expression. 4109288943Sdim if (!E->isBitPiece()) 4110288943Sdim return; 4111288943Sdim 4112288943Sdim // The frontend helps out GDB by emitting the members of local anonymous 4113288943Sdim // unions as artificial local variables with shared storage. When SROA splits 4114288943Sdim // the storage for artificial local variables that are smaller than the entire 4115288943Sdim // union, the overhang piece will be outside of the allotted space for the 4116288943Sdim // variable and this check fails. 4117288943Sdim // FIXME: Remove this check as soon as clang stops doing this; it hides bugs. 4118288943Sdim if (V->isArtificial()) 4119288943Sdim return; 4120288943Sdim 4121288943Sdim // If there's no size, the type is broken, but that should be checked 4122288943Sdim // elsewhere. 4123288943Sdim uint64_t VarSize = getVariableSize(*V, TypeRefs); 4124288943Sdim if (!VarSize) 4125288943Sdim return; 4126288943Sdim 4127288943Sdim unsigned PieceSize = E->getBitPieceSize(); 4128288943Sdim unsigned PieceOffset = E->getBitPieceOffset(); 4129288943Sdim Assert(PieceSize + PieceOffset <= VarSize, 4130288943Sdim "piece is larger than or outside of variable", &I, V, E); 4131288943Sdim Assert(PieceSize != VarSize, "piece covers entire variable", &I, V, E); 4132261991Sdim} 4133261991Sdim 4134288943Sdimvoid Verifier::visitUnresolvedTypeRef(const MDString *S, const MDNode *N) { 4135288943Sdim // This is in its own function so we get an error for each bad type ref (not 4136288943Sdim // just the first). 4137288943Sdim Assert(false, "unresolved type ref", S, N); 4138276479Sdim} 4139276479Sdim 4140288943Sdimvoid Verifier::verifyTypeRefs() { 4141288943Sdim auto *CUs = M->getNamedMetadata("llvm.dbg.cu"); 4142288943Sdim if (!CUs) 4143288943Sdim return; 4144288943Sdim 4145288943Sdim // Visit all the compile units again to map the type references. 4146288943Sdim SmallDenseMap<const MDString *, const DIType *, 32> TypeRefs; 4147288943Sdim for (auto *CU : CUs->operands()) 4148288943Sdim if (auto Ts = cast<DICompileUnit>(CU)->getRetainedTypes()) 4149288943Sdim for (DIType *Op : Ts) 4150296417Sdim if (auto *T = dyn_cast_or_null<DICompositeType>(Op)) 4151288943Sdim if (auto *S = T->getRawIdentifier()) { 4152288943Sdim UnresolvedTypeRefs.erase(S); 4153288943Sdim TypeRefs.insert(std::make_pair(S, T)); 4154288943Sdim } 4155288943Sdim 4156288943Sdim // Verify debug info intrinsic bit piece expressions. This needs a second 4157288943Sdim // pass through the intructions, since we haven't built TypeRefs yet when 4158288943Sdim // verifying functions, and simply queuing the DbgInfoIntrinsics to evaluate 4159288943Sdim // later/now would queue up some that could be later deleted. 4160288943Sdim for (const Function &F : *M) 4161288943Sdim for (const BasicBlock &BB : F) 4162288943Sdim for (const Instruction &I : BB) 4163288943Sdim if (auto *DII = dyn_cast<DbgInfoIntrinsic>(&I)) 4164288943Sdim verifyBitPieceExpression(*DII, TypeRefs); 4165288943Sdim 4166288943Sdim // Return early if all typerefs were resolved. 4167288943Sdim if (UnresolvedTypeRefs.empty()) 4168288943Sdim return; 4169288943Sdim 4170288943Sdim // Sort the unresolved references by name so the output is deterministic. 4171288943Sdim typedef std::pair<const MDString *, const MDNode *> TypeRef; 4172288943Sdim SmallVector<TypeRef, 32> Unresolved(UnresolvedTypeRefs.begin(), 4173288943Sdim UnresolvedTypeRefs.end()); 4174288943Sdim std::sort(Unresolved.begin(), Unresolved.end(), 4175288943Sdim [](const TypeRef &LHS, const TypeRef &RHS) { 4176288943Sdim return LHS.first->getString() < RHS.first->getString(); 4177288943Sdim }); 4178288943Sdim 4179288943Sdim // Visit the unresolved refs (printing out the errors). 4180288943Sdim for (const TypeRef &TR : Unresolved) 4181288943Sdim visitUnresolvedTypeRef(TR.first, TR.second); 4182276479Sdim} 4183276479Sdim 4184249259Sdim//===----------------------------------------------------------------------===// 4185249259Sdim// Implement the public interfaces to this file... 4186249259Sdim//===----------------------------------------------------------------------===// 4187249259Sdim 4188276479Sdimbool llvm::verifyFunction(const Function &f, raw_ostream *OS) { 4189276479Sdim Function &F = const_cast<Function &>(f); 4190276479Sdim assert(!F.isDeclaration() && "Cannot verify external functions"); 4191276479Sdim 4192276479Sdim raw_null_ostream NullStr; 4193276479Sdim Verifier V(OS ? *OS : NullStr); 4194276479Sdim 4195276479Sdim // Note that this function's return value is inverted from what you would 4196276479Sdim // expect of a function called "verify". 4197276479Sdim return !V.verify(F); 4198249259Sdim} 4199249259Sdim 4200276479Sdimbool llvm::verifyModule(const Module &M, raw_ostream *OS) { 4201276479Sdim raw_null_ostream NullStr; 4202276479Sdim Verifier V(OS ? *OS : NullStr); 4203249259Sdim 4204276479Sdim bool Broken = false; 4205276479Sdim for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) 4206280031Sdim if (!I->isDeclaration() && !I->isMaterializable()) 4207276479Sdim Broken |= !V.verify(*I); 4208249259Sdim 4209276479Sdim // Note that this function's return value is inverted from what you would 4210276479Sdim // expect of a function called "verify". 4211288943Sdim return !V.verify(M) || Broken; 4212249259Sdim} 4213249259Sdim 4214276479Sdimnamespace { 4215276479Sdimstruct VerifierLegacyPass : public FunctionPass { 4216276479Sdim static char ID; 4217249259Sdim 4218276479Sdim Verifier V; 4219276479Sdim bool FatalErrors; 4220276479Sdim 4221288943Sdim VerifierLegacyPass() : FunctionPass(ID), V(dbgs()), FatalErrors(true) { 4222276479Sdim initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry()); 4223276479Sdim } 4224276479Sdim explicit VerifierLegacyPass(bool FatalErrors) 4225276479Sdim : FunctionPass(ID), V(dbgs()), FatalErrors(FatalErrors) { 4226276479Sdim initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry()); 4227276479Sdim } 4228276479Sdim 4229276479Sdim bool runOnFunction(Function &F) override { 4230276479Sdim if (!V.verify(F) && FatalErrors) 4231276479Sdim report_fatal_error("Broken function found, compilation aborted!"); 4232276479Sdim 4233276479Sdim return false; 4234276479Sdim } 4235276479Sdim 4236276479Sdim bool doFinalization(Module &M) override { 4237276479Sdim if (!V.verify(M) && FatalErrors) 4238276479Sdim report_fatal_error("Broken module found, compilation aborted!"); 4239276479Sdim 4240276479Sdim return false; 4241276479Sdim } 4242276479Sdim 4243276479Sdim void getAnalysisUsage(AnalysisUsage &AU) const override { 4244276479Sdim AU.setPreservesAll(); 4245276479Sdim } 4246276479Sdim}; 4247249259Sdim} 4248276479Sdim 4249276479Sdimchar VerifierLegacyPass::ID = 0; 4250276479SdimINITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false) 4251276479Sdim 4252276479SdimFunctionPass *llvm::createVerifierPass(bool FatalErrors) { 4253276479Sdim return new VerifierLegacyPass(FatalErrors); 4254276479Sdim} 4255276479Sdim 4256280031SdimPreservedAnalyses VerifierPass::run(Module &M) { 4257280031Sdim if (verifyModule(M, &dbgs()) && FatalErrors) 4258276479Sdim report_fatal_error("Broken module found, compilation aborted!"); 4259276479Sdim 4260276479Sdim return PreservedAnalyses::all(); 4261276479Sdim} 4262276479Sdim 4263280031SdimPreservedAnalyses VerifierPass::run(Function &F) { 4264280031Sdim if (verifyFunction(F, &dbgs()) && FatalErrors) 4265276479Sdim report_fatal_error("Broken function found, compilation aborted!"); 4266276479Sdim 4267276479Sdim return PreservedAnalyses::all(); 4268276479Sdim} 4269