BitcodeReader.cpp 115 KB

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