BitcodeReader.cpp 160 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576
  1. //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
  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. #include "llvm/Bitcode/ReaderWriter.h"
  10. #include "llvm/ADT/STLExtras.h"
  11. #include "llvm/ADT/SmallString.h"
  12. #include "llvm/ADT/SmallVector.h"
  13. #include "llvm/ADT/Triple.h"
  14. #include "llvm/Bitcode/BitstreamReader.h"
  15. #include "llvm/Bitcode/LLVMBitCodes.h"
  16. #include "llvm/IR/AutoUpgrade.h"
  17. #include "llvm/IR/Constants.h"
  18. #include "llvm/IR/DebugInfoMetadata.h"
  19. #include "llvm/IR/DerivedTypes.h"
  20. #include "llvm/IR/DiagnosticPrinter.h"
  21. #include "llvm/IR/GVMaterializer.h"
  22. #include "llvm/IR/InlineAsm.h"
  23. #include "llvm/IR/IntrinsicInst.h"
  24. #include "llvm/IR/LLVMContext.h"
  25. #include "llvm/IR/Module.h"
  26. #include "llvm/IR/OperandTraits.h"
  27. #include "llvm/IR/Operator.h"
  28. #include "llvm/IR/ValueHandle.h"
  29. #include "llvm/Support/DataStream.h"
  30. #include "llvm/Support/ManagedStatic.h"
  31. #include "llvm/Support/MathExtras.h"
  32. #include "llvm/Support/MemoryBuffer.h"
  33. #include "llvm/Support/raw_ostream.h"
  34. #include <deque>
  35. using namespace llvm;
  36. namespace {
  37. enum {
  38. SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
  39. };
  40. class BitcodeReaderValueList {
  41. std::vector<WeakVH> ValuePtrs;
  42. /// ResolveConstants - As we resolve forward-referenced constants, we add
  43. /// information about them to this vector. This allows us to resolve them in
  44. /// bulk instead of resolving each reference at a time. See the code in
  45. /// ResolveConstantForwardRefs for more information about this.
  46. ///
  47. /// The key of this vector is the placeholder constant, the value is the slot
  48. /// number that holds the resolved value.
  49. typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
  50. ResolveConstantsTy ResolveConstants;
  51. LLVMContext &Context;
  52. public:
  53. BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
  54. ~BitcodeReaderValueList() {
  55. assert(ResolveConstants.empty() && "Constants not resolved?");
  56. }
  57. // vector compatibility methods
  58. unsigned size() const { return ValuePtrs.size(); }
  59. void resize(unsigned N) { ValuePtrs.resize(N); }
  60. void push_back(Value *V) {
  61. ValuePtrs.push_back(V);
  62. }
  63. void clear() {
  64. assert(ResolveConstants.empty() && "Constants not resolved?");
  65. ValuePtrs.clear();
  66. }
  67. Value *operator[](unsigned i) const {
  68. assert(i < ValuePtrs.size());
  69. return ValuePtrs[i];
  70. }
  71. Value *back() const { return ValuePtrs.back(); }
  72. void pop_back() { ValuePtrs.pop_back(); }
  73. bool empty() const { return ValuePtrs.empty(); }
  74. void shrinkTo(unsigned N) {
  75. assert(N <= size() && "Invalid shrinkTo request!");
  76. ValuePtrs.resize(N);
  77. }
  78. Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
  79. Value *getValueFwdRef(unsigned Idx, Type *Ty);
  80. void AssignValue(Value *V, unsigned Idx);
  81. /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
  82. /// resolves any forward references.
  83. void ResolveConstantForwardRefs();
  84. };
  85. class BitcodeReaderMDValueList {
  86. unsigned NumFwdRefs;
  87. bool AnyFwdRefs;
  88. unsigned MinFwdRef;
  89. unsigned MaxFwdRef;
  90. std::vector<TrackingMDRef> MDValuePtrs;
  91. LLVMContext &Context;
  92. public:
  93. BitcodeReaderMDValueList(LLVMContext &C)
  94. : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
  95. // vector compatibility methods
  96. unsigned size() const { return MDValuePtrs.size(); }
  97. void resize(unsigned N) { MDValuePtrs.resize(N); }
  98. void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); }
  99. void clear() { MDValuePtrs.clear(); }
  100. Metadata *back() const { return MDValuePtrs.back(); }
  101. void pop_back() { MDValuePtrs.pop_back(); }
  102. bool empty() const { return MDValuePtrs.empty(); }
  103. Metadata *operator[](unsigned i) const {
  104. assert(i < MDValuePtrs.size());
  105. return MDValuePtrs[i];
  106. }
  107. void shrinkTo(unsigned N) {
  108. assert(N <= size() && "Invalid shrinkTo request!");
  109. MDValuePtrs.resize(N);
  110. }
  111. Metadata *getValueFwdRef(unsigned Idx);
  112. void AssignValue(Metadata *MD, unsigned Idx);
  113. void tryToResolveCycles();
  114. };
  115. class BitcodeReader : public GVMaterializer {
  116. LLVMContext &Context;
  117. DiagnosticHandlerFunction DiagnosticHandler;
  118. Module *TheModule;
  119. std::unique_ptr<MemoryBuffer> Buffer;
  120. std::unique_ptr<BitstreamReader> StreamFile;
  121. BitstreamCursor Stream;
  122. DataStreamer *LazyStreamer;
  123. uint64_t NextUnreadBit;
  124. bool SeenValueSymbolTable;
  125. std::vector<Type*> TypeList;
  126. BitcodeReaderValueList ValueList;
  127. BitcodeReaderMDValueList MDValueList;
  128. std::vector<Comdat *> ComdatList;
  129. SmallVector<Instruction *, 64> InstructionList;
  130. std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
  131. std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
  132. std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
  133. std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
  134. SmallVector<Instruction*, 64> InstsWithTBAATag;
  135. /// MAttributes - The set of attributes by index. Index zero in the
  136. /// file is for null, and is thus not represented here. As such all indices
  137. /// are off by one.
  138. std::vector<AttributeSet> MAttributes;
  139. /// \brief The set of attribute groups.
  140. std::map<unsigned, AttributeSet> MAttributeGroups;
  141. /// FunctionBBs - While parsing a function body, this is a list of the basic
  142. /// blocks for the function.
  143. std::vector<BasicBlock*> FunctionBBs;
  144. // When reading the module header, this list is populated with functions that
  145. // have bodies later in the file.
  146. std::vector<Function*> FunctionsWithBodies;
  147. // When intrinsic functions are encountered which require upgrading they are
  148. // stored here with their replacement function.
  149. typedef std::vector<std::pair<Function*, Function*> > UpgradedIntrinsicMap;
  150. UpgradedIntrinsicMap UpgradedIntrinsics;
  151. // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
  152. DenseMap<unsigned, unsigned> MDKindMap;
  153. // Several operations happen after the module header has been read, but
  154. // before function bodies are processed. This keeps track of whether
  155. // we've done this yet.
  156. bool SeenFirstFunctionBody;
  157. /// DeferredFunctionInfo - When function bodies are initially scanned, this
  158. /// map contains info about where to find deferred function body in the
  159. /// stream.
  160. DenseMap<Function*, uint64_t> DeferredFunctionInfo;
  161. /// When Metadata block is initially scanned when parsing the module, we may
  162. /// choose to defer parsing of the metadata. This vector contains info about
  163. /// which Metadata blocks are deferred.
  164. std::vector<uint64_t> DeferredMetadataInfo;
  165. /// These are basic blocks forward-referenced by block addresses. They are
  166. /// inserted lazily into functions when they're loaded. The basic block ID is
  167. /// its index into the vector.
  168. DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
  169. std::deque<Function *> BasicBlockFwdRefQueue;
  170. /// UseRelativeIDs - Indicates that we are using a new encoding for
  171. /// instruction operands where most operands in the current
  172. /// FUNCTION_BLOCK are encoded relative to the instruction number,
  173. /// for a more compact encoding. Some instruction operands are not
  174. /// relative to the instruction ID: basic block numbers, and types.
  175. /// Once the old style function blocks have been phased out, we would
  176. /// not need this flag.
  177. bool UseRelativeIDs;
  178. /// True if all functions will be materialized, negating the need to process
  179. /// (e.g.) blockaddress forward references.
  180. bool WillMaterializeAllForwardRefs;
  181. /// Functions that have block addresses taken. This is usually empty.
  182. SmallPtrSet<const Function *, 4> BlockAddressesTaken;
  183. /// True if any Metadata block has been materialized.
  184. bool IsMetadataMaterialized;
  185. public:
  186. std::error_code Error(BitcodeError E, const Twine &Message);
  187. std::error_code Error(BitcodeError E);
  188. std::error_code Error(const Twine &Message);
  189. explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
  190. DiagnosticHandlerFunction DiagnosticHandler);
  191. explicit BitcodeReader(DataStreamer *streamer, LLVMContext &C,
  192. DiagnosticHandlerFunction DiagnosticHandler);
  193. ~BitcodeReader() { FreeState(); }
  194. std::error_code materializeForwardReferencedFunctions();
  195. void FreeState();
  196. void releaseBuffer();
  197. bool isDematerializable(const GlobalValue *GV) const override;
  198. std::error_code materialize(GlobalValue *GV) override;
  199. std::error_code MaterializeModule(Module *M) override;
  200. std::vector<StructType *> getIdentifiedStructTypes() const override;
  201. void Dematerialize(GlobalValue *GV) override;
  202. /// @brief Main interface to parsing a bitcode buffer.
  203. /// @returns true if an error occurred.
  204. std::error_code ParseBitcodeInto(Module *M,
  205. bool ShouldLazyLoadMetadata = false);
  206. /// @brief Cheap mechanism to just extract module triple
  207. /// @returns true if an error occurred.
  208. ErrorOr<std::string> parseTriple();
  209. static uint64_t decodeSignRotatedValue(uint64_t V);
  210. /// Materialize any deferred Metadata block.
  211. std::error_code materializeMetadata() override;
  212. private:
  213. std::vector<StructType *> IdentifiedStructTypes;
  214. StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
  215. StructType *createIdentifiedStructType(LLVMContext &Context);
  216. Type *getTypeByID(unsigned ID);
  217. Value *getFnValueByID(unsigned ID, Type *Ty) {
  218. if (Ty && Ty->isMetadataTy())
  219. return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
  220. return ValueList.getValueFwdRef(ID, Ty);
  221. }
  222. Metadata *getFnMetadataByID(unsigned ID) {
  223. return MDValueList.getValueFwdRef(ID);
  224. }
  225. BasicBlock *getBasicBlock(unsigned ID) const {
  226. if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
  227. return FunctionBBs[ID];
  228. }
  229. AttributeSet getAttributes(unsigned i) const {
  230. if (i-1 < MAttributes.size())
  231. return MAttributes[i-1];
  232. return AttributeSet();
  233. }
  234. /// getValueTypePair - Read a value/type pair out of the specified record from
  235. /// slot 'Slot'. Increment Slot past the number of slots used in the record.
  236. /// Return true on failure.
  237. bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
  238. unsigned InstNum, Value *&ResVal) {
  239. if (Slot == Record.size()) return true;
  240. unsigned ValNo = (unsigned)Record[Slot++];
  241. // Adjust the ValNo, if it was encoded relative to the InstNum.
  242. if (UseRelativeIDs)
  243. ValNo = InstNum - ValNo;
  244. if (ValNo < InstNum) {
  245. // If this is not a forward reference, just return the value we already
  246. // have.
  247. ResVal = getFnValueByID(ValNo, nullptr);
  248. return ResVal == nullptr;
  249. } else if (Slot == Record.size()) {
  250. return true;
  251. }
  252. unsigned TypeNo = (unsigned)Record[Slot++];
  253. ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
  254. return ResVal == nullptr;
  255. }
  256. /// popValue - Read a value out of the specified record from slot 'Slot'.
  257. /// Increment Slot past the number of slots used by the value in the record.
  258. /// Return true if there is an error.
  259. bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
  260. unsigned InstNum, Type *Ty, Value *&ResVal) {
  261. if (getValue(Record, Slot, InstNum, Ty, ResVal))
  262. return true;
  263. // All values currently take a single record slot.
  264. ++Slot;
  265. return false;
  266. }
  267. /// getValue -- Like popValue, but does not increment the Slot number.
  268. bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
  269. unsigned InstNum, Type *Ty, Value *&ResVal) {
  270. ResVal = getValue(Record, Slot, InstNum, Ty);
  271. return ResVal == nullptr;
  272. }
  273. /// getValue -- Version of getValue that returns ResVal directly,
  274. /// or 0 if there is an error.
  275. Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
  276. unsigned InstNum, Type *Ty) {
  277. if (Slot == Record.size()) return nullptr;
  278. unsigned ValNo = (unsigned)Record[Slot];
  279. // Adjust the ValNo, if it was encoded relative to the InstNum.
  280. if (UseRelativeIDs)
  281. ValNo = InstNum - ValNo;
  282. return getFnValueByID(ValNo, Ty);
  283. }
  284. /// getValueSigned -- Like getValue, but decodes signed VBRs.
  285. Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
  286. unsigned InstNum, Type *Ty) {
  287. if (Slot == Record.size()) return nullptr;
  288. unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
  289. // Adjust the ValNo, if it was encoded relative to the InstNum.
  290. if (UseRelativeIDs)
  291. ValNo = InstNum - ValNo;
  292. return getFnValueByID(ValNo, Ty);
  293. }
  294. /// Converts alignment exponent (i.e. power of two (or zero)) to the
  295. /// corresponding alignment to use. If alignment is too large, returns
  296. /// a corresponding error code.
  297. std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
  298. std::error_code ParseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
  299. std::error_code ParseModule(bool Resume, bool ShouldLazyLoadMetadata = false);
  300. std::error_code ParseAttributeBlock();
  301. std::error_code ParseAttributeGroupBlock();
  302. std::error_code ParseTypeTable();
  303. std::error_code ParseTypeTableBody();
  304. std::error_code ParseValueSymbolTable();
  305. std::error_code ParseConstants();
  306. std::error_code RememberAndSkipFunctionBody();
  307. /// Save the positions of the Metadata blocks and skip parsing the blocks.
  308. std::error_code rememberAndSkipMetadata();
  309. std::error_code ParseFunctionBody(Function *F);
  310. std::error_code GlobalCleanup();
  311. std::error_code ResolveGlobalAndAliasInits();
  312. std::error_code ParseMetadata();
  313. std::error_code ParseMetadataAttachment();
  314. ErrorOr<std::string> parseModuleTriple();
  315. std::error_code ParseUseLists();
  316. std::error_code InitStream();
  317. std::error_code InitStreamFromBuffer();
  318. std::error_code InitLazyStream();
  319. std::error_code FindFunctionInStream(
  320. Function *F,
  321. DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
  322. };
  323. } // namespace
  324. BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
  325. DiagnosticSeverity Severity,
  326. const Twine &Msg)
  327. : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
  328. void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
  329. static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
  330. std::error_code EC, const Twine &Message) {
  331. BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
  332. DiagnosticHandler(DI);
  333. return EC;
  334. }
  335. static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
  336. std::error_code EC) {
  337. return Error(DiagnosticHandler, EC, EC.message());
  338. }
  339. std::error_code BitcodeReader::Error(BitcodeError E, const Twine &Message) {
  340. return ::Error(DiagnosticHandler, make_error_code(E), Message);
  341. }
  342. std::error_code BitcodeReader::Error(const Twine &Message) {
  343. return ::Error(DiagnosticHandler,
  344. make_error_code(BitcodeError::CorruptedBitcode), Message);
  345. }
  346. std::error_code BitcodeReader::Error(BitcodeError E) {
  347. return ::Error(DiagnosticHandler, make_error_code(E));
  348. }
  349. static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
  350. LLVMContext &C) {
  351. if (F)
  352. return F;
  353. return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
  354. }
  355. BitcodeReader::BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
  356. DiagnosticHandlerFunction DiagnosticHandler)
  357. : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
  358. TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
  359. NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
  360. MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
  361. WillMaterializeAllForwardRefs(false), IsMetadataMaterialized(false) {}
  362. BitcodeReader::BitcodeReader(DataStreamer *streamer, LLVMContext &C,
  363. DiagnosticHandlerFunction DiagnosticHandler)
  364. : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
  365. TheModule(nullptr), Buffer(nullptr), LazyStreamer(streamer),
  366. NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
  367. MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
  368. WillMaterializeAllForwardRefs(false), IsMetadataMaterialized(false) {}
  369. std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
  370. if (WillMaterializeAllForwardRefs)
  371. return std::error_code();
  372. // Prevent recursion.
  373. WillMaterializeAllForwardRefs = true;
  374. while (!BasicBlockFwdRefQueue.empty()) {
  375. Function *F = BasicBlockFwdRefQueue.front();
  376. BasicBlockFwdRefQueue.pop_front();
  377. assert(F && "Expected valid function");
  378. if (!BasicBlockFwdRefs.count(F))
  379. // Already materialized.
  380. continue;
  381. // Check for a function that isn't materializable to prevent an infinite
  382. // loop. When parsing a blockaddress stored in a global variable, there
  383. // isn't a trivial way to check if a function will have a body without a
  384. // linear search through FunctionsWithBodies, so just check it here.
  385. if (!F->isMaterializable())
  386. return Error("Never resolved function from blockaddress");
  387. // Try to materialize F.
  388. if (std::error_code EC = materialize(F))
  389. return EC;
  390. }
  391. assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
  392. // Reset state.
  393. WillMaterializeAllForwardRefs = false;
  394. return std::error_code();
  395. }
  396. void BitcodeReader::FreeState() {
  397. Buffer = nullptr;
  398. std::vector<Type*>().swap(TypeList);
  399. ValueList.clear();
  400. MDValueList.clear();
  401. std::vector<Comdat *>().swap(ComdatList);
  402. std::vector<AttributeSet>().swap(MAttributes);
  403. std::vector<BasicBlock*>().swap(FunctionBBs);
  404. std::vector<Function*>().swap(FunctionsWithBodies);
  405. DeferredFunctionInfo.clear();
  406. DeferredMetadataInfo.clear();
  407. MDKindMap.clear();
  408. assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
  409. BasicBlockFwdRefQueue.clear();
  410. }
  411. //===----------------------------------------------------------------------===//
  412. // Helper functions to implement forward reference resolution, etc.
  413. //===----------------------------------------------------------------------===//
  414. /// ConvertToString - Convert a string from a record into an std::string, return
  415. /// true on failure.
  416. template<typename StrTy>
  417. static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
  418. StrTy &Result) {
  419. if (Idx > Record.size())
  420. return true;
  421. for (unsigned i = Idx, e = Record.size(); i != e; ++i)
  422. Result += (char)Record[i];
  423. return false;
  424. }
  425. static bool hasImplicitComdat(size_t Val) {
  426. switch (Val) {
  427. default:
  428. return false;
  429. case 1: // Old WeakAnyLinkage
  430. case 4: // Old LinkOnceAnyLinkage
  431. case 10: // Old WeakODRLinkage
  432. case 11: // Old LinkOnceODRLinkage
  433. return true;
  434. }
  435. }
  436. static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
  437. switch (Val) {
  438. default: // Map unknown/new linkages to external
  439. case 0:
  440. return GlobalValue::ExternalLinkage;
  441. case 2:
  442. return GlobalValue::AppendingLinkage;
  443. case 3:
  444. return GlobalValue::InternalLinkage;
  445. case 5:
  446. return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
  447. case 6:
  448. return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
  449. case 7:
  450. return GlobalValue::ExternalWeakLinkage;
  451. case 8:
  452. return GlobalValue::CommonLinkage;
  453. case 9:
  454. return GlobalValue::PrivateLinkage;
  455. case 12:
  456. return GlobalValue::AvailableExternallyLinkage;
  457. case 13:
  458. return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
  459. case 14:
  460. return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
  461. case 15:
  462. return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
  463. case 1: // Old value with implicit comdat.
  464. case 16:
  465. return GlobalValue::WeakAnyLinkage;
  466. case 10: // Old value with implicit comdat.
  467. case 17:
  468. return GlobalValue::WeakODRLinkage;
  469. case 4: // Old value with implicit comdat.
  470. case 18:
  471. return GlobalValue::LinkOnceAnyLinkage;
  472. case 11: // Old value with implicit comdat.
  473. case 19:
  474. return GlobalValue::LinkOnceODRLinkage;
  475. }
  476. }
  477. static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
  478. switch (Val) {
  479. default: // Map unknown visibilities to default.
  480. case 0: return GlobalValue::DefaultVisibility;
  481. case 1: return GlobalValue::HiddenVisibility;
  482. case 2: return GlobalValue::ProtectedVisibility;
  483. }
  484. }
  485. static GlobalValue::DLLStorageClassTypes
  486. GetDecodedDLLStorageClass(unsigned Val) {
  487. switch (Val) {
  488. default: // Map unknown values to default.
  489. case 0: return GlobalValue::DefaultStorageClass;
  490. case 1: return GlobalValue::DLLImportStorageClass;
  491. case 2: return GlobalValue::DLLExportStorageClass;
  492. }
  493. }
  494. static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
  495. switch (Val) {
  496. case 0: return GlobalVariable::NotThreadLocal;
  497. default: // Map unknown non-zero value to general dynamic.
  498. case 1: return GlobalVariable::GeneralDynamicTLSModel;
  499. case 2: return GlobalVariable::LocalDynamicTLSModel;
  500. case 3: return GlobalVariable::InitialExecTLSModel;
  501. case 4: return GlobalVariable::LocalExecTLSModel;
  502. }
  503. }
  504. static int GetDecodedCastOpcode(unsigned Val) {
  505. switch (Val) {
  506. default: return -1;
  507. case bitc::CAST_TRUNC : return Instruction::Trunc;
  508. case bitc::CAST_ZEXT : return Instruction::ZExt;
  509. case bitc::CAST_SEXT : return Instruction::SExt;
  510. case bitc::CAST_FPTOUI : return Instruction::FPToUI;
  511. case bitc::CAST_FPTOSI : return Instruction::FPToSI;
  512. case bitc::CAST_UITOFP : return Instruction::UIToFP;
  513. case bitc::CAST_SITOFP : return Instruction::SIToFP;
  514. case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
  515. case bitc::CAST_FPEXT : return Instruction::FPExt;
  516. case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
  517. case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
  518. case bitc::CAST_BITCAST : return Instruction::BitCast;
  519. case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
  520. }
  521. }
  522. static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
  523. switch (Val) {
  524. default: return -1;
  525. case bitc::BINOP_ADD:
  526. return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
  527. case bitc::BINOP_SUB:
  528. return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
  529. case bitc::BINOP_MUL:
  530. return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
  531. case bitc::BINOP_UDIV: return Instruction::UDiv;
  532. case bitc::BINOP_SDIV:
  533. return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
  534. case bitc::BINOP_UREM: return Instruction::URem;
  535. case bitc::BINOP_SREM:
  536. return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
  537. case bitc::BINOP_SHL: return Instruction::Shl;
  538. case bitc::BINOP_LSHR: return Instruction::LShr;
  539. case bitc::BINOP_ASHR: return Instruction::AShr;
  540. case bitc::BINOP_AND: return Instruction::And;
  541. case bitc::BINOP_OR: return Instruction::Or;
  542. case bitc::BINOP_XOR: return Instruction::Xor;
  543. }
  544. }
  545. static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
  546. switch (Val) {
  547. default: return AtomicRMWInst::BAD_BINOP;
  548. case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
  549. case bitc::RMW_ADD: return AtomicRMWInst::Add;
  550. case bitc::RMW_SUB: return AtomicRMWInst::Sub;
  551. case bitc::RMW_AND: return AtomicRMWInst::And;
  552. case bitc::RMW_NAND: return AtomicRMWInst::Nand;
  553. case bitc::RMW_OR: return AtomicRMWInst::Or;
  554. case bitc::RMW_XOR: return AtomicRMWInst::Xor;
  555. case bitc::RMW_MAX: return AtomicRMWInst::Max;
  556. case bitc::RMW_MIN: return AtomicRMWInst::Min;
  557. case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
  558. case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
  559. }
  560. }
  561. static AtomicOrdering GetDecodedOrdering(unsigned Val) {
  562. switch (Val) {
  563. case bitc::ORDERING_NOTATOMIC: return NotAtomic;
  564. case bitc::ORDERING_UNORDERED: return Unordered;
  565. case bitc::ORDERING_MONOTONIC: return Monotonic;
  566. case bitc::ORDERING_ACQUIRE: return Acquire;
  567. case bitc::ORDERING_RELEASE: return Release;
  568. case bitc::ORDERING_ACQREL: return AcquireRelease;
  569. default: // Map unknown orderings to sequentially-consistent.
  570. case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
  571. }
  572. }
  573. static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
  574. switch (Val) {
  575. case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
  576. default: // Map unknown scopes to cross-thread.
  577. case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
  578. }
  579. }
  580. static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
  581. switch (Val) {
  582. default: // Map unknown selection kinds to any.
  583. case bitc::COMDAT_SELECTION_KIND_ANY:
  584. return Comdat::Any;
  585. case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
  586. return Comdat::ExactMatch;
  587. case bitc::COMDAT_SELECTION_KIND_LARGEST:
  588. return Comdat::Largest;
  589. case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
  590. return Comdat::NoDuplicates;
  591. case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
  592. return Comdat::SameSize;
  593. }
  594. }
  595. static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
  596. switch (Val) {
  597. case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
  598. case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
  599. }
  600. }
  601. namespace llvm {
  602. namespace {
  603. /// @brief A class for maintaining the slot number definition
  604. /// as a placeholder for the actual definition for forward constants defs.
  605. class ConstantPlaceHolder : public ConstantExpr {
  606. void operator=(const ConstantPlaceHolder &) = delete;
  607. public:
  608. // allocate space for exactly one operand
  609. void *operator new(size_t s) {
  610. return User::operator new(s, 1);
  611. }
  612. explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
  613. : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
  614. Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
  615. }
  616. /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
  617. static bool classof(const Value *V) {
  618. return isa<ConstantExpr>(V) &&
  619. cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
  620. }
  621. /// Provide fast operand accessors
  622. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  623. };
  624. }
  625. // FIXME: can we inherit this from ConstantExpr?
  626. template <>
  627. struct OperandTraits<ConstantPlaceHolder> :
  628. public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
  629. };
  630. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
  631. }
  632. void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
  633. if (Idx == size()) {
  634. push_back(V);
  635. return;
  636. }
  637. if (Idx >= size())
  638. resize(Idx+1);
  639. WeakVH &OldV = ValuePtrs[Idx];
  640. if (!OldV) {
  641. OldV = V;
  642. return;
  643. }
  644. // Handle constants and non-constants (e.g. instrs) differently for
  645. // efficiency.
  646. if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
  647. ResolveConstants.push_back(std::make_pair(PHC, Idx));
  648. OldV = V;
  649. } else {
  650. // If there was a forward reference to this value, replace it.
  651. Value *PrevVal = OldV;
  652. OldV->replaceAllUsesWith(V);
  653. delete PrevVal;
  654. }
  655. }
  656. Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
  657. Type *Ty) {
  658. if (Idx >= size())
  659. resize(Idx + 1);
  660. if (Value *V = ValuePtrs[Idx]) {
  661. assert(Ty == V->getType() && "Type mismatch in constant table!");
  662. return cast<Constant>(V);
  663. }
  664. // Create and return a placeholder, which will later be RAUW'd.
  665. Constant *C = new ConstantPlaceHolder(Ty, Context);
  666. ValuePtrs[Idx] = C;
  667. return C;
  668. }
  669. Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
  670. if (Idx >= size())
  671. resize(Idx + 1);
  672. if (Value *V = ValuePtrs[Idx]) {
  673. assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
  674. return V;
  675. }
  676. // No type specified, must be invalid reference.
  677. if (!Ty) return nullptr;
  678. // Create and return a placeholder, which will later be RAUW'd.
  679. Value *V = new Argument(Ty);
  680. ValuePtrs[Idx] = V;
  681. return V;
  682. }
  683. /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
  684. /// resolves any forward references. The idea behind this is that we sometimes
  685. /// get constants (such as large arrays) which reference *many* forward ref
  686. /// constants. Replacing each of these causes a lot of thrashing when
  687. /// building/reuniquing the constant. Instead of doing this, we look at all the
  688. /// uses and rewrite all the place holders at once for any constant that uses
  689. /// a placeholder.
  690. void BitcodeReaderValueList::ResolveConstantForwardRefs() {
  691. // Sort the values by-pointer so that they are efficient to look up with a
  692. // binary search.
  693. std::sort(ResolveConstants.begin(), ResolveConstants.end());
  694. SmallVector<Constant*, 64> NewOps;
  695. while (!ResolveConstants.empty()) {
  696. Value *RealVal = operator[](ResolveConstants.back().second);
  697. Constant *Placeholder = ResolveConstants.back().first;
  698. ResolveConstants.pop_back();
  699. // Loop over all users of the placeholder, updating them to reference the
  700. // new value. If they reference more than one placeholder, update them all
  701. // at once.
  702. while (!Placeholder->use_empty()) {
  703. auto UI = Placeholder->user_begin();
  704. User *U = *UI;
  705. // If the using object isn't uniqued, just update the operands. This
  706. // handles instructions and initializers for global variables.
  707. if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
  708. UI.getUse().set(RealVal);
  709. continue;
  710. }
  711. // Otherwise, we have a constant that uses the placeholder. Replace that
  712. // constant with a new constant that has *all* placeholder uses updated.
  713. Constant *UserC = cast<Constant>(U);
  714. for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
  715. I != E; ++I) {
  716. Value *NewOp;
  717. if (!isa<ConstantPlaceHolder>(*I)) {
  718. // Not a placeholder reference.
  719. NewOp = *I;
  720. } else if (*I == Placeholder) {
  721. // Common case is that it just references this one placeholder.
  722. NewOp = RealVal;
  723. } else {
  724. // Otherwise, look up the placeholder in ResolveConstants.
  725. ResolveConstantsTy::iterator It =
  726. std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
  727. std::pair<Constant*, unsigned>(cast<Constant>(*I),
  728. 0));
  729. assert(It != ResolveConstants.end() && It->first == *I);
  730. NewOp = operator[](It->second);
  731. }
  732. NewOps.push_back(cast<Constant>(NewOp));
  733. }
  734. // Make the new constant.
  735. Constant *NewC;
  736. if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
  737. NewC = ConstantArray::get(UserCA->getType(), NewOps);
  738. } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
  739. NewC = ConstantStruct::get(UserCS->getType(), NewOps);
  740. } else if (isa<ConstantVector>(UserC)) {
  741. NewC = ConstantVector::get(NewOps);
  742. } else {
  743. assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
  744. NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
  745. }
  746. UserC->replaceAllUsesWith(NewC);
  747. UserC->destroyConstant();
  748. NewOps.clear();
  749. }
  750. // Update all ValueHandles, they should be the only users at this point.
  751. Placeholder->replaceAllUsesWith(RealVal);
  752. delete Placeholder;
  753. }
  754. }
  755. void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
  756. if (Idx == size()) {
  757. push_back(MD);
  758. return;
  759. }
  760. if (Idx >= size())
  761. resize(Idx+1);
  762. TrackingMDRef &OldMD = MDValuePtrs[Idx];
  763. if (!OldMD) {
  764. OldMD.reset(MD);
  765. return;
  766. }
  767. // If there was a forward reference to this value, replace it.
  768. TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
  769. PrevMD->replaceAllUsesWith(MD);
  770. --NumFwdRefs;
  771. }
  772. Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
  773. if (Idx >= size())
  774. resize(Idx + 1);
  775. if (Metadata *MD = MDValuePtrs[Idx])
  776. return MD;
  777. // Track forward refs to be resolved later.
  778. if (AnyFwdRefs) {
  779. MinFwdRef = std::min(MinFwdRef, Idx);
  780. MaxFwdRef = std::max(MaxFwdRef, Idx);
  781. } else {
  782. AnyFwdRefs = true;
  783. MinFwdRef = MaxFwdRef = Idx;
  784. }
  785. ++NumFwdRefs;
  786. // Create and return a placeholder, which will later be RAUW'd.
  787. Metadata *MD = MDNode::getTemporary(Context, None).release();
  788. MDValuePtrs[Idx].reset(MD);
  789. return MD;
  790. }
  791. void BitcodeReaderMDValueList::tryToResolveCycles() {
  792. if (!AnyFwdRefs)
  793. // Nothing to do.
  794. return;
  795. if (NumFwdRefs)
  796. // Still forward references... can't resolve cycles.
  797. return;
  798. // Resolve any cycles.
  799. for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
  800. auto &MD = MDValuePtrs[I];
  801. auto *N = dyn_cast_or_null<MDNode>(MD);
  802. if (!N)
  803. continue;
  804. assert(!N->isTemporary() && "Unexpected forward reference");
  805. N->resolveCycles();
  806. }
  807. // Make sure we return early again until there's another forward ref.
  808. AnyFwdRefs = false;
  809. }
  810. Type *BitcodeReader::getTypeByID(unsigned ID) {
  811. // The type table size is always specified correctly.
  812. if (ID >= TypeList.size())
  813. return nullptr;
  814. if (Type *Ty = TypeList[ID])
  815. return Ty;
  816. // If we have a forward reference, the only possible case is when it is to a
  817. // named struct. Just create a placeholder for now.
  818. return TypeList[ID] = createIdentifiedStructType(Context);
  819. }
  820. StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
  821. StringRef Name) {
  822. auto *Ret = StructType::create(Context, Name);
  823. IdentifiedStructTypes.push_back(Ret);
  824. return Ret;
  825. }
  826. StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
  827. auto *Ret = StructType::create(Context);
  828. IdentifiedStructTypes.push_back(Ret);
  829. return Ret;
  830. }
  831. //===----------------------------------------------------------------------===//
  832. // Functions for parsing blocks from the bitcode file
  833. //===----------------------------------------------------------------------===//
  834. /// \brief This fills an AttrBuilder object with the LLVM attributes that have
  835. /// been decoded from the given integer. This function must stay in sync with
  836. /// 'encodeLLVMAttributesForBitcode'.
  837. static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
  838. uint64_t EncodedAttrs) {
  839. // FIXME: Remove in 4.0.
  840. // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
  841. // the bits above 31 down by 11 bits.
  842. unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
  843. assert((!Alignment || isPowerOf2_32(Alignment)) &&
  844. "Alignment must be a power of two.");
  845. if (Alignment)
  846. B.addAlignmentAttr(Alignment);
  847. B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
  848. (EncodedAttrs & 0xffff));
  849. }
  850. std::error_code BitcodeReader::ParseAttributeBlock() {
  851. if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
  852. return Error("Invalid record");
  853. if (!MAttributes.empty())
  854. return Error("Invalid multiple blocks");
  855. SmallVector<uint64_t, 64> Record;
  856. SmallVector<AttributeSet, 8> Attrs;
  857. // Read all the records.
  858. while (1) {
  859. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  860. switch (Entry.Kind) {
  861. case BitstreamEntry::SubBlock: // Handled for us already.
  862. case BitstreamEntry::Error:
  863. return Error("Malformed block");
  864. case BitstreamEntry::EndBlock:
  865. return std::error_code();
  866. case BitstreamEntry::Record:
  867. // The interesting case.
  868. break;
  869. }
  870. // Read a record.
  871. Record.clear();
  872. switch (Stream.readRecord(Entry.ID, Record)) {
  873. default: // Default behavior: ignore.
  874. break;
  875. case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
  876. // FIXME: Remove in 4.0.
  877. if (Record.size() & 1)
  878. return Error("Invalid record");
  879. for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
  880. AttrBuilder B;
  881. decodeLLVMAttributesForBitcode(B, Record[i+1]);
  882. Attrs.push_back(AttributeSet::get(Context, Record[i], B));
  883. }
  884. MAttributes.push_back(AttributeSet::get(Context, Attrs));
  885. Attrs.clear();
  886. break;
  887. }
  888. case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
  889. for (unsigned i = 0, e = Record.size(); i != e; ++i)
  890. Attrs.push_back(MAttributeGroups[Record[i]]);
  891. MAttributes.push_back(AttributeSet::get(Context, Attrs));
  892. Attrs.clear();
  893. break;
  894. }
  895. }
  896. }
  897. }
  898. // Returns Attribute::None on unrecognized codes.
  899. static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
  900. switch (Code) {
  901. default:
  902. return Attribute::None;
  903. case bitc::ATTR_KIND_ALIGNMENT:
  904. return Attribute::Alignment;
  905. case bitc::ATTR_KIND_ALWAYS_INLINE:
  906. return Attribute::AlwaysInline;
  907. case bitc::ATTR_KIND_BUILTIN:
  908. return Attribute::Builtin;
  909. case bitc::ATTR_KIND_BY_VAL:
  910. return Attribute::ByVal;
  911. case bitc::ATTR_KIND_IN_ALLOCA:
  912. return Attribute::InAlloca;
  913. case bitc::ATTR_KIND_COLD:
  914. return Attribute::Cold;
  915. case bitc::ATTR_KIND_INLINE_HINT:
  916. return Attribute::InlineHint;
  917. case bitc::ATTR_KIND_IN_REG:
  918. return Attribute::InReg;
  919. case bitc::ATTR_KIND_JUMP_TABLE:
  920. return Attribute::JumpTable;
  921. case bitc::ATTR_KIND_MIN_SIZE:
  922. return Attribute::MinSize;
  923. case bitc::ATTR_KIND_NAKED:
  924. return Attribute::Naked;
  925. case bitc::ATTR_KIND_NEST:
  926. return Attribute::Nest;
  927. case bitc::ATTR_KIND_NO_ALIAS:
  928. return Attribute::NoAlias;
  929. case bitc::ATTR_KIND_NO_BUILTIN:
  930. return Attribute::NoBuiltin;
  931. case bitc::ATTR_KIND_NO_CAPTURE:
  932. return Attribute::NoCapture;
  933. case bitc::ATTR_KIND_NO_DUPLICATE:
  934. return Attribute::NoDuplicate;
  935. case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
  936. return Attribute::NoImplicitFloat;
  937. case bitc::ATTR_KIND_NO_INLINE:
  938. return Attribute::NoInline;
  939. case bitc::ATTR_KIND_NON_LAZY_BIND:
  940. return Attribute::NonLazyBind;
  941. case bitc::ATTR_KIND_NON_NULL:
  942. return Attribute::NonNull;
  943. case bitc::ATTR_KIND_DEREFERENCEABLE:
  944. return Attribute::Dereferenceable;
  945. case bitc::ATTR_KIND_NO_RED_ZONE:
  946. return Attribute::NoRedZone;
  947. case bitc::ATTR_KIND_NO_RETURN:
  948. return Attribute::NoReturn;
  949. case bitc::ATTR_KIND_NO_UNWIND:
  950. return Attribute::NoUnwind;
  951. case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
  952. return Attribute::OptimizeForSize;
  953. case bitc::ATTR_KIND_OPTIMIZE_NONE:
  954. return Attribute::OptimizeNone;
  955. case bitc::ATTR_KIND_READ_NONE:
  956. return Attribute::ReadNone;
  957. case bitc::ATTR_KIND_READ_ONLY:
  958. return Attribute::ReadOnly;
  959. case bitc::ATTR_KIND_RETURNED:
  960. return Attribute::Returned;
  961. case bitc::ATTR_KIND_RETURNS_TWICE:
  962. return Attribute::ReturnsTwice;
  963. case bitc::ATTR_KIND_S_EXT:
  964. return Attribute::SExt;
  965. case bitc::ATTR_KIND_STACK_ALIGNMENT:
  966. return Attribute::StackAlignment;
  967. case bitc::ATTR_KIND_STACK_PROTECT:
  968. return Attribute::StackProtect;
  969. case bitc::ATTR_KIND_STACK_PROTECT_REQ:
  970. return Attribute::StackProtectReq;
  971. case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
  972. return Attribute::StackProtectStrong;
  973. case bitc::ATTR_KIND_STRUCT_RET:
  974. return Attribute::StructRet;
  975. case bitc::ATTR_KIND_SANITIZE_ADDRESS:
  976. return Attribute::SanitizeAddress;
  977. case bitc::ATTR_KIND_SANITIZE_THREAD:
  978. return Attribute::SanitizeThread;
  979. case bitc::ATTR_KIND_SANITIZE_MEMORY:
  980. return Attribute::SanitizeMemory;
  981. case bitc::ATTR_KIND_UW_TABLE:
  982. return Attribute::UWTable;
  983. case bitc::ATTR_KIND_Z_EXT:
  984. return Attribute::ZExt;
  985. }
  986. }
  987. std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
  988. unsigned &Alignment) {
  989. // Note: Alignment in bitcode files is incremented by 1, so that zero
  990. // can be used for default alignment.
  991. if (Exponent > Value::MaxAlignmentExponent + 1)
  992. return Error("Invalid alignment value");
  993. Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
  994. return std::error_code();
  995. }
  996. std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
  997. Attribute::AttrKind *Kind) {
  998. *Kind = GetAttrFromCode(Code);
  999. if (*Kind == Attribute::None)
  1000. return Error(BitcodeError::CorruptedBitcode,
  1001. "Unknown attribute kind (" + Twine(Code) + ")");
  1002. return std::error_code();
  1003. }
  1004. std::error_code BitcodeReader::ParseAttributeGroupBlock() {
  1005. if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
  1006. return Error("Invalid record");
  1007. if (!MAttributeGroups.empty())
  1008. return Error("Invalid multiple blocks");
  1009. SmallVector<uint64_t, 64> Record;
  1010. // Read all the records.
  1011. while (1) {
  1012. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  1013. switch (Entry.Kind) {
  1014. case BitstreamEntry::SubBlock: // Handled for us already.
  1015. case BitstreamEntry::Error:
  1016. return Error("Malformed block");
  1017. case BitstreamEntry::EndBlock:
  1018. return std::error_code();
  1019. case BitstreamEntry::Record:
  1020. // The interesting case.
  1021. break;
  1022. }
  1023. // Read a record.
  1024. Record.clear();
  1025. switch (Stream.readRecord(Entry.ID, Record)) {
  1026. default: // Default behavior: ignore.
  1027. break;
  1028. case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
  1029. if (Record.size() < 3)
  1030. return Error("Invalid record");
  1031. uint64_t GrpID = Record[0];
  1032. uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
  1033. AttrBuilder B;
  1034. for (unsigned i = 2, e = Record.size(); i != e; ++i) {
  1035. if (Record[i] == 0) { // Enum attribute
  1036. Attribute::AttrKind Kind;
  1037. if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
  1038. return EC;
  1039. B.addAttribute(Kind);
  1040. } else if (Record[i] == 1) { // Integer attribute
  1041. Attribute::AttrKind Kind;
  1042. if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
  1043. return EC;
  1044. if (Kind == Attribute::Alignment)
  1045. B.addAlignmentAttr(Record[++i]);
  1046. else if (Kind == Attribute::StackAlignment)
  1047. B.addStackAlignmentAttr(Record[++i]);
  1048. else if (Kind == Attribute::Dereferenceable)
  1049. B.addDereferenceableAttr(Record[++i]);
  1050. } else { // String attribute
  1051. assert((Record[i] == 3 || Record[i] == 4) &&
  1052. "Invalid attribute group entry");
  1053. bool HasValue = (Record[i++] == 4);
  1054. SmallString<64> KindStr;
  1055. SmallString<64> ValStr;
  1056. while (Record[i] != 0 && i != e)
  1057. KindStr += Record[i++];
  1058. assert(Record[i] == 0 && "Kind string not null terminated");
  1059. if (HasValue) {
  1060. // Has a value associated with it.
  1061. ++i; // Skip the '0' that terminates the "kind" string.
  1062. while (Record[i] != 0 && i != e)
  1063. ValStr += Record[i++];
  1064. assert(Record[i] == 0 && "Value string not null terminated");
  1065. }
  1066. B.addAttribute(KindStr.str(), ValStr.str());
  1067. }
  1068. }
  1069. MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
  1070. break;
  1071. }
  1072. }
  1073. }
  1074. }
  1075. std::error_code BitcodeReader::ParseTypeTable() {
  1076. if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
  1077. return Error("Invalid record");
  1078. return ParseTypeTableBody();
  1079. }
  1080. std::error_code BitcodeReader::ParseTypeTableBody() {
  1081. if (!TypeList.empty())
  1082. return Error("Invalid multiple blocks");
  1083. SmallVector<uint64_t, 64> Record;
  1084. unsigned NumRecords = 0;
  1085. SmallString<64> TypeName;
  1086. // Read all the records for this type table.
  1087. while (1) {
  1088. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  1089. switch (Entry.Kind) {
  1090. case BitstreamEntry::SubBlock: // Handled for us already.
  1091. case BitstreamEntry::Error:
  1092. return Error("Malformed block");
  1093. case BitstreamEntry::EndBlock:
  1094. if (NumRecords != TypeList.size())
  1095. return Error("Malformed block");
  1096. return std::error_code();
  1097. case BitstreamEntry::Record:
  1098. // The interesting case.
  1099. break;
  1100. }
  1101. // Read a record.
  1102. Record.clear();
  1103. Type *ResultTy = nullptr;
  1104. switch (Stream.readRecord(Entry.ID, Record)) {
  1105. default:
  1106. return Error("Invalid value");
  1107. case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
  1108. // TYPE_CODE_NUMENTRY contains a count of the number of types in the
  1109. // type list. This allows us to reserve space.
  1110. if (Record.size() < 1)
  1111. return Error("Invalid record");
  1112. TypeList.resize(Record[0]);
  1113. continue;
  1114. case bitc::TYPE_CODE_VOID: // VOID
  1115. ResultTy = Type::getVoidTy(Context);
  1116. break;
  1117. case bitc::TYPE_CODE_HALF: // HALF
  1118. ResultTy = Type::getHalfTy(Context);
  1119. break;
  1120. case bitc::TYPE_CODE_FLOAT: // FLOAT
  1121. ResultTy = Type::getFloatTy(Context);
  1122. break;
  1123. case bitc::TYPE_CODE_DOUBLE: // DOUBLE
  1124. ResultTy = Type::getDoubleTy(Context);
  1125. break;
  1126. case bitc::TYPE_CODE_X86_FP80: // X86_FP80
  1127. ResultTy = Type::getX86_FP80Ty(Context);
  1128. break;
  1129. case bitc::TYPE_CODE_FP128: // FP128
  1130. ResultTy = Type::getFP128Ty(Context);
  1131. break;
  1132. case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
  1133. ResultTy = Type::getPPC_FP128Ty(Context);
  1134. break;
  1135. case bitc::TYPE_CODE_LABEL: // LABEL
  1136. ResultTy = Type::getLabelTy(Context);
  1137. break;
  1138. case bitc::TYPE_CODE_METADATA: // METADATA
  1139. ResultTy = Type::getMetadataTy(Context);
  1140. break;
  1141. case bitc::TYPE_CODE_X86_MMX: // X86_MMX
  1142. ResultTy = Type::getX86_MMXTy(Context);
  1143. break;
  1144. case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
  1145. if (Record.size() < 1)
  1146. return Error("Invalid record");
  1147. uint64_t NumBits = Record[0];
  1148. if (NumBits < IntegerType::MIN_INT_BITS ||
  1149. NumBits > IntegerType::MAX_INT_BITS)
  1150. return Error("Bitwidth for integer type out of range");
  1151. ResultTy = IntegerType::get(Context, NumBits);
  1152. break;
  1153. }
  1154. case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
  1155. // [pointee type, address space]
  1156. if (Record.size() < 1)
  1157. return Error("Invalid record");
  1158. unsigned AddressSpace = 0;
  1159. if (Record.size() == 2)
  1160. AddressSpace = Record[1];
  1161. ResultTy = getTypeByID(Record[0]);
  1162. if (!ResultTy)
  1163. return Error("Invalid type");
  1164. ResultTy = PointerType::get(ResultTy, AddressSpace);
  1165. break;
  1166. }
  1167. case bitc::TYPE_CODE_FUNCTION_OLD: {
  1168. // FIXME: attrid is dead, remove it in LLVM 4.0
  1169. // FUNCTION: [vararg, attrid, retty, paramty x N]
  1170. if (Record.size() < 3)
  1171. return Error("Invalid record");
  1172. SmallVector<Type*, 8> ArgTys;
  1173. for (unsigned i = 3, e = Record.size(); i != e; ++i) {
  1174. if (Type *T = getTypeByID(Record[i]))
  1175. ArgTys.push_back(T);
  1176. else
  1177. break;
  1178. }
  1179. ResultTy = getTypeByID(Record[2]);
  1180. if (!ResultTy || ArgTys.size() < Record.size()-3)
  1181. return Error("Invalid type");
  1182. ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
  1183. break;
  1184. }
  1185. case bitc::TYPE_CODE_FUNCTION: {
  1186. // FUNCTION: [vararg, retty, paramty x N]
  1187. if (Record.size() < 2)
  1188. return Error("Invalid record");
  1189. SmallVector<Type*, 8> ArgTys;
  1190. for (unsigned i = 2, e = Record.size(); i != e; ++i) {
  1191. if (Type *T = getTypeByID(Record[i]))
  1192. ArgTys.push_back(T);
  1193. else
  1194. break;
  1195. }
  1196. ResultTy = getTypeByID(Record[1]);
  1197. if (!ResultTy || ArgTys.size() < Record.size()-2)
  1198. return Error("Invalid type");
  1199. ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
  1200. break;
  1201. }
  1202. case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
  1203. if (Record.size() < 1)
  1204. return Error("Invalid record");
  1205. SmallVector<Type*, 8> EltTys;
  1206. for (unsigned i = 1, e = Record.size(); i != e; ++i) {
  1207. if (Type *T = getTypeByID(Record[i]))
  1208. EltTys.push_back(T);
  1209. else
  1210. break;
  1211. }
  1212. if (EltTys.size() != Record.size()-1)
  1213. return Error("Invalid type");
  1214. ResultTy = StructType::get(Context, EltTys, Record[0]);
  1215. break;
  1216. }
  1217. case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
  1218. if (ConvertToString(Record, 0, TypeName))
  1219. return Error("Invalid record");
  1220. continue;
  1221. case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
  1222. if (Record.size() < 1)
  1223. return Error("Invalid record");
  1224. if (NumRecords >= TypeList.size())
  1225. return Error("Invalid TYPE table");
  1226. // Check to see if this was forward referenced, if so fill in the temp.
  1227. StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
  1228. if (Res) {
  1229. Res->setName(TypeName);
  1230. TypeList[NumRecords] = nullptr;
  1231. } else // Otherwise, create a new struct.
  1232. Res = createIdentifiedStructType(Context, TypeName);
  1233. TypeName.clear();
  1234. SmallVector<Type*, 8> EltTys;
  1235. for (unsigned i = 1, e = Record.size(); i != e; ++i) {
  1236. if (Type *T = getTypeByID(Record[i]))
  1237. EltTys.push_back(T);
  1238. else
  1239. break;
  1240. }
  1241. if (EltTys.size() != Record.size()-1)
  1242. return Error("Invalid record");
  1243. Res->setBody(EltTys, Record[0]);
  1244. ResultTy = Res;
  1245. break;
  1246. }
  1247. case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
  1248. if (Record.size() != 1)
  1249. return Error("Invalid record");
  1250. if (NumRecords >= TypeList.size())
  1251. return Error("Invalid TYPE table");
  1252. // Check to see if this was forward referenced, if so fill in the temp.
  1253. StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
  1254. if (Res) {
  1255. Res->setName(TypeName);
  1256. TypeList[NumRecords] = nullptr;
  1257. } else // Otherwise, create a new struct with no body.
  1258. Res = createIdentifiedStructType(Context, TypeName);
  1259. TypeName.clear();
  1260. ResultTy = Res;
  1261. break;
  1262. }
  1263. case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
  1264. if (Record.size() < 2)
  1265. return Error("Invalid record");
  1266. if ((ResultTy = getTypeByID(Record[1])))
  1267. ResultTy = ArrayType::get(ResultTy, Record[0]);
  1268. else
  1269. return Error("Invalid type");
  1270. break;
  1271. case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
  1272. if (Record.size() < 2)
  1273. return Error("Invalid record");
  1274. if ((ResultTy = getTypeByID(Record[1])))
  1275. ResultTy = VectorType::get(ResultTy, Record[0]);
  1276. else
  1277. return Error("Invalid type");
  1278. break;
  1279. }
  1280. if (NumRecords >= TypeList.size())
  1281. return Error("Invalid TYPE table");
  1282. if (TypeList[NumRecords])
  1283. return Error(
  1284. "Invalid TYPE table: Only named structs can be forward referenced");
  1285. assert(ResultTy && "Didn't read a type?");
  1286. TypeList[NumRecords++] = ResultTy;
  1287. }
  1288. }
  1289. std::error_code BitcodeReader::ParseValueSymbolTable() {
  1290. if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
  1291. return Error("Invalid record");
  1292. SmallVector<uint64_t, 64> Record;
  1293. Triple TT(TheModule->getTargetTriple());
  1294. // Read all the records for this value table.
  1295. SmallString<128> ValueName;
  1296. while (1) {
  1297. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  1298. switch (Entry.Kind) {
  1299. case BitstreamEntry::SubBlock: // Handled for us already.
  1300. case BitstreamEntry::Error:
  1301. return Error("Malformed block");
  1302. case BitstreamEntry::EndBlock:
  1303. return std::error_code();
  1304. case BitstreamEntry::Record:
  1305. // The interesting case.
  1306. break;
  1307. }
  1308. // Read a record.
  1309. Record.clear();
  1310. switch (Stream.readRecord(Entry.ID, Record)) {
  1311. default: // Default behavior: unknown type.
  1312. break;
  1313. case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
  1314. if (ConvertToString(Record, 1, ValueName))
  1315. return Error("Invalid record");
  1316. unsigned ValueID = Record[0];
  1317. if (ValueID >= ValueList.size() || !ValueList[ValueID])
  1318. return Error("Invalid record");
  1319. Value *V = ValueList[ValueID];
  1320. V->setName(StringRef(ValueName.data(), ValueName.size()));
  1321. if (auto *GO = dyn_cast<GlobalObject>(V)) {
  1322. if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
  1323. if (TT.isOSBinFormatMachO())
  1324. GO->setComdat(nullptr);
  1325. else
  1326. GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
  1327. }
  1328. }
  1329. ValueName.clear();
  1330. break;
  1331. }
  1332. case bitc::VST_CODE_BBENTRY: {
  1333. if (ConvertToString(Record, 1, ValueName))
  1334. return Error("Invalid record");
  1335. BasicBlock *BB = getBasicBlock(Record[0]);
  1336. if (!BB)
  1337. return Error("Invalid record");
  1338. BB->setName(StringRef(ValueName.data(), ValueName.size()));
  1339. ValueName.clear();
  1340. break;
  1341. }
  1342. }
  1343. }
  1344. }
  1345. static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
  1346. std::error_code BitcodeReader::ParseMetadata() {
  1347. IsMetadataMaterialized = true;
  1348. unsigned NextMDValueNo = MDValueList.size();
  1349. if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
  1350. return Error("Invalid record");
  1351. SmallVector<uint64_t, 64> Record;
  1352. auto getMD =
  1353. [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
  1354. auto getMDOrNull = [&](unsigned ID) -> Metadata *{
  1355. if (ID)
  1356. return getMD(ID - 1);
  1357. return nullptr;
  1358. };
  1359. auto getMDString = [&](unsigned ID) -> MDString *{
  1360. // This requires that the ID is not really a forward reference. In
  1361. // particular, the MDString must already have been resolved.
  1362. return cast_or_null<MDString>(getMDOrNull(ID));
  1363. };
  1364. #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
  1365. (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
  1366. // Read all the records.
  1367. while (1) {
  1368. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  1369. switch (Entry.Kind) {
  1370. case BitstreamEntry::SubBlock: // Handled for us already.
  1371. case BitstreamEntry::Error:
  1372. return Error("Malformed block");
  1373. case BitstreamEntry::EndBlock:
  1374. MDValueList.tryToResolveCycles();
  1375. return std::error_code();
  1376. case BitstreamEntry::Record:
  1377. // The interesting case.
  1378. break;
  1379. }
  1380. // Read a record.
  1381. Record.clear();
  1382. unsigned Code = Stream.readRecord(Entry.ID, Record);
  1383. bool IsDistinct = false;
  1384. switch (Code) {
  1385. default: // Default behavior: ignore.
  1386. break;
  1387. case bitc::METADATA_NAME: {
  1388. // Read name of the named metadata.
  1389. SmallString<8> Name(Record.begin(), Record.end());
  1390. Record.clear();
  1391. Code = Stream.ReadCode();
  1392. // METADATA_NAME is always followed by METADATA_NAMED_NODE.
  1393. unsigned NextBitCode = Stream.readRecord(Code, Record);
  1394. assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
  1395. // Read named metadata elements.
  1396. unsigned Size = Record.size();
  1397. NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
  1398. for (unsigned i = 0; i != Size; ++i) {
  1399. MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
  1400. if (!MD)
  1401. return Error("Invalid record");
  1402. NMD->addOperand(MD);
  1403. }
  1404. break;
  1405. }
  1406. case bitc::METADATA_OLD_FN_NODE: {
  1407. // FIXME: Remove in 4.0.
  1408. // This is a LocalAsMetadata record, the only type of function-local
  1409. // metadata.
  1410. if (Record.size() % 2 == 1)
  1411. return Error("Invalid record");
  1412. // If this isn't a LocalAsMetadata record, we're dropping it. This used
  1413. // to be legal, but there's no upgrade path.
  1414. auto dropRecord = [&] {
  1415. MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
  1416. };
  1417. if (Record.size() != 2) {
  1418. dropRecord();
  1419. break;
  1420. }
  1421. Type *Ty = getTypeByID(Record[0]);
  1422. if (Ty->isMetadataTy() || Ty->isVoidTy()) {
  1423. dropRecord();
  1424. break;
  1425. }
  1426. MDValueList.AssignValue(
  1427. LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
  1428. NextMDValueNo++);
  1429. break;
  1430. }
  1431. case bitc::METADATA_OLD_NODE: {
  1432. // FIXME: Remove in 4.0.
  1433. if (Record.size() % 2 == 1)
  1434. return Error("Invalid record");
  1435. unsigned Size = Record.size();
  1436. SmallVector<Metadata *, 8> Elts;
  1437. for (unsigned i = 0; i != Size; i += 2) {
  1438. Type *Ty = getTypeByID(Record[i]);
  1439. if (!Ty)
  1440. return Error("Invalid record");
  1441. if (Ty->isMetadataTy())
  1442. Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
  1443. else if (!Ty->isVoidTy()) {
  1444. auto *MD =
  1445. ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
  1446. assert(isa<ConstantAsMetadata>(MD) &&
  1447. "Expected non-function-local metadata");
  1448. Elts.push_back(MD);
  1449. } else
  1450. Elts.push_back(nullptr);
  1451. }
  1452. MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
  1453. break;
  1454. }
  1455. case bitc::METADATA_VALUE: {
  1456. if (Record.size() != 2)
  1457. return Error("Invalid record");
  1458. Type *Ty = getTypeByID(Record[0]);
  1459. if (Ty->isMetadataTy() || Ty->isVoidTy())
  1460. return Error("Invalid record");
  1461. MDValueList.AssignValue(
  1462. ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
  1463. NextMDValueNo++);
  1464. break;
  1465. }
  1466. case bitc::METADATA_DISTINCT_NODE:
  1467. IsDistinct = true;
  1468. // fallthrough...
  1469. case bitc::METADATA_NODE: {
  1470. SmallVector<Metadata *, 8> Elts;
  1471. Elts.reserve(Record.size());
  1472. for (unsigned ID : Record)
  1473. Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
  1474. MDValueList.AssignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
  1475. : MDNode::get(Context, Elts),
  1476. NextMDValueNo++);
  1477. break;
  1478. }
  1479. case bitc::METADATA_LOCATION: {
  1480. if (Record.size() != 5)
  1481. return Error("Invalid record");
  1482. unsigned Line = Record[1];
  1483. unsigned Column = Record[2];
  1484. MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
  1485. Metadata *InlinedAt =
  1486. Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
  1487. MDValueList.AssignValue(
  1488. GET_OR_DISTINCT(MDLocation, Record[0],
  1489. (Context, Line, Column, Scope, InlinedAt)),
  1490. NextMDValueNo++);
  1491. break;
  1492. }
  1493. case bitc::METADATA_GENERIC_DEBUG: {
  1494. if (Record.size() < 4)
  1495. return Error("Invalid record");
  1496. unsigned Tag = Record[1];
  1497. unsigned Version = Record[2];
  1498. if (Tag >= 1u << 16 || Version != 0)
  1499. return Error("Invalid record");
  1500. auto *Header = getMDString(Record[3]);
  1501. SmallVector<Metadata *, 8> DwarfOps;
  1502. for (unsigned I = 4, E = Record.size(); I != E; ++I)
  1503. DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
  1504. : nullptr);
  1505. MDValueList.AssignValue(GET_OR_DISTINCT(GenericDebugNode, Record[0],
  1506. (Context, Tag, Header, DwarfOps)),
  1507. NextMDValueNo++);
  1508. break;
  1509. }
  1510. case bitc::METADATA_SUBRANGE: {
  1511. if (Record.size() != 3)
  1512. return Error("Invalid record");
  1513. MDValueList.AssignValue(
  1514. GET_OR_DISTINCT(MDSubrange, Record[0],
  1515. (Context, Record[1], unrotateSign(Record[2]))),
  1516. NextMDValueNo++);
  1517. break;
  1518. }
  1519. case bitc::METADATA_ENUMERATOR: {
  1520. if (Record.size() != 3)
  1521. return Error("Invalid record");
  1522. MDValueList.AssignValue(GET_OR_DISTINCT(MDEnumerator, Record[0],
  1523. (Context, unrotateSign(Record[1]),
  1524. getMDString(Record[2]))),
  1525. NextMDValueNo++);
  1526. break;
  1527. }
  1528. case bitc::METADATA_BASIC_TYPE: {
  1529. if (Record.size() != 6)
  1530. return Error("Invalid record");
  1531. MDValueList.AssignValue(
  1532. GET_OR_DISTINCT(MDBasicType, Record[0],
  1533. (Context, Record[1], getMDString(Record[2]),
  1534. Record[3], Record[4], Record[5])),
  1535. NextMDValueNo++);
  1536. break;
  1537. }
  1538. case bitc::METADATA_DERIVED_TYPE: {
  1539. if (Record.size() != 12)
  1540. return Error("Invalid record");
  1541. MDValueList.AssignValue(
  1542. GET_OR_DISTINCT(MDDerivedType, Record[0],
  1543. (Context, Record[1], getMDString(Record[2]),
  1544. getMDOrNull(Record[3]), Record[4],
  1545. getMDOrNull(Record[5]), getMDOrNull(Record[6]),
  1546. Record[7], Record[8], Record[9], Record[10],
  1547. getMDOrNull(Record[11]))),
  1548. NextMDValueNo++);
  1549. break;
  1550. }
  1551. case bitc::METADATA_COMPOSITE_TYPE: {
  1552. if (Record.size() != 16)
  1553. return Error("Invalid record");
  1554. MDValueList.AssignValue(
  1555. GET_OR_DISTINCT(MDCompositeType, Record[0],
  1556. (Context, Record[1], getMDString(Record[2]),
  1557. getMDOrNull(Record[3]), Record[4],
  1558. getMDOrNull(Record[5]), getMDOrNull(Record[6]),
  1559. Record[7], Record[8], Record[9], Record[10],
  1560. getMDOrNull(Record[11]), Record[12],
  1561. getMDOrNull(Record[13]), getMDOrNull(Record[14]),
  1562. getMDString(Record[15]))),
  1563. NextMDValueNo++);
  1564. break;
  1565. }
  1566. case bitc::METADATA_SUBROUTINE_TYPE: {
  1567. if (Record.size() != 3)
  1568. return Error("Invalid record");
  1569. MDValueList.AssignValue(
  1570. GET_OR_DISTINCT(MDSubroutineType, Record[0],
  1571. (Context, Record[1], getMDOrNull(Record[2]))),
  1572. NextMDValueNo++);
  1573. break;
  1574. }
  1575. case bitc::METADATA_FILE: {
  1576. if (Record.size() != 3)
  1577. return Error("Invalid record");
  1578. MDValueList.AssignValue(
  1579. GET_OR_DISTINCT(MDFile, Record[0], (Context, getMDString(Record[1]),
  1580. getMDString(Record[2]))),
  1581. NextMDValueNo++);
  1582. break;
  1583. }
  1584. case bitc::METADATA_COMPILE_UNIT: {
  1585. if (Record.size() != 14)
  1586. return Error("Invalid record");
  1587. MDValueList.AssignValue(
  1588. GET_OR_DISTINCT(MDCompileUnit, Record[0],
  1589. (Context, Record[1], getMDOrNull(Record[2]),
  1590. getMDString(Record[3]), Record[4],
  1591. getMDString(Record[5]), Record[6],
  1592. getMDString(Record[7]), Record[8],
  1593. getMDOrNull(Record[9]), getMDOrNull(Record[10]),
  1594. getMDOrNull(Record[11]), getMDOrNull(Record[12]),
  1595. getMDOrNull(Record[13]))),
  1596. NextMDValueNo++);
  1597. break;
  1598. }
  1599. case bitc::METADATA_SUBPROGRAM: {
  1600. if (Record.size() != 19)
  1601. return Error("Invalid record");
  1602. MDValueList.AssignValue(
  1603. GET_OR_DISTINCT(
  1604. MDSubprogram, Record[0],
  1605. (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
  1606. getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
  1607. getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
  1608. getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
  1609. Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
  1610. getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
  1611. NextMDValueNo++);
  1612. break;
  1613. }
  1614. case bitc::METADATA_LEXICAL_BLOCK: {
  1615. if (Record.size() != 5)
  1616. return Error("Invalid record");
  1617. MDValueList.AssignValue(
  1618. GET_OR_DISTINCT(MDLexicalBlock, Record[0],
  1619. (Context, getMDOrNull(Record[1]),
  1620. getMDOrNull(Record[2]), Record[3], Record[4])),
  1621. NextMDValueNo++);
  1622. break;
  1623. }
  1624. case bitc::METADATA_LEXICAL_BLOCK_FILE: {
  1625. if (Record.size() != 4)
  1626. return Error("Invalid record");
  1627. MDValueList.AssignValue(
  1628. GET_OR_DISTINCT(MDLexicalBlockFile, Record[0],
  1629. (Context, getMDOrNull(Record[1]),
  1630. getMDOrNull(Record[2]), Record[3])),
  1631. NextMDValueNo++);
  1632. break;
  1633. }
  1634. case bitc::METADATA_NAMESPACE: {
  1635. if (Record.size() != 5)
  1636. return Error("Invalid record");
  1637. MDValueList.AssignValue(
  1638. GET_OR_DISTINCT(MDNamespace, Record[0],
  1639. (Context, getMDOrNull(Record[1]),
  1640. getMDOrNull(Record[2]), getMDString(Record[3]),
  1641. Record[4])),
  1642. NextMDValueNo++);
  1643. break;
  1644. }
  1645. case bitc::METADATA_TEMPLATE_TYPE: {
  1646. if (Record.size() != 3)
  1647. return Error("Invalid record");
  1648. MDValueList.AssignValue(GET_OR_DISTINCT(MDTemplateTypeParameter,
  1649. Record[0],
  1650. (Context, getMDString(Record[1]),
  1651. getMDOrNull(Record[2]))),
  1652. NextMDValueNo++);
  1653. break;
  1654. }
  1655. case bitc::METADATA_TEMPLATE_VALUE: {
  1656. if (Record.size() != 5)
  1657. return Error("Invalid record");
  1658. MDValueList.AssignValue(
  1659. GET_OR_DISTINCT(MDTemplateValueParameter, Record[0],
  1660. (Context, Record[1], getMDString(Record[2]),
  1661. getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
  1662. NextMDValueNo++);
  1663. break;
  1664. }
  1665. case bitc::METADATA_GLOBAL_VAR: {
  1666. if (Record.size() != 11)
  1667. return Error("Invalid record");
  1668. MDValueList.AssignValue(
  1669. GET_OR_DISTINCT(MDGlobalVariable, Record[0],
  1670. (Context, getMDOrNull(Record[1]),
  1671. getMDString(Record[2]), getMDString(Record[3]),
  1672. getMDOrNull(Record[4]), Record[5],
  1673. getMDOrNull(Record[6]), Record[7], Record[8],
  1674. getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
  1675. NextMDValueNo++);
  1676. break;
  1677. }
  1678. case bitc::METADATA_LOCAL_VAR: {
  1679. if (Record.size() != 10)
  1680. return Error("Invalid record");
  1681. MDValueList.AssignValue(
  1682. GET_OR_DISTINCT(MDLocalVariable, Record[0],
  1683. (Context, Record[1], getMDOrNull(Record[2]),
  1684. getMDString(Record[3]), getMDOrNull(Record[4]),
  1685. Record[5], getMDOrNull(Record[6]), Record[7],
  1686. Record[8], getMDOrNull(Record[9]))),
  1687. NextMDValueNo++);
  1688. break;
  1689. }
  1690. case bitc::METADATA_EXPRESSION: {
  1691. if (Record.size() < 1)
  1692. return Error("Invalid record");
  1693. MDValueList.AssignValue(
  1694. GET_OR_DISTINCT(MDExpression, Record[0],
  1695. (Context, makeArrayRef(Record).slice(1))),
  1696. NextMDValueNo++);
  1697. break;
  1698. }
  1699. case bitc::METADATA_OBJC_PROPERTY: {
  1700. if (Record.size() != 8)
  1701. return Error("Invalid record");
  1702. MDValueList.AssignValue(
  1703. GET_OR_DISTINCT(MDObjCProperty, Record[0],
  1704. (Context, getMDString(Record[1]),
  1705. getMDOrNull(Record[2]), Record[3],
  1706. getMDString(Record[4]), getMDString(Record[5]),
  1707. Record[6], getMDOrNull(Record[7]))),
  1708. NextMDValueNo++);
  1709. break;
  1710. }
  1711. case bitc::METADATA_IMPORTED_ENTITY: {
  1712. if (Record.size() != 6)
  1713. return Error("Invalid record");
  1714. MDValueList.AssignValue(
  1715. GET_OR_DISTINCT(MDImportedEntity, Record[0],
  1716. (Context, Record[1], getMDOrNull(Record[2]),
  1717. getMDOrNull(Record[3]), Record[4],
  1718. getMDString(Record[5]))),
  1719. NextMDValueNo++);
  1720. break;
  1721. }
  1722. case bitc::METADATA_STRING: {
  1723. std::string String(Record.begin(), Record.end());
  1724. llvm::UpgradeMDStringConstant(String);
  1725. Metadata *MD = MDString::get(Context, String);
  1726. MDValueList.AssignValue(MD, NextMDValueNo++);
  1727. break;
  1728. }
  1729. case bitc::METADATA_KIND: {
  1730. if (Record.size() < 2)
  1731. return Error("Invalid record");
  1732. unsigned Kind = Record[0];
  1733. SmallString<8> Name(Record.begin()+1, Record.end());
  1734. unsigned NewKind = TheModule->getMDKindID(Name.str());
  1735. if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
  1736. return Error("Conflicting METADATA_KIND records");
  1737. break;
  1738. }
  1739. }
  1740. }
  1741. #undef GET_OR_DISTINCT
  1742. }
  1743. /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
  1744. /// the LSB for dense VBR encoding.
  1745. uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
  1746. if ((V & 1) == 0)
  1747. return V >> 1;
  1748. if (V != 1)
  1749. return -(V >> 1);
  1750. // There is no such thing as -0 with integers. "-0" really means MININT.
  1751. return 1ULL << 63;
  1752. }
  1753. /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
  1754. /// values and aliases that we can.
  1755. std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
  1756. std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
  1757. std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
  1758. std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
  1759. std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
  1760. GlobalInitWorklist.swap(GlobalInits);
  1761. AliasInitWorklist.swap(AliasInits);
  1762. FunctionPrefixWorklist.swap(FunctionPrefixes);
  1763. FunctionPrologueWorklist.swap(FunctionPrologues);
  1764. while (!GlobalInitWorklist.empty()) {
  1765. unsigned ValID = GlobalInitWorklist.back().second;
  1766. if (ValID >= ValueList.size()) {
  1767. // Not ready to resolve this yet, it requires something later in the file.
  1768. GlobalInits.push_back(GlobalInitWorklist.back());
  1769. } else {
  1770. if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
  1771. GlobalInitWorklist.back().first->setInitializer(C);
  1772. else
  1773. return Error("Expected a constant");
  1774. }
  1775. GlobalInitWorklist.pop_back();
  1776. }
  1777. while (!AliasInitWorklist.empty()) {
  1778. unsigned ValID = AliasInitWorklist.back().second;
  1779. if (ValID >= ValueList.size()) {
  1780. AliasInits.push_back(AliasInitWorklist.back());
  1781. } else {
  1782. if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
  1783. AliasInitWorklist.back().first->setAliasee(C);
  1784. else
  1785. return Error("Expected a constant");
  1786. }
  1787. AliasInitWorklist.pop_back();
  1788. }
  1789. while (!FunctionPrefixWorklist.empty()) {
  1790. unsigned ValID = FunctionPrefixWorklist.back().second;
  1791. if (ValID >= ValueList.size()) {
  1792. FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
  1793. } else {
  1794. if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
  1795. FunctionPrefixWorklist.back().first->setPrefixData(C);
  1796. else
  1797. return Error("Expected a constant");
  1798. }
  1799. FunctionPrefixWorklist.pop_back();
  1800. }
  1801. while (!FunctionPrologueWorklist.empty()) {
  1802. unsigned ValID = FunctionPrologueWorklist.back().second;
  1803. if (ValID >= ValueList.size()) {
  1804. FunctionPrologues.push_back(FunctionPrologueWorklist.back());
  1805. } else {
  1806. if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
  1807. FunctionPrologueWorklist.back().first->setPrologueData(C);
  1808. else
  1809. return Error("Expected a constant");
  1810. }
  1811. FunctionPrologueWorklist.pop_back();
  1812. }
  1813. return std::error_code();
  1814. }
  1815. static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
  1816. SmallVector<uint64_t, 8> Words(Vals.size());
  1817. std::transform(Vals.begin(), Vals.end(), Words.begin(),
  1818. BitcodeReader::decodeSignRotatedValue);
  1819. return APInt(TypeBits, Words);
  1820. }
  1821. std::error_code BitcodeReader::ParseConstants() {
  1822. if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
  1823. return Error("Invalid record");
  1824. SmallVector<uint64_t, 64> Record;
  1825. // Read all the records for this value table.
  1826. Type *CurTy = Type::getInt32Ty(Context);
  1827. unsigned NextCstNo = ValueList.size();
  1828. while (1) {
  1829. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  1830. switch (Entry.Kind) {
  1831. case BitstreamEntry::SubBlock: // Handled for us already.
  1832. case BitstreamEntry::Error:
  1833. return Error("Malformed block");
  1834. case BitstreamEntry::EndBlock:
  1835. if (NextCstNo != ValueList.size())
  1836. return Error("Invalid ronstant reference");
  1837. // Once all the constants have been read, go through and resolve forward
  1838. // references.
  1839. ValueList.ResolveConstantForwardRefs();
  1840. return std::error_code();
  1841. case BitstreamEntry::Record:
  1842. // The interesting case.
  1843. break;
  1844. }
  1845. // Read a record.
  1846. Record.clear();
  1847. Value *V = nullptr;
  1848. unsigned BitCode = Stream.readRecord(Entry.ID, Record);
  1849. switch (BitCode) {
  1850. default: // Default behavior: unknown constant
  1851. case bitc::CST_CODE_UNDEF: // UNDEF
  1852. V = UndefValue::get(CurTy);
  1853. break;
  1854. case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
  1855. if (Record.empty())
  1856. return Error("Invalid record");
  1857. if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
  1858. return Error("Invalid record");
  1859. CurTy = TypeList[Record[0]];
  1860. continue; // Skip the ValueList manipulation.
  1861. case bitc::CST_CODE_NULL: // NULL
  1862. V = Constant::getNullValue(CurTy);
  1863. break;
  1864. case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
  1865. if (!CurTy->isIntegerTy() || Record.empty())
  1866. return Error("Invalid record");
  1867. V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
  1868. break;
  1869. case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
  1870. if (!CurTy->isIntegerTy() || Record.empty())
  1871. return Error("Invalid record");
  1872. APInt VInt = ReadWideAPInt(Record,
  1873. cast<IntegerType>(CurTy)->getBitWidth());
  1874. V = ConstantInt::get(Context, VInt);
  1875. break;
  1876. }
  1877. case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
  1878. if (Record.empty())
  1879. return Error("Invalid record");
  1880. if (CurTy->isHalfTy())
  1881. V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
  1882. APInt(16, (uint16_t)Record[0])));
  1883. else if (CurTy->isFloatTy())
  1884. V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
  1885. APInt(32, (uint32_t)Record[0])));
  1886. else if (CurTy->isDoubleTy())
  1887. V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
  1888. APInt(64, Record[0])));
  1889. else if (CurTy->isX86_FP80Ty()) {
  1890. // Bits are not stored the same way as a normal i80 APInt, compensate.
  1891. uint64_t Rearrange[2];
  1892. Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
  1893. Rearrange[1] = Record[0] >> 48;
  1894. V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
  1895. APInt(80, Rearrange)));
  1896. } else if (CurTy->isFP128Ty())
  1897. V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
  1898. APInt(128, Record)));
  1899. else if (CurTy->isPPC_FP128Ty())
  1900. V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
  1901. APInt(128, Record)));
  1902. else
  1903. V = UndefValue::get(CurTy);
  1904. break;
  1905. }
  1906. case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
  1907. if (Record.empty())
  1908. return Error("Invalid record");
  1909. unsigned Size = Record.size();
  1910. SmallVector<Constant*, 16> Elts;
  1911. if (StructType *STy = dyn_cast<StructType>(CurTy)) {
  1912. for (unsigned i = 0; i != Size; ++i)
  1913. Elts.push_back(ValueList.getConstantFwdRef(Record[i],
  1914. STy->getElementType(i)));
  1915. V = ConstantStruct::get(STy, Elts);
  1916. } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
  1917. Type *EltTy = ATy->getElementType();
  1918. for (unsigned i = 0; i != Size; ++i)
  1919. Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
  1920. V = ConstantArray::get(ATy, Elts);
  1921. } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
  1922. Type *EltTy = VTy->getElementType();
  1923. for (unsigned i = 0; i != Size; ++i)
  1924. Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
  1925. V = ConstantVector::get(Elts);
  1926. } else {
  1927. V = UndefValue::get(CurTy);
  1928. }
  1929. break;
  1930. }
  1931. case bitc::CST_CODE_STRING: // STRING: [values]
  1932. case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
  1933. if (Record.empty())
  1934. return Error("Invalid record");
  1935. SmallString<16> Elts(Record.begin(), Record.end());
  1936. V = ConstantDataArray::getString(Context, Elts,
  1937. BitCode == bitc::CST_CODE_CSTRING);
  1938. break;
  1939. }
  1940. case bitc::CST_CODE_DATA: {// DATA: [n x value]
  1941. if (Record.empty())
  1942. return Error("Invalid record");
  1943. Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
  1944. unsigned Size = Record.size();
  1945. if (EltTy->isIntegerTy(8)) {
  1946. SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
  1947. if (isa<VectorType>(CurTy))
  1948. V = ConstantDataVector::get(Context, Elts);
  1949. else
  1950. V = ConstantDataArray::get(Context, Elts);
  1951. } else if (EltTy->isIntegerTy(16)) {
  1952. SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
  1953. if (isa<VectorType>(CurTy))
  1954. V = ConstantDataVector::get(Context, Elts);
  1955. else
  1956. V = ConstantDataArray::get(Context, Elts);
  1957. } else if (EltTy->isIntegerTy(32)) {
  1958. SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
  1959. if (isa<VectorType>(CurTy))
  1960. V = ConstantDataVector::get(Context, Elts);
  1961. else
  1962. V = ConstantDataArray::get(Context, Elts);
  1963. } else if (EltTy->isIntegerTy(64)) {
  1964. SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
  1965. if (isa<VectorType>(CurTy))
  1966. V = ConstantDataVector::get(Context, Elts);
  1967. else
  1968. V = ConstantDataArray::get(Context, Elts);
  1969. } else if (EltTy->isFloatTy()) {
  1970. SmallVector<float, 16> Elts(Size);
  1971. std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
  1972. if (isa<VectorType>(CurTy))
  1973. V = ConstantDataVector::get(Context, Elts);
  1974. else
  1975. V = ConstantDataArray::get(Context, Elts);
  1976. } else if (EltTy->isDoubleTy()) {
  1977. SmallVector<double, 16> Elts(Size);
  1978. std::transform(Record.begin(), Record.end(), Elts.begin(),
  1979. BitsToDouble);
  1980. if (isa<VectorType>(CurTy))
  1981. V = ConstantDataVector::get(Context, Elts);
  1982. else
  1983. V = ConstantDataArray::get(Context, Elts);
  1984. } else {
  1985. return Error("Invalid type for value");
  1986. }
  1987. break;
  1988. }
  1989. case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
  1990. if (Record.size() < 3)
  1991. return Error("Invalid record");
  1992. int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
  1993. if (Opc < 0) {
  1994. V = UndefValue::get(CurTy); // Unknown binop.
  1995. } else {
  1996. Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
  1997. Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
  1998. unsigned Flags = 0;
  1999. if (Record.size() >= 4) {
  2000. if (Opc == Instruction::Add ||
  2001. Opc == Instruction::Sub ||
  2002. Opc == Instruction::Mul ||
  2003. Opc == Instruction::Shl) {
  2004. if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
  2005. Flags |= OverflowingBinaryOperator::NoSignedWrap;
  2006. if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
  2007. Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
  2008. } else if (Opc == Instruction::SDiv ||
  2009. Opc == Instruction::UDiv ||
  2010. Opc == Instruction::LShr ||
  2011. Opc == Instruction::AShr) {
  2012. if (Record[3] & (1 << bitc::PEO_EXACT))
  2013. Flags |= SDivOperator::IsExact;
  2014. }
  2015. }
  2016. V = ConstantExpr::get(Opc, LHS, RHS, Flags);
  2017. }
  2018. break;
  2019. }
  2020. case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
  2021. if (Record.size() < 3)
  2022. return Error("Invalid record");
  2023. int Opc = GetDecodedCastOpcode(Record[0]);
  2024. if (Opc < 0) {
  2025. V = UndefValue::get(CurTy); // Unknown cast.
  2026. } else {
  2027. Type *OpTy = getTypeByID(Record[1]);
  2028. if (!OpTy)
  2029. return Error("Invalid record");
  2030. Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
  2031. V = UpgradeBitCastExpr(Opc, Op, CurTy);
  2032. if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
  2033. }
  2034. break;
  2035. }
  2036. case bitc::CST_CODE_CE_INBOUNDS_GEP:
  2037. case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
  2038. unsigned OpNum = 0;
  2039. Type *PointeeType = nullptr;
  2040. if (Record.size() % 2)
  2041. PointeeType = getTypeByID(Record[OpNum++]);
  2042. SmallVector<Constant*, 16> Elts;
  2043. while (OpNum != Record.size()) {
  2044. Type *ElTy = getTypeByID(Record[OpNum++]);
  2045. if (!ElTy)
  2046. return Error("Invalid record");
  2047. Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
  2048. }
  2049. ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
  2050. V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
  2051. BitCode ==
  2052. bitc::CST_CODE_CE_INBOUNDS_GEP);
  2053. if (PointeeType &&
  2054. PointeeType != cast<GEPOperator>(V)->getSourceElementType())
  2055. return Error("Explicit gep operator type does not match pointee type "
  2056. "of pointer operand");
  2057. break;
  2058. }
  2059. case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
  2060. if (Record.size() < 3)
  2061. return Error("Invalid record");
  2062. Type *SelectorTy = Type::getInt1Ty(Context);
  2063. // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
  2064. // vector. Otherwise, it must be a single bit.
  2065. if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
  2066. SelectorTy = VectorType::get(Type::getInt1Ty(Context),
  2067. VTy->getNumElements());
  2068. V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
  2069. SelectorTy),
  2070. ValueList.getConstantFwdRef(Record[1],CurTy),
  2071. ValueList.getConstantFwdRef(Record[2],CurTy));
  2072. break;
  2073. }
  2074. case bitc::CST_CODE_CE_EXTRACTELT
  2075. : { // CE_EXTRACTELT: [opty, opval, opty, opval]
  2076. if (Record.size() < 3)
  2077. return Error("Invalid record");
  2078. VectorType *OpTy =
  2079. dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
  2080. if (!OpTy)
  2081. return Error("Invalid record");
  2082. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  2083. Constant *Op1 = nullptr;
  2084. if (Record.size() == 4) {
  2085. Type *IdxTy = getTypeByID(Record[2]);
  2086. if (!IdxTy)
  2087. return Error("Invalid record");
  2088. Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
  2089. } else // TODO: Remove with llvm 4.0
  2090. Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
  2091. if (!Op1)
  2092. return Error("Invalid record");
  2093. V = ConstantExpr::getExtractElement(Op0, Op1);
  2094. break;
  2095. }
  2096. case bitc::CST_CODE_CE_INSERTELT
  2097. : { // CE_INSERTELT: [opval, opval, opty, opval]
  2098. VectorType *OpTy = dyn_cast<VectorType>(CurTy);
  2099. if (Record.size() < 3 || !OpTy)
  2100. return Error("Invalid record");
  2101. Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
  2102. Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
  2103. OpTy->getElementType());
  2104. Constant *Op2 = nullptr;
  2105. if (Record.size() == 4) {
  2106. Type *IdxTy = getTypeByID(Record[2]);
  2107. if (!IdxTy)
  2108. return Error("Invalid record");
  2109. Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
  2110. } else // TODO: Remove with llvm 4.0
  2111. Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
  2112. if (!Op2)
  2113. return Error("Invalid record");
  2114. V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
  2115. break;
  2116. }
  2117. case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
  2118. VectorType *OpTy = dyn_cast<VectorType>(CurTy);
  2119. if (Record.size() < 3 || !OpTy)
  2120. return Error("Invalid record");
  2121. Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
  2122. Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
  2123. Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
  2124. OpTy->getNumElements());
  2125. Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
  2126. V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
  2127. break;
  2128. }
  2129. case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
  2130. VectorType *RTy = dyn_cast<VectorType>(CurTy);
  2131. VectorType *OpTy =
  2132. dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
  2133. if (Record.size() < 4 || !RTy || !OpTy)
  2134. return Error("Invalid record");
  2135. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  2136. Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
  2137. Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
  2138. RTy->getNumElements());
  2139. Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
  2140. V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
  2141. break;
  2142. }
  2143. case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
  2144. if (Record.size() < 4)
  2145. return Error("Invalid record");
  2146. Type *OpTy = getTypeByID(Record[0]);
  2147. if (!OpTy)
  2148. return Error("Invalid record");
  2149. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  2150. Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
  2151. if (OpTy->isFPOrFPVectorTy())
  2152. V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
  2153. else
  2154. V = ConstantExpr::getICmp(Record[3], Op0, Op1);
  2155. break;
  2156. }
  2157. // This maintains backward compatibility, pre-asm dialect keywords.
  2158. // FIXME: Remove with the 4.0 release.
  2159. case bitc::CST_CODE_INLINEASM_OLD: {
  2160. if (Record.size() < 2)
  2161. return Error("Invalid record");
  2162. std::string AsmStr, ConstrStr;
  2163. bool HasSideEffects = Record[0] & 1;
  2164. bool IsAlignStack = Record[0] >> 1;
  2165. unsigned AsmStrSize = Record[1];
  2166. if (2+AsmStrSize >= Record.size())
  2167. return Error("Invalid record");
  2168. unsigned ConstStrSize = Record[2+AsmStrSize];
  2169. if (3+AsmStrSize+ConstStrSize > Record.size())
  2170. return Error("Invalid record");
  2171. for (unsigned i = 0; i != AsmStrSize; ++i)
  2172. AsmStr += (char)Record[2+i];
  2173. for (unsigned i = 0; i != ConstStrSize; ++i)
  2174. ConstrStr += (char)Record[3+AsmStrSize+i];
  2175. PointerType *PTy = cast<PointerType>(CurTy);
  2176. V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
  2177. AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
  2178. break;
  2179. }
  2180. // This version adds support for the asm dialect keywords (e.g.,
  2181. // inteldialect).
  2182. case bitc::CST_CODE_INLINEASM: {
  2183. if (Record.size() < 2)
  2184. return Error("Invalid record");
  2185. std::string AsmStr, ConstrStr;
  2186. bool HasSideEffects = Record[0] & 1;
  2187. bool IsAlignStack = (Record[0] >> 1) & 1;
  2188. unsigned AsmDialect = Record[0] >> 2;
  2189. unsigned AsmStrSize = Record[1];
  2190. if (2+AsmStrSize >= Record.size())
  2191. return Error("Invalid record");
  2192. unsigned ConstStrSize = Record[2+AsmStrSize];
  2193. if (3+AsmStrSize+ConstStrSize > Record.size())
  2194. return Error("Invalid record");
  2195. for (unsigned i = 0; i != AsmStrSize; ++i)
  2196. AsmStr += (char)Record[2+i];
  2197. for (unsigned i = 0; i != ConstStrSize; ++i)
  2198. ConstrStr += (char)Record[3+AsmStrSize+i];
  2199. PointerType *PTy = cast<PointerType>(CurTy);
  2200. V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
  2201. AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
  2202. InlineAsm::AsmDialect(AsmDialect));
  2203. break;
  2204. }
  2205. case bitc::CST_CODE_BLOCKADDRESS:{
  2206. if (Record.size() < 3)
  2207. return Error("Invalid record");
  2208. Type *FnTy = getTypeByID(Record[0]);
  2209. if (!FnTy)
  2210. return Error("Invalid record");
  2211. Function *Fn =
  2212. dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
  2213. if (!Fn)
  2214. return Error("Invalid record");
  2215. // Don't let Fn get dematerialized.
  2216. BlockAddressesTaken.insert(Fn);
  2217. // If the function is already parsed we can insert the block address right
  2218. // away.
  2219. BasicBlock *BB;
  2220. unsigned BBID = Record[2];
  2221. if (!BBID)
  2222. // Invalid reference to entry block.
  2223. return Error("Invalid ID");
  2224. if (!Fn->empty()) {
  2225. Function::iterator BBI = Fn->begin(), BBE = Fn->end();
  2226. for (size_t I = 0, E = BBID; I != E; ++I) {
  2227. if (BBI == BBE)
  2228. return Error("Invalid ID");
  2229. ++BBI;
  2230. }
  2231. BB = BBI;
  2232. } else {
  2233. // Otherwise insert a placeholder and remember it so it can be inserted
  2234. // when the function is parsed.
  2235. auto &FwdBBs = BasicBlockFwdRefs[Fn];
  2236. if (FwdBBs.empty())
  2237. BasicBlockFwdRefQueue.push_back(Fn);
  2238. if (FwdBBs.size() < BBID + 1)
  2239. FwdBBs.resize(BBID + 1);
  2240. if (!FwdBBs[BBID])
  2241. FwdBBs[BBID] = BasicBlock::Create(Context);
  2242. BB = FwdBBs[BBID];
  2243. }
  2244. V = BlockAddress::get(Fn, BB);
  2245. break;
  2246. }
  2247. }
  2248. ValueList.AssignValue(V, NextCstNo);
  2249. ++NextCstNo;
  2250. }
  2251. }
  2252. std::error_code BitcodeReader::ParseUseLists() {
  2253. if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
  2254. return Error("Invalid record");
  2255. // Read all the records.
  2256. SmallVector<uint64_t, 64> Record;
  2257. while (1) {
  2258. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  2259. switch (Entry.Kind) {
  2260. case BitstreamEntry::SubBlock: // Handled for us already.
  2261. case BitstreamEntry::Error:
  2262. return Error("Malformed block");
  2263. case BitstreamEntry::EndBlock:
  2264. return std::error_code();
  2265. case BitstreamEntry::Record:
  2266. // The interesting case.
  2267. break;
  2268. }
  2269. // Read a use list record.
  2270. Record.clear();
  2271. bool IsBB = false;
  2272. switch (Stream.readRecord(Entry.ID, Record)) {
  2273. default: // Default behavior: unknown type.
  2274. break;
  2275. case bitc::USELIST_CODE_BB:
  2276. IsBB = true;
  2277. // fallthrough
  2278. case bitc::USELIST_CODE_DEFAULT: {
  2279. unsigned RecordLength = Record.size();
  2280. if (RecordLength < 3)
  2281. // Records should have at least an ID and two indexes.
  2282. return Error("Invalid record");
  2283. unsigned ID = Record.back();
  2284. Record.pop_back();
  2285. Value *V;
  2286. if (IsBB) {
  2287. assert(ID < FunctionBBs.size() && "Basic block not found");
  2288. V = FunctionBBs[ID];
  2289. } else
  2290. V = ValueList[ID];
  2291. unsigned NumUses = 0;
  2292. SmallDenseMap<const Use *, unsigned, 16> Order;
  2293. for (const Use &U : V->uses()) {
  2294. if (++NumUses > Record.size())
  2295. break;
  2296. Order[&U] = Record[NumUses - 1];
  2297. }
  2298. if (Order.size() != Record.size() || NumUses > Record.size())
  2299. // Mismatches can happen if the functions are being materialized lazily
  2300. // (out-of-order), or a value has been upgraded.
  2301. break;
  2302. V->sortUseList([&](const Use &L, const Use &R) {
  2303. return Order.lookup(&L) < Order.lookup(&R);
  2304. });
  2305. break;
  2306. }
  2307. }
  2308. }
  2309. }
  2310. /// When we see the block for metadata, remember where it is and then skip it.
  2311. /// This lets us lazily deserialize the metadata.
  2312. std::error_code BitcodeReader::rememberAndSkipMetadata() {
  2313. // Save the current stream state.
  2314. uint64_t CurBit = Stream.GetCurrentBitNo();
  2315. DeferredMetadataInfo.push_back(CurBit);
  2316. // Skip over the block for now.
  2317. if (Stream.SkipBlock())
  2318. return Error("Invalid record");
  2319. return std::error_code();
  2320. }
  2321. std::error_code BitcodeReader::materializeMetadata() {
  2322. for (uint64_t BitPos : DeferredMetadataInfo) {
  2323. // Move the bit stream to the saved position.
  2324. Stream.JumpToBit(BitPos);
  2325. if (std::error_code EC = ParseMetadata())
  2326. return EC;
  2327. }
  2328. DeferredMetadataInfo.clear();
  2329. return std::error_code();
  2330. }
  2331. /// RememberAndSkipFunctionBody - When we see the block for a function body,
  2332. /// remember where it is and then skip it. This lets us lazily deserialize the
  2333. /// functions.
  2334. std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
  2335. // Get the function we are talking about.
  2336. if (FunctionsWithBodies.empty())
  2337. return Error("Insufficient function protos");
  2338. Function *Fn = FunctionsWithBodies.back();
  2339. FunctionsWithBodies.pop_back();
  2340. // Save the current stream state.
  2341. uint64_t CurBit = Stream.GetCurrentBitNo();
  2342. DeferredFunctionInfo[Fn] = CurBit;
  2343. // Skip over the function block for now.
  2344. if (Stream.SkipBlock())
  2345. return Error("Invalid record");
  2346. return std::error_code();
  2347. }
  2348. std::error_code BitcodeReader::GlobalCleanup() {
  2349. // Patch the initializers for globals and aliases up.
  2350. ResolveGlobalAndAliasInits();
  2351. if (!GlobalInits.empty() || !AliasInits.empty())
  2352. return Error("Malformed global initializer set");
  2353. // Look for intrinsic functions which need to be upgraded at some point
  2354. for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
  2355. FI != FE; ++FI) {
  2356. Function *NewFn;
  2357. if (UpgradeIntrinsicFunction(FI, NewFn))
  2358. UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
  2359. }
  2360. // Look for global variables which need to be renamed.
  2361. for (Module::global_iterator
  2362. GI = TheModule->global_begin(), GE = TheModule->global_end();
  2363. GI != GE;) {
  2364. GlobalVariable *GV = GI++;
  2365. UpgradeGlobalVariable(GV);
  2366. }
  2367. // Force deallocation of memory for these vectors to favor the client that
  2368. // want lazy deserialization.
  2369. std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
  2370. std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
  2371. return std::error_code();
  2372. }
  2373. std::error_code BitcodeReader::ParseModule(bool Resume,
  2374. bool ShouldLazyLoadMetadata) {
  2375. if (Resume)
  2376. Stream.JumpToBit(NextUnreadBit);
  2377. else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
  2378. return Error("Invalid record");
  2379. SmallVector<uint64_t, 64> Record;
  2380. std::vector<std::string> SectionTable;
  2381. std::vector<std::string> GCTable;
  2382. // Read all the records for this module.
  2383. while (1) {
  2384. BitstreamEntry Entry = Stream.advance();
  2385. switch (Entry.Kind) {
  2386. case BitstreamEntry::Error:
  2387. return Error("Malformed block");
  2388. case BitstreamEntry::EndBlock:
  2389. return GlobalCleanup();
  2390. case BitstreamEntry::SubBlock:
  2391. switch (Entry.ID) {
  2392. default: // Skip unknown content.
  2393. if (Stream.SkipBlock())
  2394. return Error("Invalid record");
  2395. break;
  2396. case bitc::BLOCKINFO_BLOCK_ID:
  2397. if (Stream.ReadBlockInfoBlock())
  2398. return Error("Malformed block");
  2399. break;
  2400. case bitc::PARAMATTR_BLOCK_ID:
  2401. if (std::error_code EC = ParseAttributeBlock())
  2402. return EC;
  2403. break;
  2404. case bitc::PARAMATTR_GROUP_BLOCK_ID:
  2405. if (std::error_code EC = ParseAttributeGroupBlock())
  2406. return EC;
  2407. break;
  2408. case bitc::TYPE_BLOCK_ID_NEW:
  2409. if (std::error_code EC = ParseTypeTable())
  2410. return EC;
  2411. break;
  2412. case bitc::VALUE_SYMTAB_BLOCK_ID:
  2413. if (std::error_code EC = ParseValueSymbolTable())
  2414. return EC;
  2415. SeenValueSymbolTable = true;
  2416. break;
  2417. case bitc::CONSTANTS_BLOCK_ID:
  2418. if (std::error_code EC = ParseConstants())
  2419. return EC;
  2420. if (std::error_code EC = ResolveGlobalAndAliasInits())
  2421. return EC;
  2422. break;
  2423. case bitc::METADATA_BLOCK_ID:
  2424. if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
  2425. if (std::error_code EC = rememberAndSkipMetadata())
  2426. return EC;
  2427. break;
  2428. }
  2429. assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
  2430. if (std::error_code EC = ParseMetadata())
  2431. return EC;
  2432. break;
  2433. case bitc::FUNCTION_BLOCK_ID:
  2434. // If this is the first function body we've seen, reverse the
  2435. // FunctionsWithBodies list.
  2436. if (!SeenFirstFunctionBody) {
  2437. std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
  2438. if (std::error_code EC = GlobalCleanup())
  2439. return EC;
  2440. SeenFirstFunctionBody = true;
  2441. }
  2442. if (std::error_code EC = RememberAndSkipFunctionBody())
  2443. return EC;
  2444. // For streaming bitcode, suspend parsing when we reach the function
  2445. // bodies. Subsequent materialization calls will resume it when
  2446. // necessary. For streaming, the function bodies must be at the end of
  2447. // the bitcode. If the bitcode file is old, the symbol table will be
  2448. // at the end instead and will not have been seen yet. In this case,
  2449. // just finish the parse now.
  2450. if (LazyStreamer && SeenValueSymbolTable) {
  2451. NextUnreadBit = Stream.GetCurrentBitNo();
  2452. return std::error_code();
  2453. }
  2454. break;
  2455. case bitc::USELIST_BLOCK_ID:
  2456. if (std::error_code EC = ParseUseLists())
  2457. return EC;
  2458. break;
  2459. }
  2460. continue;
  2461. case BitstreamEntry::Record:
  2462. // The interesting case.
  2463. break;
  2464. }
  2465. // Read a record.
  2466. switch (Stream.readRecord(Entry.ID, Record)) {
  2467. default: break; // Default behavior, ignore unknown content.
  2468. case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
  2469. if (Record.size() < 1)
  2470. return Error("Invalid record");
  2471. // Only version #0 and #1 are supported so far.
  2472. unsigned module_version = Record[0];
  2473. switch (module_version) {
  2474. default:
  2475. return Error("Invalid value");
  2476. case 0:
  2477. UseRelativeIDs = false;
  2478. break;
  2479. case 1:
  2480. UseRelativeIDs = true;
  2481. break;
  2482. }
  2483. break;
  2484. }
  2485. case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
  2486. std::string S;
  2487. if (ConvertToString(Record, 0, S))
  2488. return Error("Invalid record");
  2489. TheModule->setTargetTriple(S);
  2490. break;
  2491. }
  2492. case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
  2493. std::string S;
  2494. if (ConvertToString(Record, 0, S))
  2495. return Error("Invalid record");
  2496. TheModule->setDataLayout(S);
  2497. break;
  2498. }
  2499. case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
  2500. std::string S;
  2501. if (ConvertToString(Record, 0, S))
  2502. return Error("Invalid record");
  2503. TheModule->setModuleInlineAsm(S);
  2504. break;
  2505. }
  2506. case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
  2507. // FIXME: Remove in 4.0.
  2508. std::string S;
  2509. if (ConvertToString(Record, 0, S))
  2510. return Error("Invalid record");
  2511. // Ignore value.
  2512. break;
  2513. }
  2514. case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
  2515. std::string S;
  2516. if (ConvertToString(Record, 0, S))
  2517. return Error("Invalid record");
  2518. SectionTable.push_back(S);
  2519. break;
  2520. }
  2521. case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
  2522. std::string S;
  2523. if (ConvertToString(Record, 0, S))
  2524. return Error("Invalid record");
  2525. GCTable.push_back(S);
  2526. break;
  2527. }
  2528. case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
  2529. if (Record.size() < 2)
  2530. return Error("Invalid record");
  2531. Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
  2532. unsigned ComdatNameSize = Record[1];
  2533. std::string ComdatName;
  2534. ComdatName.reserve(ComdatNameSize);
  2535. for (unsigned i = 0; i != ComdatNameSize; ++i)
  2536. ComdatName += (char)Record[2 + i];
  2537. Comdat *C = TheModule->getOrInsertComdat(ComdatName);
  2538. C->setSelectionKind(SK);
  2539. ComdatList.push_back(C);
  2540. break;
  2541. }
  2542. // GLOBALVAR: [pointer type, isconst, initid,
  2543. // linkage, alignment, section, visibility, threadlocal,
  2544. // unnamed_addr, externally_initialized, dllstorageclass,
  2545. // comdat]
  2546. case bitc::MODULE_CODE_GLOBALVAR: {
  2547. if (Record.size() < 6)
  2548. return Error("Invalid record");
  2549. Type *Ty = getTypeByID(Record[0]);
  2550. if (!Ty)
  2551. return Error("Invalid record");
  2552. if (!Ty->isPointerTy())
  2553. return Error("Invalid type for value");
  2554. unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
  2555. Ty = cast<PointerType>(Ty)->getElementType();
  2556. bool isConstant = Record[1];
  2557. uint64_t RawLinkage = Record[3];
  2558. GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
  2559. unsigned Alignment;
  2560. if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
  2561. return EC;
  2562. std::string Section;
  2563. if (Record[5]) {
  2564. if (Record[5]-1 >= SectionTable.size())
  2565. return Error("Invalid ID");
  2566. Section = SectionTable[Record[5]-1];
  2567. }
  2568. GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
  2569. // Local linkage must have default visibility.
  2570. if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
  2571. // FIXME: Change to an error if non-default in 4.0.
  2572. Visibility = GetDecodedVisibility(Record[6]);
  2573. GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
  2574. if (Record.size() > 7)
  2575. TLM = GetDecodedThreadLocalMode(Record[7]);
  2576. bool UnnamedAddr = false;
  2577. if (Record.size() > 8)
  2578. UnnamedAddr = Record[8];
  2579. bool ExternallyInitialized = false;
  2580. if (Record.size() > 9)
  2581. ExternallyInitialized = Record[9];
  2582. GlobalVariable *NewGV =
  2583. new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
  2584. TLM, AddressSpace, ExternallyInitialized);
  2585. NewGV->setAlignment(Alignment);
  2586. if (!Section.empty())
  2587. NewGV->setSection(Section);
  2588. NewGV->setVisibility(Visibility);
  2589. NewGV->setUnnamedAddr(UnnamedAddr);
  2590. if (Record.size() > 10)
  2591. NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
  2592. else
  2593. UpgradeDLLImportExportLinkage(NewGV, RawLinkage);
  2594. ValueList.push_back(NewGV);
  2595. // Remember which value to use for the global initializer.
  2596. if (unsigned InitID = Record[2])
  2597. GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
  2598. if (Record.size() > 11) {
  2599. if (unsigned ComdatID = Record[11]) {
  2600. assert(ComdatID <= ComdatList.size());
  2601. NewGV->setComdat(ComdatList[ComdatID - 1]);
  2602. }
  2603. } else if (hasImplicitComdat(RawLinkage)) {
  2604. NewGV->setComdat(reinterpret_cast<Comdat *>(1));
  2605. }
  2606. break;
  2607. }
  2608. // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
  2609. // alignment, section, visibility, gc, unnamed_addr,
  2610. // prologuedata, dllstorageclass, comdat, prefixdata]
  2611. case bitc::MODULE_CODE_FUNCTION: {
  2612. if (Record.size() < 8)
  2613. return Error("Invalid record");
  2614. Type *Ty = getTypeByID(Record[0]);
  2615. if (!Ty)
  2616. return Error("Invalid record");
  2617. if (!Ty->isPointerTy())
  2618. return Error("Invalid type for value");
  2619. FunctionType *FTy =
  2620. dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
  2621. if (!FTy)
  2622. return Error("Invalid type for value");
  2623. Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
  2624. "", TheModule);
  2625. Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
  2626. bool isProto = Record[2];
  2627. uint64_t RawLinkage = Record[3];
  2628. Func->setLinkage(getDecodedLinkage(RawLinkage));
  2629. Func->setAttributes(getAttributes(Record[4]));
  2630. unsigned Alignment;
  2631. if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
  2632. return EC;
  2633. Func->setAlignment(Alignment);
  2634. if (Record[6]) {
  2635. if (Record[6]-1 >= SectionTable.size())
  2636. return Error("Invalid ID");
  2637. Func->setSection(SectionTable[Record[6]-1]);
  2638. }
  2639. // Local linkage must have default visibility.
  2640. if (!Func->hasLocalLinkage())
  2641. // FIXME: Change to an error if non-default in 4.0.
  2642. Func->setVisibility(GetDecodedVisibility(Record[7]));
  2643. if (Record.size() > 8 && Record[8]) {
  2644. if (Record[8]-1 > GCTable.size())
  2645. return Error("Invalid ID");
  2646. Func->setGC(GCTable[Record[8]-1].c_str());
  2647. }
  2648. bool UnnamedAddr = false;
  2649. if (Record.size() > 9)
  2650. UnnamedAddr = Record[9];
  2651. Func->setUnnamedAddr(UnnamedAddr);
  2652. if (Record.size() > 10 && Record[10] != 0)
  2653. FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
  2654. if (Record.size() > 11)
  2655. Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
  2656. else
  2657. UpgradeDLLImportExportLinkage(Func, RawLinkage);
  2658. if (Record.size() > 12) {
  2659. if (unsigned ComdatID = Record[12]) {
  2660. assert(ComdatID <= ComdatList.size());
  2661. Func->setComdat(ComdatList[ComdatID - 1]);
  2662. }
  2663. } else if (hasImplicitComdat(RawLinkage)) {
  2664. Func->setComdat(reinterpret_cast<Comdat *>(1));
  2665. }
  2666. if (Record.size() > 13 && Record[13] != 0)
  2667. FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
  2668. ValueList.push_back(Func);
  2669. // If this is a function with a body, remember the prototype we are
  2670. // creating now, so that we can match up the body with them later.
  2671. if (!isProto) {
  2672. Func->setIsMaterializable(true);
  2673. FunctionsWithBodies.push_back(Func);
  2674. if (LazyStreamer)
  2675. DeferredFunctionInfo[Func] = 0;
  2676. }
  2677. break;
  2678. }
  2679. // ALIAS: [alias type, aliasee val#, linkage]
  2680. // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
  2681. case bitc::MODULE_CODE_ALIAS: {
  2682. if (Record.size() < 3)
  2683. return Error("Invalid record");
  2684. Type *Ty = getTypeByID(Record[0]);
  2685. if (!Ty)
  2686. return Error("Invalid record");
  2687. auto *PTy = dyn_cast<PointerType>(Ty);
  2688. if (!PTy)
  2689. return Error("Invalid type for value");
  2690. auto *NewGA =
  2691. GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
  2692. getDecodedLinkage(Record[2]), "", TheModule);
  2693. // Old bitcode files didn't have visibility field.
  2694. // Local linkage must have default visibility.
  2695. if (Record.size() > 3 && !NewGA->hasLocalLinkage())
  2696. // FIXME: Change to an error if non-default in 4.0.
  2697. NewGA->setVisibility(GetDecodedVisibility(Record[3]));
  2698. if (Record.size() > 4)
  2699. NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
  2700. else
  2701. UpgradeDLLImportExportLinkage(NewGA, Record[2]);
  2702. if (Record.size() > 5)
  2703. NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
  2704. if (Record.size() > 6)
  2705. NewGA->setUnnamedAddr(Record[6]);
  2706. ValueList.push_back(NewGA);
  2707. AliasInits.push_back(std::make_pair(NewGA, Record[1]));
  2708. break;
  2709. }
  2710. /// MODULE_CODE_PURGEVALS: [numvals]
  2711. case bitc::MODULE_CODE_PURGEVALS:
  2712. // Trim down the value list to the specified size.
  2713. if (Record.size() < 1 || Record[0] > ValueList.size())
  2714. return Error("Invalid record");
  2715. ValueList.shrinkTo(Record[0]);
  2716. break;
  2717. }
  2718. Record.clear();
  2719. }
  2720. }
  2721. std::error_code BitcodeReader::ParseBitcodeInto(Module *M,
  2722. bool ShouldLazyLoadMetadata) {
  2723. TheModule = nullptr;
  2724. if (std::error_code EC = InitStream())
  2725. return EC;
  2726. // Sniff for the signature.
  2727. if (Stream.Read(8) != 'B' ||
  2728. Stream.Read(8) != 'C' ||
  2729. Stream.Read(4) != 0x0 ||
  2730. Stream.Read(4) != 0xC ||
  2731. Stream.Read(4) != 0xE ||
  2732. Stream.Read(4) != 0xD)
  2733. return Error("Invalid bitcode signature");
  2734. // We expect a number of well-defined blocks, though we don't necessarily
  2735. // need to understand them all.
  2736. while (1) {
  2737. if (Stream.AtEndOfStream())
  2738. return std::error_code();
  2739. BitstreamEntry Entry =
  2740. Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
  2741. switch (Entry.Kind) {
  2742. case BitstreamEntry::Error:
  2743. return Error("Malformed block");
  2744. case BitstreamEntry::EndBlock:
  2745. return std::error_code();
  2746. case BitstreamEntry::SubBlock:
  2747. switch (Entry.ID) {
  2748. case bitc::BLOCKINFO_BLOCK_ID:
  2749. if (Stream.ReadBlockInfoBlock())
  2750. return Error("Malformed block");
  2751. break;
  2752. case bitc::MODULE_BLOCK_ID:
  2753. // Reject multiple MODULE_BLOCK's in a single bitstream.
  2754. if (TheModule)
  2755. return Error("Invalid multiple blocks");
  2756. TheModule = M;
  2757. if (std::error_code EC = ParseModule(false, ShouldLazyLoadMetadata))
  2758. return EC;
  2759. if (LazyStreamer)
  2760. return std::error_code();
  2761. break;
  2762. default:
  2763. if (Stream.SkipBlock())
  2764. return Error("Invalid record");
  2765. break;
  2766. }
  2767. continue;
  2768. case BitstreamEntry::Record:
  2769. // There should be no records in the top-level of blocks.
  2770. // The ranlib in Xcode 4 will align archive members by appending newlines
  2771. // to the end of them. If this file size is a multiple of 4 but not 8, we
  2772. // have to read and ignore these final 4 bytes :-(
  2773. if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
  2774. Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
  2775. Stream.AtEndOfStream())
  2776. return std::error_code();
  2777. return Error("Invalid record");
  2778. }
  2779. }
  2780. }
  2781. ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
  2782. if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
  2783. return Error("Invalid record");
  2784. SmallVector<uint64_t, 64> Record;
  2785. std::string Triple;
  2786. // Read all the records for this module.
  2787. while (1) {
  2788. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  2789. switch (Entry.Kind) {
  2790. case BitstreamEntry::SubBlock: // Handled for us already.
  2791. case BitstreamEntry::Error:
  2792. return Error("Malformed block");
  2793. case BitstreamEntry::EndBlock:
  2794. return Triple;
  2795. case BitstreamEntry::Record:
  2796. // The interesting case.
  2797. break;
  2798. }
  2799. // Read a record.
  2800. switch (Stream.readRecord(Entry.ID, Record)) {
  2801. default: break; // Default behavior, ignore unknown content.
  2802. case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
  2803. std::string S;
  2804. if (ConvertToString(Record, 0, S))
  2805. return Error("Invalid record");
  2806. Triple = S;
  2807. break;
  2808. }
  2809. }
  2810. Record.clear();
  2811. }
  2812. llvm_unreachable("Exit infinite loop");
  2813. }
  2814. ErrorOr<std::string> BitcodeReader::parseTriple() {
  2815. if (std::error_code EC = InitStream())
  2816. return EC;
  2817. // Sniff for the signature.
  2818. if (Stream.Read(8) != 'B' ||
  2819. Stream.Read(8) != 'C' ||
  2820. Stream.Read(4) != 0x0 ||
  2821. Stream.Read(4) != 0xC ||
  2822. Stream.Read(4) != 0xE ||
  2823. Stream.Read(4) != 0xD)
  2824. return Error("Invalid bitcode signature");
  2825. // We expect a number of well-defined blocks, though we don't necessarily
  2826. // need to understand them all.
  2827. while (1) {
  2828. BitstreamEntry Entry = Stream.advance();
  2829. switch (Entry.Kind) {
  2830. case BitstreamEntry::Error:
  2831. return Error("Malformed block");
  2832. case BitstreamEntry::EndBlock:
  2833. return std::error_code();
  2834. case BitstreamEntry::SubBlock:
  2835. if (Entry.ID == bitc::MODULE_BLOCK_ID)
  2836. return parseModuleTriple();
  2837. // Ignore other sub-blocks.
  2838. if (Stream.SkipBlock())
  2839. return Error("Malformed block");
  2840. continue;
  2841. case BitstreamEntry::Record:
  2842. Stream.skipRecord(Entry.ID);
  2843. continue;
  2844. }
  2845. }
  2846. }
  2847. /// ParseMetadataAttachment - Parse metadata attachments.
  2848. std::error_code BitcodeReader::ParseMetadataAttachment() {
  2849. if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
  2850. return Error("Invalid record");
  2851. SmallVector<uint64_t, 64> Record;
  2852. while (1) {
  2853. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  2854. switch (Entry.Kind) {
  2855. case BitstreamEntry::SubBlock: // Handled for us already.
  2856. case BitstreamEntry::Error:
  2857. return Error("Malformed block");
  2858. case BitstreamEntry::EndBlock:
  2859. return std::error_code();
  2860. case BitstreamEntry::Record:
  2861. // The interesting case.
  2862. break;
  2863. }
  2864. // Read a metadata attachment record.
  2865. Record.clear();
  2866. switch (Stream.readRecord(Entry.ID, Record)) {
  2867. default: // Default behavior: ignore.
  2868. break;
  2869. case bitc::METADATA_ATTACHMENT: {
  2870. unsigned RecordLength = Record.size();
  2871. if (Record.empty() || (RecordLength - 1) % 2 == 1)
  2872. return Error("Invalid record");
  2873. Instruction *Inst = InstructionList[Record[0]];
  2874. for (unsigned i = 1; i != RecordLength; i = i+2) {
  2875. unsigned Kind = Record[i];
  2876. DenseMap<unsigned, unsigned>::iterator I =
  2877. MDKindMap.find(Kind);
  2878. if (I == MDKindMap.end())
  2879. return Error("Invalid ID");
  2880. Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
  2881. if (isa<LocalAsMetadata>(Node))
  2882. // Drop the attachment. This used to be legal, but there's no
  2883. // upgrade path.
  2884. break;
  2885. Inst->setMetadata(I->second, cast<MDNode>(Node));
  2886. if (I->second == LLVMContext::MD_tbaa)
  2887. InstsWithTBAATag.push_back(Inst);
  2888. }
  2889. break;
  2890. }
  2891. }
  2892. }
  2893. }
  2894. /// ParseFunctionBody - Lazily parse the specified function body block.
  2895. std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
  2896. if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
  2897. return Error("Invalid record");
  2898. InstructionList.clear();
  2899. unsigned ModuleValueListSize = ValueList.size();
  2900. unsigned ModuleMDValueListSize = MDValueList.size();
  2901. // Add all the function arguments to the value table.
  2902. for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
  2903. ValueList.push_back(I);
  2904. unsigned NextValueNo = ValueList.size();
  2905. BasicBlock *CurBB = nullptr;
  2906. unsigned CurBBNo = 0;
  2907. DebugLoc LastLoc;
  2908. auto getLastInstruction = [&]() -> Instruction * {
  2909. if (CurBB && !CurBB->empty())
  2910. return &CurBB->back();
  2911. else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
  2912. !FunctionBBs[CurBBNo - 1]->empty())
  2913. return &FunctionBBs[CurBBNo - 1]->back();
  2914. return nullptr;
  2915. };
  2916. // Read all the records.
  2917. SmallVector<uint64_t, 64> Record;
  2918. while (1) {
  2919. BitstreamEntry Entry = Stream.advance();
  2920. switch (Entry.Kind) {
  2921. case BitstreamEntry::Error:
  2922. return Error("Malformed block");
  2923. case BitstreamEntry::EndBlock:
  2924. goto OutOfRecordLoop;
  2925. case BitstreamEntry::SubBlock:
  2926. switch (Entry.ID) {
  2927. default: // Skip unknown content.
  2928. if (Stream.SkipBlock())
  2929. return Error("Invalid record");
  2930. break;
  2931. case bitc::CONSTANTS_BLOCK_ID:
  2932. if (std::error_code EC = ParseConstants())
  2933. return EC;
  2934. NextValueNo = ValueList.size();
  2935. break;
  2936. case bitc::VALUE_SYMTAB_BLOCK_ID:
  2937. if (std::error_code EC = ParseValueSymbolTable())
  2938. return EC;
  2939. break;
  2940. case bitc::METADATA_ATTACHMENT_ID:
  2941. if (std::error_code EC = ParseMetadataAttachment())
  2942. return EC;
  2943. break;
  2944. case bitc::METADATA_BLOCK_ID:
  2945. if (std::error_code EC = ParseMetadata())
  2946. return EC;
  2947. break;
  2948. case bitc::USELIST_BLOCK_ID:
  2949. if (std::error_code EC = ParseUseLists())
  2950. return EC;
  2951. break;
  2952. }
  2953. continue;
  2954. case BitstreamEntry::Record:
  2955. // The interesting case.
  2956. break;
  2957. }
  2958. // Read a record.
  2959. Record.clear();
  2960. Instruction *I = nullptr;
  2961. unsigned BitCode = Stream.readRecord(Entry.ID, Record);
  2962. switch (BitCode) {
  2963. default: // Default behavior: reject
  2964. return Error("Invalid value");
  2965. case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
  2966. if (Record.size() < 1 || Record[0] == 0)
  2967. return Error("Invalid record");
  2968. // Create all the basic blocks for the function.
  2969. FunctionBBs.resize(Record[0]);
  2970. // See if anything took the address of blocks in this function.
  2971. auto BBFRI = BasicBlockFwdRefs.find(F);
  2972. if (BBFRI == BasicBlockFwdRefs.end()) {
  2973. for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
  2974. FunctionBBs[i] = BasicBlock::Create(Context, "", F);
  2975. } else {
  2976. auto &BBRefs = BBFRI->second;
  2977. // Check for invalid basic block references.
  2978. if (BBRefs.size() > FunctionBBs.size())
  2979. return Error("Invalid ID");
  2980. assert(!BBRefs.empty() && "Unexpected empty array");
  2981. assert(!BBRefs.front() && "Invalid reference to entry block");
  2982. for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
  2983. ++I)
  2984. if (I < RE && BBRefs[I]) {
  2985. BBRefs[I]->insertInto(F);
  2986. FunctionBBs[I] = BBRefs[I];
  2987. } else {
  2988. FunctionBBs[I] = BasicBlock::Create(Context, "", F);
  2989. }
  2990. // Erase from the table.
  2991. BasicBlockFwdRefs.erase(BBFRI);
  2992. }
  2993. CurBB = FunctionBBs[0];
  2994. continue;
  2995. }
  2996. case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
  2997. // This record indicates that the last instruction is at the same
  2998. // location as the previous instruction with a location.
  2999. I = getLastInstruction();
  3000. if (!I)
  3001. return Error("Invalid record");
  3002. I->setDebugLoc(LastLoc);
  3003. I = nullptr;
  3004. continue;
  3005. case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
  3006. I = getLastInstruction();
  3007. if (!I || Record.size() < 4)
  3008. return Error("Invalid record");
  3009. unsigned Line = Record[0], Col = Record[1];
  3010. unsigned ScopeID = Record[2], IAID = Record[3];
  3011. MDNode *Scope = nullptr, *IA = nullptr;
  3012. if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
  3013. if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
  3014. LastLoc = DebugLoc::get(Line, Col, Scope, IA);
  3015. I->setDebugLoc(LastLoc);
  3016. I = nullptr;
  3017. continue;
  3018. }
  3019. case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
  3020. unsigned OpNum = 0;
  3021. Value *LHS, *RHS;
  3022. if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
  3023. popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
  3024. OpNum+1 > Record.size())
  3025. return Error("Invalid record");
  3026. int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
  3027. if (Opc == -1)
  3028. return Error("Invalid record");
  3029. I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
  3030. InstructionList.push_back(I);
  3031. if (OpNum < Record.size()) {
  3032. if (Opc == Instruction::Add ||
  3033. Opc == Instruction::Sub ||
  3034. Opc == Instruction::Mul ||
  3035. Opc == Instruction::Shl) {
  3036. if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
  3037. cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
  3038. if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
  3039. cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
  3040. } else if (Opc == Instruction::SDiv ||
  3041. Opc == Instruction::UDiv ||
  3042. Opc == Instruction::LShr ||
  3043. Opc == Instruction::AShr) {
  3044. if (Record[OpNum] & (1 << bitc::PEO_EXACT))
  3045. cast<BinaryOperator>(I)->setIsExact(true);
  3046. } else if (isa<FPMathOperator>(I)) {
  3047. FastMathFlags FMF;
  3048. if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
  3049. FMF.setUnsafeAlgebra();
  3050. if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
  3051. FMF.setNoNaNs();
  3052. if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
  3053. FMF.setNoInfs();
  3054. if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
  3055. FMF.setNoSignedZeros();
  3056. if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
  3057. FMF.setAllowReciprocal();
  3058. if (FMF.any())
  3059. I->setFastMathFlags(FMF);
  3060. }
  3061. }
  3062. break;
  3063. }
  3064. case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
  3065. unsigned OpNum = 0;
  3066. Value *Op;
  3067. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  3068. OpNum+2 != Record.size())
  3069. return Error("Invalid record");
  3070. Type *ResTy = getTypeByID(Record[OpNum]);
  3071. int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
  3072. if (Opc == -1 || !ResTy)
  3073. return Error("Invalid record");
  3074. Instruction *Temp = nullptr;
  3075. if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
  3076. if (Temp) {
  3077. InstructionList.push_back(Temp);
  3078. CurBB->getInstList().push_back(Temp);
  3079. }
  3080. } else {
  3081. I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
  3082. }
  3083. InstructionList.push_back(I);
  3084. break;
  3085. }
  3086. case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
  3087. case bitc::FUNC_CODE_INST_GEP_OLD:
  3088. case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
  3089. unsigned OpNum = 0;
  3090. Type *Ty;
  3091. bool InBounds;
  3092. if (BitCode == bitc::FUNC_CODE_INST_GEP) {
  3093. InBounds = Record[OpNum++];
  3094. Ty = getTypeByID(Record[OpNum++]);
  3095. } else {
  3096. InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
  3097. Ty = nullptr;
  3098. }
  3099. Value *BasePtr;
  3100. if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
  3101. return Error("Invalid record");
  3102. if (Ty &&
  3103. Ty !=
  3104. cast<SequentialType>(BasePtr->getType()->getScalarType())
  3105. ->getElementType())
  3106. return Error(
  3107. "Explicit gep type does not match pointee type of pointer operand");
  3108. SmallVector<Value*, 16> GEPIdx;
  3109. while (OpNum != Record.size()) {
  3110. Value *Op;
  3111. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  3112. return Error("Invalid record");
  3113. GEPIdx.push_back(Op);
  3114. }
  3115. I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
  3116. InstructionList.push_back(I);
  3117. if (InBounds)
  3118. cast<GetElementPtrInst>(I)->setIsInBounds(true);
  3119. break;
  3120. }
  3121. case bitc::FUNC_CODE_INST_EXTRACTVAL: {
  3122. // EXTRACTVAL: [opty, opval, n x indices]
  3123. unsigned OpNum = 0;
  3124. Value *Agg;
  3125. if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
  3126. return Error("Invalid record");
  3127. SmallVector<unsigned, 4> EXTRACTVALIdx;
  3128. Type *CurTy = Agg->getType();
  3129. for (unsigned RecSize = Record.size();
  3130. OpNum != RecSize; ++OpNum) {
  3131. bool IsArray = CurTy->isArrayTy();
  3132. bool IsStruct = CurTy->isStructTy();
  3133. uint64_t Index = Record[OpNum];
  3134. if (!IsStruct && !IsArray)
  3135. return Error("EXTRACTVAL: Invalid type");
  3136. if ((unsigned)Index != Index)
  3137. return Error("Invalid value");
  3138. if (IsStruct && Index >= CurTy->subtypes().size())
  3139. return Error("EXTRACTVAL: Invalid struct index");
  3140. if (IsArray && Index >= CurTy->getArrayNumElements())
  3141. return Error("EXTRACTVAL: Invalid array index");
  3142. EXTRACTVALIdx.push_back((unsigned)Index);
  3143. if (IsStruct)
  3144. CurTy = CurTy->subtypes()[Index];
  3145. else
  3146. CurTy = CurTy->subtypes()[0];
  3147. }
  3148. I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
  3149. InstructionList.push_back(I);
  3150. break;
  3151. }
  3152. case bitc::FUNC_CODE_INST_INSERTVAL: {
  3153. // INSERTVAL: [opty, opval, opty, opval, n x indices]
  3154. unsigned OpNum = 0;
  3155. Value *Agg;
  3156. if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
  3157. return Error("Invalid record");
  3158. Value *Val;
  3159. if (getValueTypePair(Record, OpNum, NextValueNo, Val))
  3160. return Error("Invalid record");
  3161. SmallVector<unsigned, 4> INSERTVALIdx;
  3162. Type *CurTy = Agg->getType();
  3163. for (unsigned RecSize = Record.size();
  3164. OpNum != RecSize; ++OpNum) {
  3165. bool IsArray = CurTy->isArrayTy();
  3166. bool IsStruct = CurTy->isStructTy();
  3167. uint64_t Index = Record[OpNum];
  3168. if (!IsStruct && !IsArray)
  3169. return Error("INSERTVAL: Invalid type");
  3170. if (!CurTy->isStructTy() && !CurTy->isArrayTy())
  3171. return Error("Invalid type");
  3172. if ((unsigned)Index != Index)
  3173. return Error("Invalid value");
  3174. if (IsStruct && Index >= CurTy->subtypes().size())
  3175. return Error("INSERTVAL: Invalid struct index");
  3176. if (IsArray && Index >= CurTy->getArrayNumElements())
  3177. return Error("INSERTVAL: Invalid array index");
  3178. INSERTVALIdx.push_back((unsigned)Index);
  3179. if (IsStruct)
  3180. CurTy = CurTy->subtypes()[Index];
  3181. else
  3182. CurTy = CurTy->subtypes()[0];
  3183. }
  3184. I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
  3185. InstructionList.push_back(I);
  3186. break;
  3187. }
  3188. case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
  3189. // obsolete form of select
  3190. // handles select i1 ... in old bitcode
  3191. unsigned OpNum = 0;
  3192. Value *TrueVal, *FalseVal, *Cond;
  3193. if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
  3194. popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
  3195. popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
  3196. return Error("Invalid record");
  3197. I = SelectInst::Create(Cond, TrueVal, FalseVal);
  3198. InstructionList.push_back(I);
  3199. break;
  3200. }
  3201. case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
  3202. // new form of select
  3203. // handles select i1 or select [N x i1]
  3204. unsigned OpNum = 0;
  3205. Value *TrueVal, *FalseVal, *Cond;
  3206. if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
  3207. popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
  3208. getValueTypePair(Record, OpNum, NextValueNo, Cond))
  3209. return Error("Invalid record");
  3210. // select condition can be either i1 or [N x i1]
  3211. if (VectorType* vector_type =
  3212. dyn_cast<VectorType>(Cond->getType())) {
  3213. // expect <n x i1>
  3214. if (vector_type->getElementType() != Type::getInt1Ty(Context))
  3215. return Error("Invalid type for value");
  3216. } else {
  3217. // expect i1
  3218. if (Cond->getType() != Type::getInt1Ty(Context))
  3219. return Error("Invalid type for value");
  3220. }
  3221. I = SelectInst::Create(Cond, TrueVal, FalseVal);
  3222. InstructionList.push_back(I);
  3223. break;
  3224. }
  3225. case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
  3226. unsigned OpNum = 0;
  3227. Value *Vec, *Idx;
  3228. if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
  3229. getValueTypePair(Record, OpNum, NextValueNo, Idx))
  3230. return Error("Invalid record");
  3231. I = ExtractElementInst::Create(Vec, Idx);
  3232. InstructionList.push_back(I);
  3233. break;
  3234. }
  3235. case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
  3236. unsigned OpNum = 0;
  3237. Value *Vec, *Elt, *Idx;
  3238. if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
  3239. popValue(Record, OpNum, NextValueNo,
  3240. cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
  3241. getValueTypePair(Record, OpNum, NextValueNo, Idx))
  3242. return Error("Invalid record");
  3243. I = InsertElementInst::Create(Vec, Elt, Idx);
  3244. InstructionList.push_back(I);
  3245. break;
  3246. }
  3247. case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
  3248. unsigned OpNum = 0;
  3249. Value *Vec1, *Vec2, *Mask;
  3250. if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
  3251. popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
  3252. return Error("Invalid record");
  3253. if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
  3254. return Error("Invalid record");
  3255. I = new ShuffleVectorInst(Vec1, Vec2, Mask);
  3256. InstructionList.push_back(I);
  3257. break;
  3258. }
  3259. case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
  3260. // Old form of ICmp/FCmp returning bool
  3261. // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
  3262. // both legal on vectors but had different behaviour.
  3263. case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
  3264. // FCmp/ICmp returning bool or vector of bool
  3265. unsigned OpNum = 0;
  3266. Value *LHS, *RHS;
  3267. if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
  3268. popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
  3269. OpNum+1 != Record.size())
  3270. return Error("Invalid record");
  3271. if (LHS->getType()->isFPOrFPVectorTy())
  3272. I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
  3273. else
  3274. I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
  3275. InstructionList.push_back(I);
  3276. break;
  3277. }
  3278. case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
  3279. {
  3280. unsigned Size = Record.size();
  3281. if (Size == 0) {
  3282. I = ReturnInst::Create(Context);
  3283. InstructionList.push_back(I);
  3284. break;
  3285. }
  3286. unsigned OpNum = 0;
  3287. Value *Op = nullptr;
  3288. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  3289. return Error("Invalid record");
  3290. if (OpNum != Record.size())
  3291. return Error("Invalid record");
  3292. I = ReturnInst::Create(Context, Op);
  3293. InstructionList.push_back(I);
  3294. break;
  3295. }
  3296. case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
  3297. if (Record.size() != 1 && Record.size() != 3)
  3298. return Error("Invalid record");
  3299. BasicBlock *TrueDest = getBasicBlock(Record[0]);
  3300. if (!TrueDest)
  3301. return Error("Invalid record");
  3302. if (Record.size() == 1) {
  3303. I = BranchInst::Create(TrueDest);
  3304. InstructionList.push_back(I);
  3305. }
  3306. else {
  3307. BasicBlock *FalseDest = getBasicBlock(Record[1]);
  3308. Value *Cond = getValue(Record, 2, NextValueNo,
  3309. Type::getInt1Ty(Context));
  3310. if (!FalseDest || !Cond)
  3311. return Error("Invalid record");
  3312. I = BranchInst::Create(TrueDest, FalseDest, Cond);
  3313. InstructionList.push_back(I);
  3314. }
  3315. break;
  3316. }
  3317. case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
  3318. // Check magic
  3319. if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
  3320. // "New" SwitchInst format with case ranges. The changes to write this
  3321. // format were reverted but we still recognize bitcode that uses it.
  3322. // Hopefully someday we will have support for case ranges and can use
  3323. // this format again.
  3324. Type *OpTy = getTypeByID(Record[1]);
  3325. unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
  3326. Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
  3327. BasicBlock *Default = getBasicBlock(Record[3]);
  3328. if (!OpTy || !Cond || !Default)
  3329. return Error("Invalid record");
  3330. unsigned NumCases = Record[4];
  3331. SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
  3332. InstructionList.push_back(SI);
  3333. unsigned CurIdx = 5;
  3334. for (unsigned i = 0; i != NumCases; ++i) {
  3335. SmallVector<ConstantInt*, 1> CaseVals;
  3336. unsigned NumItems = Record[CurIdx++];
  3337. for (unsigned ci = 0; ci != NumItems; ++ci) {
  3338. bool isSingleNumber = Record[CurIdx++];
  3339. APInt Low;
  3340. unsigned ActiveWords = 1;
  3341. if (ValueBitWidth > 64)
  3342. ActiveWords = Record[CurIdx++];
  3343. Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
  3344. ValueBitWidth);
  3345. CurIdx += ActiveWords;
  3346. if (!isSingleNumber) {
  3347. ActiveWords = 1;
  3348. if (ValueBitWidth > 64)
  3349. ActiveWords = Record[CurIdx++];
  3350. APInt High =
  3351. ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
  3352. ValueBitWidth);
  3353. CurIdx += ActiveWords;
  3354. // FIXME: It is not clear whether values in the range should be
  3355. // compared as signed or unsigned values. The partially
  3356. // implemented changes that used this format in the past used
  3357. // unsigned comparisons.
  3358. for ( ; Low.ule(High); ++Low)
  3359. CaseVals.push_back(ConstantInt::get(Context, Low));
  3360. } else
  3361. CaseVals.push_back(ConstantInt::get(Context, Low));
  3362. }
  3363. BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
  3364. for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
  3365. cve = CaseVals.end(); cvi != cve; ++cvi)
  3366. SI->addCase(*cvi, DestBB);
  3367. }
  3368. I = SI;
  3369. break;
  3370. }
  3371. // Old SwitchInst format without case ranges.
  3372. if (Record.size() < 3 || (Record.size() & 1) == 0)
  3373. return Error("Invalid record");
  3374. Type *OpTy = getTypeByID(Record[0]);
  3375. Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
  3376. BasicBlock *Default = getBasicBlock(Record[2]);
  3377. if (!OpTy || !Cond || !Default)
  3378. return Error("Invalid record");
  3379. unsigned NumCases = (Record.size()-3)/2;
  3380. SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
  3381. InstructionList.push_back(SI);
  3382. for (unsigned i = 0, e = NumCases; i != e; ++i) {
  3383. ConstantInt *CaseVal =
  3384. dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
  3385. BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
  3386. if (!CaseVal || !DestBB) {
  3387. delete SI;
  3388. return Error("Invalid record");
  3389. }
  3390. SI->addCase(CaseVal, DestBB);
  3391. }
  3392. I = SI;
  3393. break;
  3394. }
  3395. case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
  3396. if (Record.size() < 2)
  3397. return Error("Invalid record");
  3398. Type *OpTy = getTypeByID(Record[0]);
  3399. Value *Address = getValue(Record, 1, NextValueNo, OpTy);
  3400. if (!OpTy || !Address)
  3401. return Error("Invalid record");
  3402. unsigned NumDests = Record.size()-2;
  3403. IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
  3404. InstructionList.push_back(IBI);
  3405. for (unsigned i = 0, e = NumDests; i != e; ++i) {
  3406. if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
  3407. IBI->addDestination(DestBB);
  3408. } else {
  3409. delete IBI;
  3410. return Error("Invalid record");
  3411. }
  3412. }
  3413. I = IBI;
  3414. break;
  3415. }
  3416. case bitc::FUNC_CODE_INST_INVOKE: {
  3417. // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
  3418. if (Record.size() < 4)
  3419. return Error("Invalid record");
  3420. AttributeSet PAL = getAttributes(Record[0]);
  3421. unsigned CCInfo = Record[1];
  3422. BasicBlock *NormalBB = getBasicBlock(Record[2]);
  3423. BasicBlock *UnwindBB = getBasicBlock(Record[3]);
  3424. unsigned OpNum = 4;
  3425. Value *Callee;
  3426. if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
  3427. return Error("Invalid record");
  3428. PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
  3429. FunctionType *FTy = !CalleeTy ? nullptr :
  3430. dyn_cast<FunctionType>(CalleeTy->getElementType());
  3431. // Check that the right number of fixed parameters are here.
  3432. if (!FTy || !NormalBB || !UnwindBB ||
  3433. Record.size() < OpNum+FTy->getNumParams())
  3434. return Error("Invalid record");
  3435. SmallVector<Value*, 16> Ops;
  3436. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
  3437. Ops.push_back(getValue(Record, OpNum, NextValueNo,
  3438. FTy->getParamType(i)));
  3439. if (!Ops.back())
  3440. return Error("Invalid record");
  3441. }
  3442. if (!FTy->isVarArg()) {
  3443. if (Record.size() != OpNum)
  3444. return Error("Invalid record");
  3445. } else {
  3446. // Read type/value pairs for varargs params.
  3447. while (OpNum != Record.size()) {
  3448. Value *Op;
  3449. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  3450. return Error("Invalid record");
  3451. Ops.push_back(Op);
  3452. }
  3453. }
  3454. I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
  3455. InstructionList.push_back(I);
  3456. cast<InvokeInst>(I)->setCallingConv(
  3457. static_cast<CallingConv::ID>(CCInfo));
  3458. cast<InvokeInst>(I)->setAttributes(PAL);
  3459. break;
  3460. }
  3461. case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
  3462. unsigned Idx = 0;
  3463. Value *Val = nullptr;
  3464. if (getValueTypePair(Record, Idx, NextValueNo, Val))
  3465. return Error("Invalid record");
  3466. I = ResumeInst::Create(Val);
  3467. InstructionList.push_back(I);
  3468. break;
  3469. }
  3470. case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
  3471. I = new UnreachableInst(Context);
  3472. InstructionList.push_back(I);
  3473. break;
  3474. case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
  3475. if (Record.size() < 1 || ((Record.size()-1)&1))
  3476. return Error("Invalid record");
  3477. Type *Ty = getTypeByID(Record[0]);
  3478. if (!Ty)
  3479. return Error("Invalid record");
  3480. PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
  3481. InstructionList.push_back(PN);
  3482. for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
  3483. Value *V;
  3484. // With the new function encoding, it is possible that operands have
  3485. // negative IDs (for forward references). Use a signed VBR
  3486. // representation to keep the encoding small.
  3487. if (UseRelativeIDs)
  3488. V = getValueSigned(Record, 1+i, NextValueNo, Ty);
  3489. else
  3490. V = getValue(Record, 1+i, NextValueNo, Ty);
  3491. BasicBlock *BB = getBasicBlock(Record[2+i]);
  3492. if (!V || !BB)
  3493. return Error("Invalid record");
  3494. PN->addIncoming(V, BB);
  3495. }
  3496. I = PN;
  3497. break;
  3498. }
  3499. case bitc::FUNC_CODE_INST_LANDINGPAD: {
  3500. // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
  3501. unsigned Idx = 0;
  3502. if (Record.size() < 4)
  3503. return Error("Invalid record");
  3504. Type *Ty = getTypeByID(Record[Idx++]);
  3505. if (!Ty)
  3506. return Error("Invalid record");
  3507. Value *PersFn = nullptr;
  3508. if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
  3509. return Error("Invalid record");
  3510. bool IsCleanup = !!Record[Idx++];
  3511. unsigned NumClauses = Record[Idx++];
  3512. LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
  3513. LP->setCleanup(IsCleanup);
  3514. for (unsigned J = 0; J != NumClauses; ++J) {
  3515. LandingPadInst::ClauseType CT =
  3516. LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
  3517. Value *Val;
  3518. if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
  3519. delete LP;
  3520. return Error("Invalid record");
  3521. }
  3522. assert((CT != LandingPadInst::Catch ||
  3523. !isa<ArrayType>(Val->getType())) &&
  3524. "Catch clause has a invalid type!");
  3525. assert((CT != LandingPadInst::Filter ||
  3526. isa<ArrayType>(Val->getType())) &&
  3527. "Filter clause has invalid type!");
  3528. LP->addClause(cast<Constant>(Val));
  3529. }
  3530. I = LP;
  3531. InstructionList.push_back(I);
  3532. break;
  3533. }
  3534. case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
  3535. if (Record.size() != 4)
  3536. return Error("Invalid record");
  3537. PointerType *Ty =
  3538. dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
  3539. Type *OpTy = getTypeByID(Record[1]);
  3540. Value *Size = getFnValueByID(Record[2], OpTy);
  3541. uint64_t AlignRecord = Record[3];
  3542. const uint64_t InAllocaMask = uint64_t(1) << 5;
  3543. bool InAlloca = AlignRecord & InAllocaMask;
  3544. unsigned Align;
  3545. if (std::error_code EC =
  3546. parseAlignmentValue(AlignRecord & ~InAllocaMask, Align)) {
  3547. return EC;
  3548. }
  3549. if (!Ty || !Size)
  3550. return Error("Invalid record");
  3551. AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, Align);
  3552. AI->setUsedWithInAlloca(InAlloca);
  3553. I = AI;
  3554. InstructionList.push_back(I);
  3555. break;
  3556. }
  3557. case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
  3558. unsigned OpNum = 0;
  3559. Value *Op;
  3560. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  3561. (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
  3562. return Error("Invalid record");
  3563. Type *Ty = nullptr;
  3564. if (OpNum + 3 == Record.size())
  3565. Ty = getTypeByID(Record[OpNum++]);
  3566. unsigned Align;
  3567. if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
  3568. return EC;
  3569. I = new LoadInst(Op, "", Record[OpNum+1], Align);
  3570. if (Ty && Ty != I->getType())
  3571. return Error("Explicit load type does not match pointee type of "
  3572. "pointer operand");
  3573. InstructionList.push_back(I);
  3574. break;
  3575. }
  3576. case bitc::FUNC_CODE_INST_LOADATOMIC: {
  3577. // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
  3578. unsigned OpNum = 0;
  3579. Value *Op;
  3580. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  3581. (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
  3582. return Error("Invalid record");
  3583. Type *Ty = nullptr;
  3584. if (OpNum + 5 == Record.size())
  3585. Ty = getTypeByID(Record[OpNum++]);
  3586. AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
  3587. if (Ordering == NotAtomic || Ordering == Release ||
  3588. Ordering == AcquireRelease)
  3589. return Error("Invalid record");
  3590. if (Ordering != NotAtomic && Record[OpNum] == 0)
  3591. return Error("Invalid record");
  3592. SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
  3593. unsigned Align;
  3594. if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
  3595. return EC;
  3596. I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
  3597. (void)Ty;
  3598. assert((!Ty || Ty == I->getType()) &&
  3599. "Explicit type doesn't match pointee type of the first operand");
  3600. InstructionList.push_back(I);
  3601. break;
  3602. }
  3603. case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
  3604. unsigned OpNum = 0;
  3605. Value *Val, *Ptr;
  3606. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
  3607. popValue(Record, OpNum, NextValueNo,
  3608. cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
  3609. OpNum+2 != Record.size())
  3610. return Error("Invalid record");
  3611. unsigned Align;
  3612. if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
  3613. return EC;
  3614. I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
  3615. InstructionList.push_back(I);
  3616. break;
  3617. }
  3618. case bitc::FUNC_CODE_INST_STOREATOMIC: {
  3619. // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
  3620. unsigned OpNum = 0;
  3621. Value *Val, *Ptr;
  3622. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
  3623. popValue(Record, OpNum, NextValueNo,
  3624. cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
  3625. OpNum+4 != Record.size())
  3626. return Error("Invalid record");
  3627. AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
  3628. if (Ordering == NotAtomic || Ordering == Acquire ||
  3629. Ordering == AcquireRelease)
  3630. return Error("Invalid record");
  3631. SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
  3632. if (Ordering != NotAtomic && Record[OpNum] == 0)
  3633. return Error("Invalid record");
  3634. unsigned Align;
  3635. if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
  3636. return EC;
  3637. I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
  3638. InstructionList.push_back(I);
  3639. break;
  3640. }
  3641. case bitc::FUNC_CODE_INST_CMPXCHG: {
  3642. // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
  3643. // failureordering?, isweak?]
  3644. unsigned OpNum = 0;
  3645. Value *Ptr, *Cmp, *New;
  3646. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
  3647. popValue(Record, OpNum, NextValueNo,
  3648. cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
  3649. popValue(Record, OpNum, NextValueNo,
  3650. cast<PointerType>(Ptr->getType())->getElementType(), New) ||
  3651. (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
  3652. return Error("Invalid record");
  3653. AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
  3654. if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
  3655. return Error("Invalid record");
  3656. SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
  3657. AtomicOrdering FailureOrdering;
  3658. if (Record.size() < 7)
  3659. FailureOrdering =
  3660. AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
  3661. else
  3662. FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
  3663. I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
  3664. SynchScope);
  3665. cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
  3666. if (Record.size() < 8) {
  3667. // Before weak cmpxchgs existed, the instruction simply returned the
  3668. // value loaded from memory, so bitcode files from that era will be
  3669. // expecting the first component of a modern cmpxchg.
  3670. CurBB->getInstList().push_back(I);
  3671. I = ExtractValueInst::Create(I, 0);
  3672. } else {
  3673. cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
  3674. }
  3675. InstructionList.push_back(I);
  3676. break;
  3677. }
  3678. case bitc::FUNC_CODE_INST_ATOMICRMW: {
  3679. // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
  3680. unsigned OpNum = 0;
  3681. Value *Ptr, *Val;
  3682. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
  3683. popValue(Record, OpNum, NextValueNo,
  3684. cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
  3685. OpNum+4 != Record.size())
  3686. return Error("Invalid record");
  3687. AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
  3688. if (Operation < AtomicRMWInst::FIRST_BINOP ||
  3689. Operation > AtomicRMWInst::LAST_BINOP)
  3690. return Error("Invalid record");
  3691. AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
  3692. if (Ordering == NotAtomic || Ordering == Unordered)
  3693. return Error("Invalid record");
  3694. SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
  3695. I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
  3696. cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
  3697. InstructionList.push_back(I);
  3698. break;
  3699. }
  3700. case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
  3701. if (2 != Record.size())
  3702. return Error("Invalid record");
  3703. AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
  3704. if (Ordering == NotAtomic || Ordering == Unordered ||
  3705. Ordering == Monotonic)
  3706. return Error("Invalid record");
  3707. SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
  3708. I = new FenceInst(Context, Ordering, SynchScope);
  3709. InstructionList.push_back(I);
  3710. break;
  3711. }
  3712. case bitc::FUNC_CODE_INST_CALL: {
  3713. // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
  3714. if (Record.size() < 3)
  3715. return Error("Invalid record");
  3716. AttributeSet PAL = getAttributes(Record[0]);
  3717. unsigned CCInfo = Record[1];
  3718. unsigned OpNum = 2;
  3719. Value *Callee;
  3720. if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
  3721. return Error("Invalid record");
  3722. PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
  3723. FunctionType *FTy = nullptr;
  3724. if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
  3725. if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
  3726. return Error("Invalid record");
  3727. SmallVector<Value*, 16> Args;
  3728. // Read the fixed params.
  3729. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
  3730. if (FTy->getParamType(i)->isLabelTy())
  3731. Args.push_back(getBasicBlock(Record[OpNum]));
  3732. else
  3733. Args.push_back(getValue(Record, OpNum, NextValueNo,
  3734. FTy->getParamType(i)));
  3735. if (!Args.back())
  3736. return Error("Invalid record");
  3737. }
  3738. // Read type/value pairs for varargs params.
  3739. if (!FTy->isVarArg()) {
  3740. if (OpNum != Record.size())
  3741. return Error("Invalid record");
  3742. } else {
  3743. while (OpNum != Record.size()) {
  3744. Value *Op;
  3745. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  3746. return Error("Invalid record");
  3747. Args.push_back(Op);
  3748. }
  3749. }
  3750. I = CallInst::Create(Callee, Args);
  3751. InstructionList.push_back(I);
  3752. cast<CallInst>(I)->setCallingConv(
  3753. static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
  3754. CallInst::TailCallKind TCK = CallInst::TCK_None;
  3755. if (CCInfo & 1)
  3756. TCK = CallInst::TCK_Tail;
  3757. if (CCInfo & (1 << 14))
  3758. TCK = CallInst::TCK_MustTail;
  3759. cast<CallInst>(I)->setTailCallKind(TCK);
  3760. cast<CallInst>(I)->setAttributes(PAL);
  3761. break;
  3762. }
  3763. case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
  3764. if (Record.size() < 3)
  3765. return Error("Invalid record");
  3766. Type *OpTy = getTypeByID(Record[0]);
  3767. Value *Op = getValue(Record, 1, NextValueNo, OpTy);
  3768. Type *ResTy = getTypeByID(Record[2]);
  3769. if (!OpTy || !Op || !ResTy)
  3770. return Error("Invalid record");
  3771. I = new VAArgInst(Op, ResTy);
  3772. InstructionList.push_back(I);
  3773. break;
  3774. }
  3775. }
  3776. // Add instruction to end of current BB. If there is no current BB, reject
  3777. // this file.
  3778. if (!CurBB) {
  3779. delete I;
  3780. return Error("Invalid instruction with no BB");
  3781. }
  3782. CurBB->getInstList().push_back(I);
  3783. // If this was a terminator instruction, move to the next block.
  3784. if (isa<TerminatorInst>(I)) {
  3785. ++CurBBNo;
  3786. CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
  3787. }
  3788. // Non-void values get registered in the value table for future use.
  3789. if (I && !I->getType()->isVoidTy())
  3790. ValueList.AssignValue(I, NextValueNo++);
  3791. }
  3792. OutOfRecordLoop:
  3793. // Check the function list for unresolved values.
  3794. if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
  3795. if (!A->getParent()) {
  3796. // We found at least one unresolved value. Nuke them all to avoid leaks.
  3797. for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
  3798. if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
  3799. A->replaceAllUsesWith(UndefValue::get(A->getType()));
  3800. delete A;
  3801. }
  3802. }
  3803. return Error("Never resolved value found in function");
  3804. }
  3805. }
  3806. // FIXME: Check for unresolved forward-declared metadata references
  3807. // and clean up leaks.
  3808. // Trim the value list down to the size it was before we parsed this function.
  3809. ValueList.shrinkTo(ModuleValueListSize);
  3810. MDValueList.shrinkTo(ModuleMDValueListSize);
  3811. std::vector<BasicBlock*>().swap(FunctionBBs);
  3812. return std::error_code();
  3813. }
  3814. /// Find the function body in the bitcode stream
  3815. std::error_code BitcodeReader::FindFunctionInStream(
  3816. Function *F,
  3817. DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
  3818. while (DeferredFunctionInfoIterator->second == 0) {
  3819. if (Stream.AtEndOfStream())
  3820. return Error("Could not find function in stream");
  3821. // ParseModule will parse the next body in the stream and set its
  3822. // position in the DeferredFunctionInfo map.
  3823. if (std::error_code EC = ParseModule(true))
  3824. return EC;
  3825. }
  3826. return std::error_code();
  3827. }
  3828. //===----------------------------------------------------------------------===//
  3829. // GVMaterializer implementation
  3830. //===----------------------------------------------------------------------===//
  3831. void BitcodeReader::releaseBuffer() { Buffer.release(); }
  3832. std::error_code BitcodeReader::materialize(GlobalValue *GV) {
  3833. if (std::error_code EC = materializeMetadata())
  3834. return EC;
  3835. Function *F = dyn_cast<Function>(GV);
  3836. // If it's not a function or is already material, ignore the request.
  3837. if (!F || !F->isMaterializable())
  3838. return std::error_code();
  3839. DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
  3840. assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
  3841. // If its position is recorded as 0, its body is somewhere in the stream
  3842. // but we haven't seen it yet.
  3843. if (DFII->second == 0 && LazyStreamer)
  3844. if (std::error_code EC = FindFunctionInStream(F, DFII))
  3845. return EC;
  3846. // Move the bit stream to the saved position of the deferred function body.
  3847. Stream.JumpToBit(DFII->second);
  3848. if (std::error_code EC = ParseFunctionBody(F))
  3849. return EC;
  3850. F->setIsMaterializable(false);
  3851. // Upgrade any old intrinsic calls in the function.
  3852. for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
  3853. E = UpgradedIntrinsics.end(); I != E; ++I) {
  3854. if (I->first != I->second) {
  3855. for (auto UI = I->first->user_begin(), UE = I->first->user_end();
  3856. UI != UE;) {
  3857. if (CallInst* CI = dyn_cast<CallInst>(*UI++))
  3858. UpgradeIntrinsicCall(CI, I->second);
  3859. }
  3860. }
  3861. }
  3862. // Bring in any functions that this function forward-referenced via
  3863. // blockaddresses.
  3864. return materializeForwardReferencedFunctions();
  3865. }
  3866. bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
  3867. const Function *F = dyn_cast<Function>(GV);
  3868. if (!F || F->isDeclaration())
  3869. return false;
  3870. // Dematerializing F would leave dangling references that wouldn't be
  3871. // reconnected on re-materialization.
  3872. if (BlockAddressesTaken.count(F))
  3873. return false;
  3874. return DeferredFunctionInfo.count(const_cast<Function*>(F));
  3875. }
  3876. void BitcodeReader::Dematerialize(GlobalValue *GV) {
  3877. Function *F = dyn_cast<Function>(GV);
  3878. // If this function isn't dematerializable, this is a noop.
  3879. if (!F || !isDematerializable(F))
  3880. return;
  3881. assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
  3882. // Just forget the function body, we can remat it later.
  3883. F->dropAllReferences();
  3884. F->setIsMaterializable(true);
  3885. }
  3886. std::error_code BitcodeReader::MaterializeModule(Module *M) {
  3887. assert(M == TheModule &&
  3888. "Can only Materialize the Module this BitcodeReader is attached to.");
  3889. if (std::error_code EC = materializeMetadata())
  3890. return EC;
  3891. // Promise to materialize all forward references.
  3892. WillMaterializeAllForwardRefs = true;
  3893. // Iterate over the module, deserializing any functions that are still on
  3894. // disk.
  3895. for (Module::iterator F = TheModule->begin(), E = TheModule->end();
  3896. F != E; ++F) {
  3897. if (std::error_code EC = materialize(F))
  3898. return EC;
  3899. }
  3900. // At this point, if there are any function bodies, the current bit is
  3901. // pointing to the END_BLOCK record after them. Now make sure the rest
  3902. // of the bits in the module have been read.
  3903. if (NextUnreadBit)
  3904. ParseModule(true);
  3905. // Check that all block address forward references got resolved (as we
  3906. // promised above).
  3907. if (!BasicBlockFwdRefs.empty())
  3908. return Error("Never resolved function from blockaddress");
  3909. // Upgrade any intrinsic calls that slipped through (should not happen!) and
  3910. // delete the old functions to clean up. We can't do this unless the entire
  3911. // module is materialized because there could always be another function body
  3912. // with calls to the old function.
  3913. for (std::vector<std::pair<Function*, Function*> >::iterator I =
  3914. UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
  3915. if (I->first != I->second) {
  3916. for (auto UI = I->first->user_begin(), UE = I->first->user_end();
  3917. UI != UE;) {
  3918. if (CallInst* CI = dyn_cast<CallInst>(*UI++))
  3919. UpgradeIntrinsicCall(CI, I->second);
  3920. }
  3921. if (!I->first->use_empty())
  3922. I->first->replaceAllUsesWith(I->second);
  3923. I->first->eraseFromParent();
  3924. }
  3925. }
  3926. std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
  3927. for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
  3928. UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
  3929. UpgradeDebugInfo(*M);
  3930. return std::error_code();
  3931. }
  3932. std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
  3933. return IdentifiedStructTypes;
  3934. }
  3935. std::error_code BitcodeReader::InitStream() {
  3936. if (LazyStreamer)
  3937. return InitLazyStream();
  3938. return InitStreamFromBuffer();
  3939. }
  3940. std::error_code BitcodeReader::InitStreamFromBuffer() {
  3941. const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
  3942. const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
  3943. if (Buffer->getBufferSize() & 3)
  3944. return Error("Invalid bitcode signature");
  3945. // If we have a wrapper header, parse it and ignore the non-bc file contents.
  3946. // The magic number is 0x0B17C0DE stored in little endian.
  3947. if (isBitcodeWrapper(BufPtr, BufEnd))
  3948. if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
  3949. return Error("Invalid bitcode wrapper header");
  3950. StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
  3951. Stream.init(&*StreamFile);
  3952. return std::error_code();
  3953. }
  3954. std::error_code BitcodeReader::InitLazyStream() {
  3955. // Check and strip off the bitcode wrapper; BitstreamReader expects never to
  3956. // see it.
  3957. auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
  3958. StreamingMemoryObject &Bytes = *OwnedBytes;
  3959. StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
  3960. Stream.init(&*StreamFile);
  3961. unsigned char buf[16];
  3962. if (Bytes.readBytes(buf, 16, 0) != 16)
  3963. return Error("Invalid bitcode signature");
  3964. if (!isBitcode(buf, buf + 16))
  3965. return Error("Invalid bitcode signature");
  3966. if (isBitcodeWrapper(buf, buf + 4)) {
  3967. const unsigned char *bitcodeStart = buf;
  3968. const unsigned char *bitcodeEnd = buf + 16;
  3969. SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
  3970. Bytes.dropLeadingBytes(bitcodeStart - buf);
  3971. Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
  3972. }
  3973. return std::error_code();
  3974. }
  3975. namespace {
  3976. class BitcodeErrorCategoryType : public std::error_category {
  3977. const char *name() const LLVM_NOEXCEPT override {
  3978. return "llvm.bitcode";
  3979. }
  3980. std::string message(int IE) const override {
  3981. BitcodeError E = static_cast<BitcodeError>(IE);
  3982. switch (E) {
  3983. case BitcodeError::InvalidBitcodeSignature:
  3984. return "Invalid bitcode signature";
  3985. case BitcodeError::CorruptedBitcode:
  3986. return "Corrupted bitcode";
  3987. }
  3988. llvm_unreachable("Unknown error type!");
  3989. }
  3990. };
  3991. }
  3992. static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
  3993. const std::error_category &llvm::BitcodeErrorCategory() {
  3994. return *ErrorCategory;
  3995. }
  3996. //===----------------------------------------------------------------------===//
  3997. // External interface
  3998. //===----------------------------------------------------------------------===//
  3999. /// \brief Get a lazy one-at-time loading module from bitcode.
  4000. ///
  4001. /// This isn't always used in a lazy context. In particular, it's also used by
  4002. /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
  4003. /// in forward-referenced functions from block address references.
  4004. ///
  4005. /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
  4006. /// materialize everything -- in particular, if this isn't truly lazy.
  4007. static ErrorOr<Module *>
  4008. getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
  4009. LLVMContext &Context, bool WillMaterializeAll,
  4010. DiagnosticHandlerFunction DiagnosticHandler,
  4011. bool ShouldLazyLoadMetadata = false) {
  4012. Module *M = new Module(Buffer->getBufferIdentifier(), Context);
  4013. BitcodeReader *R =
  4014. new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
  4015. M->setMaterializer(R);
  4016. auto cleanupOnError = [&](std::error_code EC) {
  4017. R->releaseBuffer(); // Never take ownership on error.
  4018. delete M; // Also deletes R.
  4019. return EC;
  4020. };
  4021. // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
  4022. if (std::error_code EC = R->ParseBitcodeInto(M, ShouldLazyLoadMetadata))
  4023. return cleanupOnError(EC);
  4024. if (!WillMaterializeAll)
  4025. // Resolve forward references from blockaddresses.
  4026. if (std::error_code EC = R->materializeForwardReferencedFunctions())
  4027. return cleanupOnError(EC);
  4028. Buffer.release(); // The BitcodeReader owns it now.
  4029. return M;
  4030. }
  4031. ErrorOr<Module *>
  4032. llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
  4033. LLVMContext &Context,
  4034. DiagnosticHandlerFunction DiagnosticHandler,
  4035. bool ShouldLazyLoadMetadata) {
  4036. return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
  4037. DiagnosticHandler, ShouldLazyLoadMetadata);
  4038. }
  4039. ErrorOr<std::unique_ptr<Module>>
  4040. llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
  4041. LLVMContext &Context,
  4042. DiagnosticHandlerFunction DiagnosticHandler) {
  4043. std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
  4044. BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler);
  4045. M->setMaterializer(R);
  4046. if (std::error_code EC = R->ParseBitcodeInto(M.get()))
  4047. return EC;
  4048. return std::move(M);
  4049. }
  4050. ErrorOr<Module *>
  4051. llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
  4052. DiagnosticHandlerFunction DiagnosticHandler) {
  4053. std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
  4054. ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl(
  4055. std::move(Buf), Context, true, DiagnosticHandler);
  4056. if (!ModuleOrErr)
  4057. return ModuleOrErr;
  4058. Module *M = ModuleOrErr.get();
  4059. // Read in the entire module, and destroy the BitcodeReader.
  4060. if (std::error_code EC = M->materializeAllPermanently()) {
  4061. delete M;
  4062. return EC;
  4063. }
  4064. // TODO: Restore the use-lists to the in-memory state when the bitcode was
  4065. // written. We must defer until the Module has been fully materialized.
  4066. return M;
  4067. }
  4068. std::string
  4069. llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
  4070. DiagnosticHandlerFunction DiagnosticHandler) {
  4071. std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
  4072. auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
  4073. DiagnosticHandler);
  4074. ErrorOr<std::string> Triple = R->parseTriple();
  4075. if (Triple.getError())
  4076. return "";
  4077. return Triple.get();
  4078. }