BitcodeReader.cpp 147 KB

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