Verifier.cpp 140 KB

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