Verifier.cpp 140 KB

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