BitcodeReader.cpp 120 KB

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