Verifier.cpp 140 KB

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