BitcodeReader.cpp 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452
  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. //
  10. // This header defines the BitcodeReader class.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Bitcode/ReaderWriter.h"
  14. #include "BitcodeReader.h"
  15. #include "llvm/Constants.h"
  16. #include "llvm/DerivedTypes.h"
  17. #include "llvm/InlineAsm.h"
  18. #include "llvm/IntrinsicInst.h"
  19. #include "llvm/Module.h"
  20. #include "llvm/Operator.h"
  21. #include "llvm/AutoUpgrade.h"
  22. #include "llvm/ADT/SmallString.h"
  23. #include "llvm/ADT/SmallVector.h"
  24. #include "llvm/Support/MathExtras.h"
  25. #include "llvm/Support/MemoryBuffer.h"
  26. #include "llvm/OperandTraits.h"
  27. using namespace llvm;
  28. void BitcodeReader::FreeState() {
  29. if (BufferOwned)
  30. delete Buffer;
  31. Buffer = 0;
  32. std::vector<PATypeHolder>().swap(TypeList);
  33. ValueList.clear();
  34. MDValueList.clear();
  35. std::vector<AttrListPtr>().swap(MAttributes);
  36. std::vector<BasicBlock*>().swap(FunctionBBs);
  37. std::vector<Function*>().swap(FunctionsWithBodies);
  38. DeferredFunctionInfo.clear();
  39. }
  40. //===----------------------------------------------------------------------===//
  41. // Helper functions to implement forward reference resolution, etc.
  42. //===----------------------------------------------------------------------===//
  43. /// ConvertToString - Convert a string from a record into an std::string, return
  44. /// true on failure.
  45. template<typename StrTy>
  46. static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
  47. StrTy &Result) {
  48. if (Idx > Record.size())
  49. return true;
  50. for (unsigned i = Idx, e = Record.size(); i != e; ++i)
  51. Result += (char)Record[i];
  52. return false;
  53. }
  54. static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
  55. switch (Val) {
  56. default: // Map unknown/new linkages to external
  57. case 0: return GlobalValue::ExternalLinkage;
  58. case 1: return GlobalValue::WeakAnyLinkage;
  59. case 2: return GlobalValue::AppendingLinkage;
  60. case 3: return GlobalValue::InternalLinkage;
  61. case 4: return GlobalValue::LinkOnceAnyLinkage;
  62. case 5: return GlobalValue::DLLImportLinkage;
  63. case 6: return GlobalValue::DLLExportLinkage;
  64. case 7: return GlobalValue::ExternalWeakLinkage;
  65. case 8: return GlobalValue::CommonLinkage;
  66. case 9: return GlobalValue::PrivateLinkage;
  67. case 10: return GlobalValue::WeakODRLinkage;
  68. case 11: return GlobalValue::LinkOnceODRLinkage;
  69. case 12: return GlobalValue::AvailableExternallyLinkage;
  70. case 13: return GlobalValue::LinkerPrivateLinkage;
  71. }
  72. }
  73. static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
  74. switch (Val) {
  75. default: // Map unknown visibilities to default.
  76. case 0: return GlobalValue::DefaultVisibility;
  77. case 1: return GlobalValue::HiddenVisibility;
  78. case 2: return GlobalValue::ProtectedVisibility;
  79. }
  80. }
  81. static int GetDecodedCastOpcode(unsigned Val) {
  82. switch (Val) {
  83. default: return -1;
  84. case bitc::CAST_TRUNC : return Instruction::Trunc;
  85. case bitc::CAST_ZEXT : return Instruction::ZExt;
  86. case bitc::CAST_SEXT : return Instruction::SExt;
  87. case bitc::CAST_FPTOUI : return Instruction::FPToUI;
  88. case bitc::CAST_FPTOSI : return Instruction::FPToSI;
  89. case bitc::CAST_UITOFP : return Instruction::UIToFP;
  90. case bitc::CAST_SITOFP : return Instruction::SIToFP;
  91. case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
  92. case bitc::CAST_FPEXT : return Instruction::FPExt;
  93. case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
  94. case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
  95. case bitc::CAST_BITCAST : return Instruction::BitCast;
  96. }
  97. }
  98. static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
  99. switch (Val) {
  100. default: return -1;
  101. case bitc::BINOP_ADD:
  102. return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
  103. case bitc::BINOP_SUB:
  104. return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
  105. case bitc::BINOP_MUL:
  106. return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
  107. case bitc::BINOP_UDIV: return Instruction::UDiv;
  108. case bitc::BINOP_SDIV:
  109. return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
  110. case bitc::BINOP_UREM: return Instruction::URem;
  111. case bitc::BINOP_SREM:
  112. return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
  113. case bitc::BINOP_SHL: return Instruction::Shl;
  114. case bitc::BINOP_LSHR: return Instruction::LShr;
  115. case bitc::BINOP_ASHR: return Instruction::AShr;
  116. case bitc::BINOP_AND: return Instruction::And;
  117. case bitc::BINOP_OR: return Instruction::Or;
  118. case bitc::BINOP_XOR: return Instruction::Xor;
  119. }
  120. }
  121. namespace llvm {
  122. namespace {
  123. /// @brief A class for maintaining the slot number definition
  124. /// as a placeholder for the actual definition for forward constants defs.
  125. class ConstantPlaceHolder : public ConstantExpr {
  126. ConstantPlaceHolder(); // DO NOT IMPLEMENT
  127. void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
  128. public:
  129. // allocate space for exactly one operand
  130. void *operator new(size_t s) {
  131. return User::operator new(s, 1);
  132. }
  133. explicit ConstantPlaceHolder(const Type *Ty, LLVMContext& Context)
  134. : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
  135. Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
  136. }
  137. /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
  138. static inline bool classof(const ConstantPlaceHolder *) { return true; }
  139. static bool classof(const Value *V) {
  140. return isa<ConstantExpr>(V) &&
  141. cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
  142. }
  143. /// Provide fast operand accessors
  144. //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  145. };
  146. }
  147. // FIXME: can we inherit this from ConstantExpr?
  148. template <>
  149. struct OperandTraits<ConstantPlaceHolder> : public FixedNumOperandTraits<1> {
  150. };
  151. }
  152. void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
  153. if (Idx == size()) {
  154. push_back(V);
  155. return;
  156. }
  157. if (Idx >= size())
  158. resize(Idx+1);
  159. WeakVH &OldV = ValuePtrs[Idx];
  160. if (OldV == 0) {
  161. OldV = V;
  162. return;
  163. }
  164. // Handle constants and non-constants (e.g. instrs) differently for
  165. // efficiency.
  166. if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
  167. ResolveConstants.push_back(std::make_pair(PHC, Idx));
  168. OldV = V;
  169. } else {
  170. // If there was a forward reference to this value, replace it.
  171. Value *PrevVal = OldV;
  172. OldV->replaceAllUsesWith(V);
  173. delete PrevVal;
  174. }
  175. }
  176. Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
  177. const Type *Ty) {
  178. if (Idx >= size())
  179. resize(Idx + 1);
  180. if (Value *V = ValuePtrs[Idx]) {
  181. assert(Ty == V->getType() && "Type mismatch in constant table!");
  182. return cast<Constant>(V);
  183. }
  184. // Create and return a placeholder, which will later be RAUW'd.
  185. Constant *C = new ConstantPlaceHolder(Ty, Context);
  186. ValuePtrs[Idx] = C;
  187. return C;
  188. }
  189. Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
  190. if (Idx >= size())
  191. resize(Idx + 1);
  192. if (Value *V = ValuePtrs[Idx]) {
  193. assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
  194. return V;
  195. }
  196. // No type specified, must be invalid reference.
  197. if (Ty == 0) return 0;
  198. // Create and return a placeholder, which will later be RAUW'd.
  199. Value *V = new Argument(Ty);
  200. ValuePtrs[Idx] = V;
  201. return V;
  202. }
  203. /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
  204. /// resolves any forward references. The idea behind this is that we sometimes
  205. /// get constants (such as large arrays) which reference *many* forward ref
  206. /// constants. Replacing each of these causes a lot of thrashing when
  207. /// building/reuniquing the constant. Instead of doing this, we look at all the
  208. /// uses and rewrite all the place holders at once for any constant that uses
  209. /// a placeholder.
  210. void BitcodeReaderValueList::ResolveConstantForwardRefs() {
  211. // Sort the values by-pointer so that they are efficient to look up with a
  212. // binary search.
  213. std::sort(ResolveConstants.begin(), ResolveConstants.end());
  214. SmallVector<Constant*, 64> NewOps;
  215. while (!ResolveConstants.empty()) {
  216. Value *RealVal = operator[](ResolveConstants.back().second);
  217. Constant *Placeholder = ResolveConstants.back().first;
  218. ResolveConstants.pop_back();
  219. // Loop over all users of the placeholder, updating them to reference the
  220. // new value. If they reference more than one placeholder, update them all
  221. // at once.
  222. while (!Placeholder->use_empty()) {
  223. Value::use_iterator UI = Placeholder->use_begin();
  224. // If the using object isn't uniqued, just update the operands. This
  225. // handles instructions and initializers for global variables.
  226. if (!isa<Constant>(*UI) || isa<GlobalValue>(*UI)) {
  227. UI.getUse().set(RealVal);
  228. continue;
  229. }
  230. // Otherwise, we have a constant that uses the placeholder. Replace that
  231. // constant with a new constant that has *all* placeholder uses updated.
  232. Constant *UserC = cast<Constant>(*UI);
  233. for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
  234. I != E; ++I) {
  235. Value *NewOp;
  236. if (!isa<ConstantPlaceHolder>(*I)) {
  237. // Not a placeholder reference.
  238. NewOp = *I;
  239. } else if (*I == Placeholder) {
  240. // Common case is that it just references this one placeholder.
  241. NewOp = RealVal;
  242. } else {
  243. // Otherwise, look up the placeholder in ResolveConstants.
  244. ResolveConstantsTy::iterator It =
  245. std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
  246. std::pair<Constant*, unsigned>(cast<Constant>(*I),
  247. 0));
  248. assert(It != ResolveConstants.end() && It->first == *I);
  249. NewOp = operator[](It->second);
  250. }
  251. NewOps.push_back(cast<Constant>(NewOp));
  252. }
  253. // Make the new constant.
  254. Constant *NewC;
  255. if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
  256. NewC = ConstantArray::get(UserCA->getType(), &NewOps[0],
  257. NewOps.size());
  258. } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
  259. NewC = ConstantStruct::get(Context, &NewOps[0], NewOps.size(),
  260. UserCS->getType()->isPacked());
  261. } else if (ConstantUnion *UserCU = dyn_cast<ConstantUnion>(UserC)) {
  262. NewC = ConstantUnion::get(UserCU->getType(), NewOps[0]);
  263. } else if (isa<ConstantVector>(UserC)) {
  264. NewC = ConstantVector::get(&NewOps[0], NewOps.size());
  265. } else {
  266. assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
  267. NewC = cast<ConstantExpr>(UserC)->getWithOperands(&NewOps[0],
  268. NewOps.size());
  269. }
  270. UserC->replaceAllUsesWith(NewC);
  271. UserC->destroyConstant();
  272. NewOps.clear();
  273. }
  274. // Update all ValueHandles, they should be the only users at this point.
  275. Placeholder->replaceAllUsesWith(RealVal);
  276. delete Placeholder;
  277. }
  278. }
  279. void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
  280. if (Idx == size()) {
  281. push_back(V);
  282. return;
  283. }
  284. if (Idx >= size())
  285. resize(Idx+1);
  286. WeakVH &OldV = MDValuePtrs[Idx];
  287. if (OldV == 0) {
  288. OldV = V;
  289. return;
  290. }
  291. // If there was a forward reference to this value, replace it.
  292. Value *PrevVal = OldV;
  293. OldV->replaceAllUsesWith(V);
  294. delete PrevVal;
  295. // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
  296. // value for Idx.
  297. MDValuePtrs[Idx] = V;
  298. }
  299. Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
  300. if (Idx >= size())
  301. resize(Idx + 1);
  302. if (Value *V = MDValuePtrs[Idx]) {
  303. assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
  304. return V;
  305. }
  306. // Create and return a placeholder, which will later be RAUW'd.
  307. Value *V = new Argument(Type::getMetadataTy(Context));
  308. MDValuePtrs[Idx] = V;
  309. return V;
  310. }
  311. const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
  312. // If the TypeID is in range, return it.
  313. if (ID < TypeList.size())
  314. return TypeList[ID].get();
  315. if (!isTypeTable) return 0;
  316. // The type table allows forward references. Push as many Opaque types as
  317. // needed to get up to ID.
  318. while (TypeList.size() <= ID)
  319. TypeList.push_back(OpaqueType::get(Context));
  320. return TypeList.back().get();
  321. }
  322. //===----------------------------------------------------------------------===//
  323. // Functions for parsing blocks from the bitcode file
  324. //===----------------------------------------------------------------------===//
  325. bool BitcodeReader::ParseAttributeBlock() {
  326. if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
  327. return Error("Malformed block record");
  328. if (!MAttributes.empty())
  329. return Error("Multiple PARAMATTR blocks found!");
  330. SmallVector<uint64_t, 64> Record;
  331. SmallVector<AttributeWithIndex, 8> Attrs;
  332. // Read all the records.
  333. while (1) {
  334. unsigned Code = Stream.ReadCode();
  335. if (Code == bitc::END_BLOCK) {
  336. if (Stream.ReadBlockEnd())
  337. return Error("Error at end of PARAMATTR block");
  338. return false;
  339. }
  340. if (Code == bitc::ENTER_SUBBLOCK) {
  341. // No known subblocks, always skip them.
  342. Stream.ReadSubBlockID();
  343. if (Stream.SkipBlock())
  344. return Error("Malformed block record");
  345. continue;
  346. }
  347. if (Code == bitc::DEFINE_ABBREV) {
  348. Stream.ReadAbbrevRecord();
  349. continue;
  350. }
  351. // Read a record.
  352. Record.clear();
  353. switch (Stream.ReadRecord(Code, Record)) {
  354. default: // Default behavior: ignore.
  355. break;
  356. case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
  357. if (Record.size() & 1)
  358. return Error("Invalid ENTRY record");
  359. // FIXME : Remove this autoupgrade code in LLVM 3.0.
  360. // If Function attributes are using index 0 then transfer them
  361. // to index ~0. Index 0 is used for return value attributes but used to be
  362. // used for function attributes.
  363. Attributes RetAttribute = Attribute::None;
  364. Attributes FnAttribute = Attribute::None;
  365. for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
  366. // FIXME: remove in LLVM 3.0
  367. // The alignment is stored as a 16-bit raw value from bits 31--16.
  368. // We shift the bits above 31 down by 11 bits.
  369. unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
  370. if (Alignment && !isPowerOf2_32(Alignment))
  371. return Error("Alignment is not a power of two.");
  372. Attributes ReconstitutedAttr = Record[i+1] & 0xffff;
  373. if (Alignment)
  374. ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
  375. ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11;
  376. Record[i+1] = ReconstitutedAttr;
  377. if (Record[i] == 0)
  378. RetAttribute = Record[i+1];
  379. else if (Record[i] == ~0U)
  380. FnAttribute = Record[i+1];
  381. }
  382. unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
  383. Attribute::ReadOnly|Attribute::ReadNone);
  384. if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
  385. (RetAttribute & OldRetAttrs) != 0) {
  386. if (FnAttribute == Attribute::None) { // add a slot so they get added.
  387. Record.push_back(~0U);
  388. Record.push_back(0);
  389. }
  390. FnAttribute |= RetAttribute & OldRetAttrs;
  391. RetAttribute &= ~OldRetAttrs;
  392. }
  393. for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
  394. if (Record[i] == 0) {
  395. if (RetAttribute != Attribute::None)
  396. Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
  397. } else if (Record[i] == ~0U) {
  398. if (FnAttribute != Attribute::None)
  399. Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
  400. } else if (Record[i+1] != Attribute::None)
  401. Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1]));
  402. }
  403. MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
  404. Attrs.clear();
  405. break;
  406. }
  407. }
  408. }
  409. }
  410. bool BitcodeReader::ParseTypeTable() {
  411. if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
  412. return Error("Malformed block record");
  413. if (!TypeList.empty())
  414. return Error("Multiple TYPE_BLOCKs found!");
  415. SmallVector<uint64_t, 64> Record;
  416. unsigned NumRecords = 0;
  417. // Read all the records for this type table.
  418. while (1) {
  419. unsigned Code = Stream.ReadCode();
  420. if (Code == bitc::END_BLOCK) {
  421. if (NumRecords != TypeList.size())
  422. return Error("Invalid type forward reference in TYPE_BLOCK");
  423. if (Stream.ReadBlockEnd())
  424. return Error("Error at end of type table block");
  425. return false;
  426. }
  427. if (Code == bitc::ENTER_SUBBLOCK) {
  428. // No known subblocks, always skip them.
  429. Stream.ReadSubBlockID();
  430. if (Stream.SkipBlock())
  431. return Error("Malformed block record");
  432. continue;
  433. }
  434. if (Code == bitc::DEFINE_ABBREV) {
  435. Stream.ReadAbbrevRecord();
  436. continue;
  437. }
  438. // Read a record.
  439. Record.clear();
  440. const Type *ResultTy = 0;
  441. switch (Stream.ReadRecord(Code, Record)) {
  442. default: // Default behavior: unknown type.
  443. ResultTy = 0;
  444. break;
  445. case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
  446. // TYPE_CODE_NUMENTRY contains a count of the number of types in the
  447. // type list. This allows us to reserve space.
  448. if (Record.size() < 1)
  449. return Error("Invalid TYPE_CODE_NUMENTRY record");
  450. TypeList.reserve(Record[0]);
  451. continue;
  452. case bitc::TYPE_CODE_VOID: // VOID
  453. ResultTy = Type::getVoidTy(Context);
  454. break;
  455. case bitc::TYPE_CODE_FLOAT: // FLOAT
  456. ResultTy = Type::getFloatTy(Context);
  457. break;
  458. case bitc::TYPE_CODE_DOUBLE: // DOUBLE
  459. ResultTy = Type::getDoubleTy(Context);
  460. break;
  461. case bitc::TYPE_CODE_X86_FP80: // X86_FP80
  462. ResultTy = Type::getX86_FP80Ty(Context);
  463. break;
  464. case bitc::TYPE_CODE_FP128: // FP128
  465. ResultTy = Type::getFP128Ty(Context);
  466. break;
  467. case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
  468. ResultTy = Type::getPPC_FP128Ty(Context);
  469. break;
  470. case bitc::TYPE_CODE_LABEL: // LABEL
  471. ResultTy = Type::getLabelTy(Context);
  472. break;
  473. case bitc::TYPE_CODE_OPAQUE: // OPAQUE
  474. ResultTy = 0;
  475. break;
  476. case bitc::TYPE_CODE_METADATA: // METADATA
  477. ResultTy = Type::getMetadataTy(Context);
  478. break;
  479. case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
  480. if (Record.size() < 1)
  481. return Error("Invalid Integer type record");
  482. ResultTy = IntegerType::get(Context, Record[0]);
  483. break;
  484. case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
  485. // [pointee type, address space]
  486. if (Record.size() < 1)
  487. return Error("Invalid POINTER type record");
  488. unsigned AddressSpace = 0;
  489. if (Record.size() == 2)
  490. AddressSpace = Record[1];
  491. ResultTy = PointerType::get(getTypeByID(Record[0], true),
  492. AddressSpace);
  493. break;
  494. }
  495. case bitc::TYPE_CODE_FUNCTION: {
  496. // FIXME: attrid is dead, remove it in LLVM 3.0
  497. // FUNCTION: [vararg, attrid, retty, paramty x N]
  498. if (Record.size() < 3)
  499. return Error("Invalid FUNCTION type record");
  500. std::vector<const Type*> ArgTys;
  501. for (unsigned i = 3, e = Record.size(); i != e; ++i)
  502. ArgTys.push_back(getTypeByID(Record[i], true));
  503. ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
  504. Record[0]);
  505. break;
  506. }
  507. case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
  508. if (Record.size() < 1)
  509. return Error("Invalid STRUCT type record");
  510. std::vector<const Type*> EltTys;
  511. for (unsigned i = 1, e = Record.size(); i != e; ++i)
  512. EltTys.push_back(getTypeByID(Record[i], true));
  513. ResultTy = StructType::get(Context, EltTys, Record[0]);
  514. break;
  515. }
  516. case bitc::TYPE_CODE_UNION: { // UNION: [eltty x N]
  517. SmallVector<const Type*, 8> EltTys;
  518. for (unsigned i = 0, e = Record.size(); i != e; ++i)
  519. EltTys.push_back(getTypeByID(Record[i], true));
  520. ResultTy = UnionType::get(&EltTys[0], EltTys.size());
  521. break;
  522. }
  523. case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
  524. if (Record.size() < 2)
  525. return Error("Invalid ARRAY type record");
  526. ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
  527. break;
  528. case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
  529. if (Record.size() < 2)
  530. return Error("Invalid VECTOR type record");
  531. ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
  532. break;
  533. }
  534. if (NumRecords == TypeList.size()) {
  535. // If this is a new type slot, just append it.
  536. TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get(Context));
  537. ++NumRecords;
  538. } else if (ResultTy == 0) {
  539. // Otherwise, this was forward referenced, so an opaque type was created,
  540. // but the result type is actually just an opaque. Leave the one we
  541. // created previously.
  542. ++NumRecords;
  543. } else {
  544. // Otherwise, this was forward referenced, so an opaque type was created.
  545. // Resolve the opaque type to the real type now.
  546. assert(NumRecords < TypeList.size() && "Typelist imbalance");
  547. const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
  548. // Don't directly push the new type on the Tab. Instead we want to replace
  549. // the opaque type we previously inserted with the new concrete value. The
  550. // refinement from the abstract (opaque) type to the new type causes all
  551. // uses of the abstract type to use the concrete type (NewTy). This will
  552. // also cause the opaque type to be deleted.
  553. const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
  554. // This should have replaced the old opaque type with the new type in the
  555. // value table... or with a preexisting type that was already in the
  556. // system. Let's just make sure it did.
  557. assert(TypeList[NumRecords-1].get() != OldTy &&
  558. "refineAbstractType didn't work!");
  559. }
  560. }
  561. }
  562. bool BitcodeReader::ParseTypeSymbolTable() {
  563. if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
  564. return Error("Malformed block record");
  565. SmallVector<uint64_t, 64> Record;
  566. // Read all the records for this type table.
  567. std::string TypeName;
  568. while (1) {
  569. unsigned Code = Stream.ReadCode();
  570. if (Code == bitc::END_BLOCK) {
  571. if (Stream.ReadBlockEnd())
  572. return Error("Error at end of type symbol table block");
  573. return false;
  574. }
  575. if (Code == bitc::ENTER_SUBBLOCK) {
  576. // No known subblocks, always skip them.
  577. Stream.ReadSubBlockID();
  578. if (Stream.SkipBlock())
  579. return Error("Malformed block record");
  580. continue;
  581. }
  582. if (Code == bitc::DEFINE_ABBREV) {
  583. Stream.ReadAbbrevRecord();
  584. continue;
  585. }
  586. // Read a record.
  587. Record.clear();
  588. switch (Stream.ReadRecord(Code, Record)) {
  589. default: // Default behavior: unknown type.
  590. break;
  591. case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
  592. if (ConvertToString(Record, 1, TypeName))
  593. return Error("Invalid TST_ENTRY record");
  594. unsigned TypeID = Record[0];
  595. if (TypeID >= TypeList.size())
  596. return Error("Invalid Type ID in TST_ENTRY record");
  597. TheModule->addTypeName(TypeName, TypeList[TypeID].get());
  598. TypeName.clear();
  599. break;
  600. }
  601. }
  602. }
  603. bool BitcodeReader::ParseValueSymbolTable() {
  604. if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
  605. return Error("Malformed block record");
  606. SmallVector<uint64_t, 64> Record;
  607. // Read all the records for this value table.
  608. SmallString<128> ValueName;
  609. while (1) {
  610. unsigned Code = Stream.ReadCode();
  611. if (Code == bitc::END_BLOCK) {
  612. if (Stream.ReadBlockEnd())
  613. return Error("Error at end of value symbol table block");
  614. return false;
  615. }
  616. if (Code == bitc::ENTER_SUBBLOCK) {
  617. // No known subblocks, always skip them.
  618. Stream.ReadSubBlockID();
  619. if (Stream.SkipBlock())
  620. return Error("Malformed block record");
  621. continue;
  622. }
  623. if (Code == bitc::DEFINE_ABBREV) {
  624. Stream.ReadAbbrevRecord();
  625. continue;
  626. }
  627. // Read a record.
  628. Record.clear();
  629. switch (Stream.ReadRecord(Code, Record)) {
  630. default: // Default behavior: unknown type.
  631. break;
  632. case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
  633. if (ConvertToString(Record, 1, ValueName))
  634. return Error("Invalid VST_ENTRY record");
  635. unsigned ValueID = Record[0];
  636. if (ValueID >= ValueList.size())
  637. return Error("Invalid Value ID in VST_ENTRY record");
  638. Value *V = ValueList[ValueID];
  639. V->setName(StringRef(ValueName.data(), ValueName.size()));
  640. ValueName.clear();
  641. break;
  642. }
  643. case bitc::VST_CODE_BBENTRY: {
  644. if (ConvertToString(Record, 1, ValueName))
  645. return Error("Invalid VST_BBENTRY record");
  646. BasicBlock *BB = getBasicBlock(Record[0]);
  647. if (BB == 0)
  648. return Error("Invalid BB ID in VST_BBENTRY record");
  649. BB->setName(StringRef(ValueName.data(), ValueName.size()));
  650. ValueName.clear();
  651. break;
  652. }
  653. }
  654. }
  655. }
  656. bool BitcodeReader::ParseMetadata() {
  657. unsigned NextMDValueNo = MDValueList.size();
  658. if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
  659. return Error("Malformed block record");
  660. SmallVector<uint64_t, 64> Record;
  661. // Read all the records.
  662. while (1) {
  663. unsigned Code = Stream.ReadCode();
  664. if (Code == bitc::END_BLOCK) {
  665. if (Stream.ReadBlockEnd())
  666. return Error("Error at end of PARAMATTR block");
  667. return false;
  668. }
  669. if (Code == bitc::ENTER_SUBBLOCK) {
  670. // No known subblocks, always skip them.
  671. Stream.ReadSubBlockID();
  672. if (Stream.SkipBlock())
  673. return Error("Malformed block record");
  674. continue;
  675. }
  676. if (Code == bitc::DEFINE_ABBREV) {
  677. Stream.ReadAbbrevRecord();
  678. continue;
  679. }
  680. bool IsFunctionLocal = false;
  681. // Read a record.
  682. Record.clear();
  683. switch (Stream.ReadRecord(Code, Record)) {
  684. default: // Default behavior: ignore.
  685. break;
  686. case bitc::METADATA_NAME: {
  687. // Read named of the named metadata.
  688. unsigned NameLength = Record.size();
  689. SmallString<8> Name;
  690. Name.resize(NameLength);
  691. for (unsigned i = 0; i != NameLength; ++i)
  692. Name[i] = Record[i];
  693. Record.clear();
  694. Code = Stream.ReadCode();
  695. // METADATA_NAME is always followed by METADATA_NAMED_NODE.
  696. if (Stream.ReadRecord(Code, Record) != bitc::METADATA_NAMED_NODE)
  697. assert ( 0 && "Inavlid Named Metadata record");
  698. // Read named metadata elements.
  699. unsigned Size = Record.size();
  700. SmallVector<MDNode *, 8> Elts;
  701. for (unsigned i = 0; i != Size; ++i) {
  702. if (Record[i] == ~0U) {
  703. Elts.push_back(NULL);
  704. continue;
  705. }
  706. MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
  707. if (MD == 0)
  708. return Error("Malformed metadata record");
  709. Elts.push_back(MD);
  710. }
  711. Value *V = NamedMDNode::Create(Context, Name.str(), Elts.data(),
  712. Elts.size(), TheModule);
  713. MDValueList.AssignValue(V, NextMDValueNo++);
  714. break;
  715. }
  716. case bitc::METADATA_FN_NODE:
  717. IsFunctionLocal = true;
  718. // fall-through
  719. case bitc::METADATA_NODE: {
  720. if (Record.empty() || Record.size() % 2 == 1)
  721. return Error("Invalid METADATA_NODE record");
  722. unsigned Size = Record.size();
  723. SmallVector<Value*, 8> Elts;
  724. for (unsigned i = 0; i != Size; i += 2) {
  725. const Type *Ty = getTypeByID(Record[i], false);
  726. if (Ty->isMetadataTy())
  727. Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
  728. else if (!Ty->isVoidTy())
  729. Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
  730. else
  731. Elts.push_back(NULL);
  732. }
  733. Value *V = MDNode::getWhenValsUnresolved(Context, &Elts[0], Elts.size(),
  734. IsFunctionLocal);
  735. IsFunctionLocal = false;
  736. MDValueList.AssignValue(V, NextMDValueNo++);
  737. break;
  738. }
  739. case bitc::METADATA_STRING: {
  740. unsigned MDStringLength = Record.size();
  741. SmallString<8> String;
  742. String.resize(MDStringLength);
  743. for (unsigned i = 0; i != MDStringLength; ++i)
  744. String[i] = Record[i];
  745. Value *V = MDString::get(Context,
  746. StringRef(String.data(), String.size()));
  747. MDValueList.AssignValue(V, NextMDValueNo++);
  748. break;
  749. }
  750. case bitc::METADATA_KIND: {
  751. unsigned RecordLength = Record.size();
  752. if (Record.empty() || RecordLength < 2)
  753. return Error("Invalid METADATA_KIND record");
  754. SmallString<8> Name;
  755. Name.resize(RecordLength-1);
  756. unsigned Kind = Record[0];
  757. (void) Kind;
  758. for (unsigned i = 1; i != RecordLength; ++i)
  759. Name[i-1] = Record[i];
  760. unsigned NewKind = TheModule->getMDKindID(Name.str());
  761. assert(Kind == NewKind &&
  762. "FIXME: Unable to handle custom metadata mismatch!");(void)NewKind;
  763. break;
  764. }
  765. }
  766. }
  767. }
  768. /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
  769. /// the LSB for dense VBR encoding.
  770. static uint64_t DecodeSignRotatedValue(uint64_t V) {
  771. if ((V & 1) == 0)
  772. return V >> 1;
  773. if (V != 1)
  774. return -(V >> 1);
  775. // There is no such thing as -0 with integers. "-0" really means MININT.
  776. return 1ULL << 63;
  777. }
  778. /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
  779. /// values and aliases that we can.
  780. bool BitcodeReader::ResolveGlobalAndAliasInits() {
  781. std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
  782. std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
  783. GlobalInitWorklist.swap(GlobalInits);
  784. AliasInitWorklist.swap(AliasInits);
  785. while (!GlobalInitWorklist.empty()) {
  786. unsigned ValID = GlobalInitWorklist.back().second;
  787. if (ValID >= ValueList.size()) {
  788. // Not ready to resolve this yet, it requires something later in the file.
  789. GlobalInits.push_back(GlobalInitWorklist.back());
  790. } else {
  791. if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
  792. GlobalInitWorklist.back().first->setInitializer(C);
  793. else
  794. return Error("Global variable initializer is not a constant!");
  795. }
  796. GlobalInitWorklist.pop_back();
  797. }
  798. while (!AliasInitWorklist.empty()) {
  799. unsigned ValID = AliasInitWorklist.back().second;
  800. if (ValID >= ValueList.size()) {
  801. AliasInits.push_back(AliasInitWorklist.back());
  802. } else {
  803. if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
  804. AliasInitWorklist.back().first->setAliasee(C);
  805. else
  806. return Error("Alias initializer is not a constant!");
  807. }
  808. AliasInitWorklist.pop_back();
  809. }
  810. return false;
  811. }
  812. bool BitcodeReader::ParseConstants() {
  813. if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
  814. return Error("Malformed block record");
  815. SmallVector<uint64_t, 64> Record;
  816. // Read all the records for this value table.
  817. const Type *CurTy = Type::getInt32Ty(Context);
  818. unsigned NextCstNo = ValueList.size();
  819. while (1) {
  820. unsigned Code = Stream.ReadCode();
  821. if (Code == bitc::END_BLOCK)
  822. break;
  823. if (Code == bitc::ENTER_SUBBLOCK) {
  824. // No known subblocks, always skip them.
  825. Stream.ReadSubBlockID();
  826. if (Stream.SkipBlock())
  827. return Error("Malformed block record");
  828. continue;
  829. }
  830. if (Code == bitc::DEFINE_ABBREV) {
  831. Stream.ReadAbbrevRecord();
  832. continue;
  833. }
  834. // Read a record.
  835. Record.clear();
  836. Value *V = 0;
  837. unsigned BitCode = Stream.ReadRecord(Code, Record);
  838. switch (BitCode) {
  839. default: // Default behavior: unknown constant
  840. case bitc::CST_CODE_UNDEF: // UNDEF
  841. V = UndefValue::get(CurTy);
  842. break;
  843. case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
  844. if (Record.empty())
  845. return Error("Malformed CST_SETTYPE record");
  846. if (Record[0] >= TypeList.size())
  847. return Error("Invalid Type ID in CST_SETTYPE record");
  848. CurTy = TypeList[Record[0]];
  849. continue; // Skip the ValueList manipulation.
  850. case bitc::CST_CODE_NULL: // NULL
  851. V = Constant::getNullValue(CurTy);
  852. break;
  853. case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
  854. if (!CurTy->isIntegerTy() || Record.empty())
  855. return Error("Invalid CST_INTEGER record");
  856. V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
  857. break;
  858. case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
  859. if (!CurTy->isIntegerTy() || Record.empty())
  860. return Error("Invalid WIDE_INTEGER record");
  861. unsigned NumWords = Record.size();
  862. SmallVector<uint64_t, 8> Words;
  863. Words.resize(NumWords);
  864. for (unsigned i = 0; i != NumWords; ++i)
  865. Words[i] = DecodeSignRotatedValue(Record[i]);
  866. V = ConstantInt::get(Context,
  867. APInt(cast<IntegerType>(CurTy)->getBitWidth(),
  868. NumWords, &Words[0]));
  869. break;
  870. }
  871. case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
  872. if (Record.empty())
  873. return Error("Invalid FLOAT record");
  874. if (CurTy->isFloatTy())
  875. V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
  876. else if (CurTy->isDoubleTy())
  877. V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
  878. else if (CurTy->isX86_FP80Ty()) {
  879. // Bits are not stored the same way as a normal i80 APInt, compensate.
  880. uint64_t Rearrange[2];
  881. Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
  882. Rearrange[1] = Record[0] >> 48;
  883. V = ConstantFP::get(Context, APFloat(APInt(80, 2, Rearrange)));
  884. } else if (CurTy->isFP128Ty())
  885. V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0]), true));
  886. else if (CurTy->isPPC_FP128Ty())
  887. V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0])));
  888. else
  889. V = UndefValue::get(CurTy);
  890. break;
  891. }
  892. case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
  893. if (Record.empty())
  894. return Error("Invalid CST_AGGREGATE record");
  895. unsigned Size = Record.size();
  896. std::vector<Constant*> Elts;
  897. if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
  898. for (unsigned i = 0; i != Size; ++i)
  899. Elts.push_back(ValueList.getConstantFwdRef(Record[i],
  900. STy->getElementType(i)));
  901. V = ConstantStruct::get(STy, Elts);
  902. } else if (const UnionType *UnTy = dyn_cast<UnionType>(CurTy)) {
  903. uint64_t Index = Record[0];
  904. Constant *Val = ValueList.getConstantFwdRef(Record[1],
  905. UnTy->getElementType(Index));
  906. V = ConstantUnion::get(UnTy, Val);
  907. } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
  908. const Type *EltTy = ATy->getElementType();
  909. for (unsigned i = 0; i != Size; ++i)
  910. Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
  911. V = ConstantArray::get(ATy, Elts);
  912. } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
  913. const Type *EltTy = VTy->getElementType();
  914. for (unsigned i = 0; i != Size; ++i)
  915. Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
  916. V = ConstantVector::get(Elts);
  917. } else {
  918. V = UndefValue::get(CurTy);
  919. }
  920. break;
  921. }
  922. case bitc::CST_CODE_STRING: { // STRING: [values]
  923. if (Record.empty())
  924. return Error("Invalid CST_AGGREGATE record");
  925. const ArrayType *ATy = cast<ArrayType>(CurTy);
  926. const Type *EltTy = ATy->getElementType();
  927. unsigned Size = Record.size();
  928. std::vector<Constant*> Elts;
  929. for (unsigned i = 0; i != Size; ++i)
  930. Elts.push_back(ConstantInt::get(EltTy, Record[i]));
  931. V = ConstantArray::get(ATy, Elts);
  932. break;
  933. }
  934. case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
  935. if (Record.empty())
  936. return Error("Invalid CST_AGGREGATE record");
  937. const ArrayType *ATy = cast<ArrayType>(CurTy);
  938. const Type *EltTy = ATy->getElementType();
  939. unsigned Size = Record.size();
  940. std::vector<Constant*> Elts;
  941. for (unsigned i = 0; i != Size; ++i)
  942. Elts.push_back(ConstantInt::get(EltTy, Record[i]));
  943. Elts.push_back(Constant::getNullValue(EltTy));
  944. V = ConstantArray::get(ATy, Elts);
  945. break;
  946. }
  947. case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
  948. if (Record.size() < 3) return Error("Invalid CE_BINOP record");
  949. int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
  950. if (Opc < 0) {
  951. V = UndefValue::get(CurTy); // Unknown binop.
  952. } else {
  953. Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
  954. Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
  955. unsigned Flags = 0;
  956. if (Record.size() >= 4) {
  957. if (Opc == Instruction::Add ||
  958. Opc == Instruction::Sub ||
  959. Opc == Instruction::Mul) {
  960. if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
  961. Flags |= OverflowingBinaryOperator::NoSignedWrap;
  962. if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
  963. Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
  964. } else if (Opc == Instruction::SDiv) {
  965. if (Record[3] & (1 << bitc::SDIV_EXACT))
  966. Flags |= SDivOperator::IsExact;
  967. }
  968. }
  969. V = ConstantExpr::get(Opc, LHS, RHS, Flags);
  970. }
  971. break;
  972. }
  973. case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
  974. if (Record.size() < 3) return Error("Invalid CE_CAST record");
  975. int Opc = GetDecodedCastOpcode(Record[0]);
  976. if (Opc < 0) {
  977. V = UndefValue::get(CurTy); // Unknown cast.
  978. } else {
  979. const Type *OpTy = getTypeByID(Record[1]);
  980. if (!OpTy) return Error("Invalid CE_CAST record");
  981. Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
  982. V = ConstantExpr::getCast(Opc, Op, CurTy);
  983. }
  984. break;
  985. }
  986. case bitc::CST_CODE_CE_INBOUNDS_GEP:
  987. case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
  988. if (Record.size() & 1) return Error("Invalid CE_GEP record");
  989. SmallVector<Constant*, 16> Elts;
  990. for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
  991. const Type *ElTy = getTypeByID(Record[i]);
  992. if (!ElTy) return Error("Invalid CE_GEP record");
  993. Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
  994. }
  995. if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
  996. V = ConstantExpr::getInBoundsGetElementPtr(Elts[0], &Elts[1],
  997. Elts.size()-1);
  998. else
  999. V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1],
  1000. Elts.size()-1);
  1001. break;
  1002. }
  1003. case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
  1004. if (Record.size() < 3) return Error("Invalid CE_SELECT record");
  1005. V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
  1006. Type::getInt1Ty(Context)),
  1007. ValueList.getConstantFwdRef(Record[1],CurTy),
  1008. ValueList.getConstantFwdRef(Record[2],CurTy));
  1009. break;
  1010. case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
  1011. if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
  1012. const VectorType *OpTy =
  1013. dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
  1014. if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
  1015. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  1016. Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
  1017. V = ConstantExpr::getExtractElement(Op0, Op1);
  1018. break;
  1019. }
  1020. case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
  1021. const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
  1022. if (Record.size() < 3 || OpTy == 0)
  1023. return Error("Invalid CE_INSERTELT record");
  1024. Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
  1025. Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
  1026. OpTy->getElementType());
  1027. Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
  1028. V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
  1029. break;
  1030. }
  1031. case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
  1032. const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
  1033. if (Record.size() < 3 || OpTy == 0)
  1034. return Error("Invalid CE_SHUFFLEVEC record");
  1035. Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
  1036. Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
  1037. const Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
  1038. OpTy->getNumElements());
  1039. Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
  1040. V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
  1041. break;
  1042. }
  1043. case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
  1044. const VectorType *RTy = dyn_cast<VectorType>(CurTy);
  1045. const VectorType *OpTy = dyn_cast<VectorType>(getTypeByID(Record[0]));
  1046. if (Record.size() < 4 || RTy == 0 || OpTy == 0)
  1047. return Error("Invalid CE_SHUFVEC_EX record");
  1048. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  1049. Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
  1050. const Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
  1051. RTy->getNumElements());
  1052. Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
  1053. V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
  1054. break;
  1055. }
  1056. case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
  1057. if (Record.size() < 4) return Error("Invalid CE_CMP record");
  1058. const Type *OpTy = getTypeByID(Record[0]);
  1059. if (OpTy == 0) return Error("Invalid CE_CMP record");
  1060. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  1061. Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
  1062. if (OpTy->isFPOrFPVectorTy())
  1063. V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
  1064. else
  1065. V = ConstantExpr::getICmp(Record[3], Op0, Op1);
  1066. break;
  1067. }
  1068. case bitc::CST_CODE_INLINEASM: {
  1069. if (Record.size() < 2) return Error("Invalid INLINEASM record");
  1070. std::string AsmStr, ConstrStr;
  1071. bool HasSideEffects = Record[0] & 1;
  1072. bool IsAlignStack = Record[0] >> 1;
  1073. unsigned AsmStrSize = Record[1];
  1074. if (2+AsmStrSize >= Record.size())
  1075. return Error("Invalid INLINEASM record");
  1076. unsigned ConstStrSize = Record[2+AsmStrSize];
  1077. if (3+AsmStrSize+ConstStrSize > Record.size())
  1078. return Error("Invalid INLINEASM record");
  1079. for (unsigned i = 0; i != AsmStrSize; ++i)
  1080. AsmStr += (char)Record[2+i];
  1081. for (unsigned i = 0; i != ConstStrSize; ++i)
  1082. ConstrStr += (char)Record[3+AsmStrSize+i];
  1083. const PointerType *PTy = cast<PointerType>(CurTy);
  1084. V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
  1085. AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
  1086. break;
  1087. }
  1088. case bitc::CST_CODE_BLOCKADDRESS:{
  1089. if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
  1090. const Type *FnTy = getTypeByID(Record[0]);
  1091. if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
  1092. Function *Fn =
  1093. dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
  1094. if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
  1095. GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
  1096. Type::getInt8Ty(Context),
  1097. false, GlobalValue::InternalLinkage,
  1098. 0, "");
  1099. BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
  1100. V = FwdRef;
  1101. break;
  1102. }
  1103. }
  1104. ValueList.AssignValue(V, NextCstNo);
  1105. ++NextCstNo;
  1106. }
  1107. if (NextCstNo != ValueList.size())
  1108. return Error("Invalid constant reference!");
  1109. if (Stream.ReadBlockEnd())
  1110. return Error("Error at end of constants block");
  1111. // Once all the constants have been read, go through and resolve forward
  1112. // references.
  1113. ValueList.ResolveConstantForwardRefs();
  1114. return false;
  1115. }
  1116. /// RememberAndSkipFunctionBody - When we see the block for a function body,
  1117. /// remember where it is and then skip it. This lets us lazily deserialize the
  1118. /// functions.
  1119. bool BitcodeReader::RememberAndSkipFunctionBody() {
  1120. // Get the function we are talking about.
  1121. if (FunctionsWithBodies.empty())
  1122. return Error("Insufficient function protos");
  1123. Function *Fn = FunctionsWithBodies.back();
  1124. FunctionsWithBodies.pop_back();
  1125. // Save the current stream state.
  1126. uint64_t CurBit = Stream.GetCurrentBitNo();
  1127. DeferredFunctionInfo[Fn] = CurBit;
  1128. // Skip over the function block for now.
  1129. if (Stream.SkipBlock())
  1130. return Error("Malformed block record");
  1131. return false;
  1132. }
  1133. bool BitcodeReader::ParseModule() {
  1134. if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
  1135. return Error("Malformed block record");
  1136. SmallVector<uint64_t, 64> Record;
  1137. std::vector<std::string> SectionTable;
  1138. std::vector<std::string> GCTable;
  1139. // Read all the records for this module.
  1140. while (!Stream.AtEndOfStream()) {
  1141. unsigned Code = Stream.ReadCode();
  1142. if (Code == bitc::END_BLOCK) {
  1143. if (Stream.ReadBlockEnd())
  1144. return Error("Error at end of module block");
  1145. // Patch the initializers for globals and aliases up.
  1146. ResolveGlobalAndAliasInits();
  1147. if (!GlobalInits.empty() || !AliasInits.empty())
  1148. return Error("Malformed global initializer set");
  1149. if (!FunctionsWithBodies.empty())
  1150. return Error("Too few function bodies found");
  1151. // Look for intrinsic functions which need to be upgraded at some point
  1152. for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
  1153. FI != FE; ++FI) {
  1154. Function* NewFn;
  1155. if (UpgradeIntrinsicFunction(FI, NewFn))
  1156. UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
  1157. }
  1158. // Force deallocation of memory for these vectors to favor the client that
  1159. // want lazy deserialization.
  1160. std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
  1161. std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
  1162. std::vector<Function*>().swap(FunctionsWithBodies);
  1163. return false;
  1164. }
  1165. if (Code == bitc::ENTER_SUBBLOCK) {
  1166. switch (Stream.ReadSubBlockID()) {
  1167. default: // Skip unknown content.
  1168. if (Stream.SkipBlock())
  1169. return Error("Malformed block record");
  1170. break;
  1171. case bitc::BLOCKINFO_BLOCK_ID:
  1172. if (Stream.ReadBlockInfoBlock())
  1173. return Error("Malformed BlockInfoBlock");
  1174. break;
  1175. case bitc::PARAMATTR_BLOCK_ID:
  1176. if (ParseAttributeBlock())
  1177. return true;
  1178. break;
  1179. case bitc::TYPE_BLOCK_ID:
  1180. if (ParseTypeTable())
  1181. return true;
  1182. break;
  1183. case bitc::TYPE_SYMTAB_BLOCK_ID:
  1184. if (ParseTypeSymbolTable())
  1185. return true;
  1186. break;
  1187. case bitc::VALUE_SYMTAB_BLOCK_ID:
  1188. if (ParseValueSymbolTable())
  1189. return true;
  1190. break;
  1191. case bitc::CONSTANTS_BLOCK_ID:
  1192. if (ParseConstants() || ResolveGlobalAndAliasInits())
  1193. return true;
  1194. break;
  1195. case bitc::METADATA_BLOCK_ID:
  1196. if (ParseMetadata())
  1197. return true;
  1198. break;
  1199. case bitc::FUNCTION_BLOCK_ID:
  1200. // If this is the first function body we've seen, reverse the
  1201. // FunctionsWithBodies list.
  1202. if (!HasReversedFunctionsWithBodies) {
  1203. std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
  1204. HasReversedFunctionsWithBodies = true;
  1205. }
  1206. if (RememberAndSkipFunctionBody())
  1207. return true;
  1208. break;
  1209. }
  1210. continue;
  1211. }
  1212. if (Code == bitc::DEFINE_ABBREV) {
  1213. Stream.ReadAbbrevRecord();
  1214. continue;
  1215. }
  1216. // Read a record.
  1217. switch (Stream.ReadRecord(Code, Record)) {
  1218. default: break; // Default behavior, ignore unknown content.
  1219. case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
  1220. if (Record.size() < 1)
  1221. return Error("Malformed MODULE_CODE_VERSION");
  1222. // Only version #0 is supported so far.
  1223. if (Record[0] != 0)
  1224. return Error("Unknown bitstream version!");
  1225. break;
  1226. case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
  1227. std::string S;
  1228. if (ConvertToString(Record, 0, S))
  1229. return Error("Invalid MODULE_CODE_TRIPLE record");
  1230. TheModule->setTargetTriple(S);
  1231. break;
  1232. }
  1233. case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
  1234. std::string S;
  1235. if (ConvertToString(Record, 0, S))
  1236. return Error("Invalid MODULE_CODE_DATALAYOUT record");
  1237. TheModule->setDataLayout(S);
  1238. break;
  1239. }
  1240. case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
  1241. std::string S;
  1242. if (ConvertToString(Record, 0, S))
  1243. return Error("Invalid MODULE_CODE_ASM record");
  1244. TheModule->setModuleInlineAsm(S);
  1245. break;
  1246. }
  1247. case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
  1248. std::string S;
  1249. if (ConvertToString(Record, 0, S))
  1250. return Error("Invalid MODULE_CODE_DEPLIB record");
  1251. TheModule->addLibrary(S);
  1252. break;
  1253. }
  1254. case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
  1255. std::string S;
  1256. if (ConvertToString(Record, 0, S))
  1257. return Error("Invalid MODULE_CODE_SECTIONNAME record");
  1258. SectionTable.push_back(S);
  1259. break;
  1260. }
  1261. case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
  1262. std::string S;
  1263. if (ConvertToString(Record, 0, S))
  1264. return Error("Invalid MODULE_CODE_GCNAME record");
  1265. GCTable.push_back(S);
  1266. break;
  1267. }
  1268. // GLOBALVAR: [pointer type, isconst, initid,
  1269. // linkage, alignment, section, visibility, threadlocal]
  1270. case bitc::MODULE_CODE_GLOBALVAR: {
  1271. if (Record.size() < 6)
  1272. return Error("Invalid MODULE_CODE_GLOBALVAR record");
  1273. const Type *Ty = getTypeByID(Record[0]);
  1274. if (!Ty->isPointerTy())
  1275. return Error("Global not a pointer type!");
  1276. unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
  1277. Ty = cast<PointerType>(Ty)->getElementType();
  1278. bool isConstant = Record[1];
  1279. GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
  1280. unsigned Alignment = (1 << Record[4]) >> 1;
  1281. std::string Section;
  1282. if (Record[5]) {
  1283. if (Record[5]-1 >= SectionTable.size())
  1284. return Error("Invalid section ID");
  1285. Section = SectionTable[Record[5]-1];
  1286. }
  1287. GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
  1288. if (Record.size() > 6)
  1289. Visibility = GetDecodedVisibility(Record[6]);
  1290. bool isThreadLocal = false;
  1291. if (Record.size() > 7)
  1292. isThreadLocal = Record[7];
  1293. GlobalVariable *NewGV =
  1294. new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
  1295. isThreadLocal, AddressSpace);
  1296. NewGV->setAlignment(Alignment);
  1297. if (!Section.empty())
  1298. NewGV->setSection(Section);
  1299. NewGV->setVisibility(Visibility);
  1300. NewGV->setThreadLocal(isThreadLocal);
  1301. ValueList.push_back(NewGV);
  1302. // Remember which value to use for the global initializer.
  1303. if (unsigned InitID = Record[2])
  1304. GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
  1305. break;
  1306. }
  1307. // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
  1308. // alignment, section, visibility, gc]
  1309. case bitc::MODULE_CODE_FUNCTION: {
  1310. if (Record.size() < 8)
  1311. return Error("Invalid MODULE_CODE_FUNCTION record");
  1312. const Type *Ty = getTypeByID(Record[0]);
  1313. if (!Ty->isPointerTy())
  1314. return Error("Function not a pointer type!");
  1315. const FunctionType *FTy =
  1316. dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
  1317. if (!FTy)
  1318. return Error("Function not a pointer to function type!");
  1319. Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
  1320. "", TheModule);
  1321. Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
  1322. bool isProto = Record[2];
  1323. Func->setLinkage(GetDecodedLinkage(Record[3]));
  1324. Func->setAttributes(getAttributes(Record[4]));
  1325. Func->setAlignment((1 << Record[5]) >> 1);
  1326. if (Record[6]) {
  1327. if (Record[6]-1 >= SectionTable.size())
  1328. return Error("Invalid section ID");
  1329. Func->setSection(SectionTable[Record[6]-1]);
  1330. }
  1331. Func->setVisibility(GetDecodedVisibility(Record[7]));
  1332. if (Record.size() > 8 && Record[8]) {
  1333. if (Record[8]-1 > GCTable.size())
  1334. return Error("Invalid GC ID");
  1335. Func->setGC(GCTable[Record[8]-1].c_str());
  1336. }
  1337. ValueList.push_back(Func);
  1338. // If this is a function with a body, remember the prototype we are
  1339. // creating now, so that we can match up the body with them later.
  1340. if (!isProto)
  1341. FunctionsWithBodies.push_back(Func);
  1342. break;
  1343. }
  1344. // ALIAS: [alias type, aliasee val#, linkage]
  1345. // ALIAS: [alias type, aliasee val#, linkage, visibility]
  1346. case bitc::MODULE_CODE_ALIAS: {
  1347. if (Record.size() < 3)
  1348. return Error("Invalid MODULE_ALIAS record");
  1349. const Type *Ty = getTypeByID(Record[0]);
  1350. if (!Ty->isPointerTy())
  1351. return Error("Function not a pointer type!");
  1352. GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
  1353. "", 0, TheModule);
  1354. // Old bitcode files didn't have visibility field.
  1355. if (Record.size() > 3)
  1356. NewGA->setVisibility(GetDecodedVisibility(Record[3]));
  1357. ValueList.push_back(NewGA);
  1358. AliasInits.push_back(std::make_pair(NewGA, Record[1]));
  1359. break;
  1360. }
  1361. /// MODULE_CODE_PURGEVALS: [numvals]
  1362. case bitc::MODULE_CODE_PURGEVALS:
  1363. // Trim down the value list to the specified size.
  1364. if (Record.size() < 1 || Record[0] > ValueList.size())
  1365. return Error("Invalid MODULE_PURGEVALS record");
  1366. ValueList.shrinkTo(Record[0]);
  1367. break;
  1368. }
  1369. Record.clear();
  1370. }
  1371. return Error("Premature end of bitstream");
  1372. }
  1373. bool BitcodeReader::ParseBitcodeInto(Module *M) {
  1374. TheModule = 0;
  1375. if (Buffer->getBufferSize() & 3)
  1376. return Error("Bitcode stream should be a multiple of 4 bytes in length");
  1377. unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
  1378. unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
  1379. // If we have a wrapper header, parse it and ignore the non-bc file contents.
  1380. // The magic number is 0x0B17C0DE stored in little endian.
  1381. if (isBitcodeWrapper(BufPtr, BufEnd))
  1382. if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
  1383. return Error("Invalid bitcode wrapper header");
  1384. StreamFile.init(BufPtr, BufEnd);
  1385. Stream.init(StreamFile);
  1386. // Sniff for the signature.
  1387. if (Stream.Read(8) != 'B' ||
  1388. Stream.Read(8) != 'C' ||
  1389. Stream.Read(4) != 0x0 ||
  1390. Stream.Read(4) != 0xC ||
  1391. Stream.Read(4) != 0xE ||
  1392. Stream.Read(4) != 0xD)
  1393. return Error("Invalid bitcode signature");
  1394. // We expect a number of well-defined blocks, though we don't necessarily
  1395. // need to understand them all.
  1396. while (!Stream.AtEndOfStream()) {
  1397. unsigned Code = Stream.ReadCode();
  1398. if (Code != bitc::ENTER_SUBBLOCK)
  1399. return Error("Invalid record at top-level");
  1400. unsigned BlockID = Stream.ReadSubBlockID();
  1401. // We only know the MODULE subblock ID.
  1402. switch (BlockID) {
  1403. case bitc::BLOCKINFO_BLOCK_ID:
  1404. if (Stream.ReadBlockInfoBlock())
  1405. return Error("Malformed BlockInfoBlock");
  1406. break;
  1407. case bitc::MODULE_BLOCK_ID:
  1408. // Reject multiple MODULE_BLOCK's in a single bitstream.
  1409. if (TheModule)
  1410. return Error("Multiple MODULE_BLOCKs in same stream");
  1411. TheModule = M;
  1412. if (ParseModule())
  1413. return true;
  1414. break;
  1415. default:
  1416. if (Stream.SkipBlock())
  1417. return Error("Malformed block record");
  1418. break;
  1419. }
  1420. }
  1421. return false;
  1422. }
  1423. /// ParseMetadataAttachment - Parse metadata attachments.
  1424. bool BitcodeReader::ParseMetadataAttachment() {
  1425. if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
  1426. return Error("Malformed block record");
  1427. SmallVector<uint64_t, 64> Record;
  1428. while(1) {
  1429. unsigned Code = Stream.ReadCode();
  1430. if (Code == bitc::END_BLOCK) {
  1431. if (Stream.ReadBlockEnd())
  1432. return Error("Error at end of PARAMATTR block");
  1433. break;
  1434. }
  1435. if (Code == bitc::DEFINE_ABBREV) {
  1436. Stream.ReadAbbrevRecord();
  1437. continue;
  1438. }
  1439. // Read a metadata attachment record.
  1440. Record.clear();
  1441. switch (Stream.ReadRecord(Code, Record)) {
  1442. default: // Default behavior: ignore.
  1443. break;
  1444. case bitc::METADATA_ATTACHMENT: {
  1445. unsigned RecordLength = Record.size();
  1446. if (Record.empty() || (RecordLength - 1) % 2 == 1)
  1447. return Error ("Invalid METADATA_ATTACHMENT reader!");
  1448. Instruction *Inst = InstructionList[Record[0]];
  1449. for (unsigned i = 1; i != RecordLength; i = i+2) {
  1450. unsigned Kind = Record[i];
  1451. Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
  1452. Inst->setMetadata(Kind, cast<MDNode>(Node));
  1453. }
  1454. break;
  1455. }
  1456. }
  1457. }
  1458. return false;
  1459. }
  1460. /// ParseFunctionBody - Lazily parse the specified function body block.
  1461. bool BitcodeReader::ParseFunctionBody(Function *F) {
  1462. if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
  1463. return Error("Malformed block record");
  1464. InstructionList.clear();
  1465. unsigned ModuleValueListSize = ValueList.size();
  1466. // Add all the function arguments to the value table.
  1467. for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
  1468. ValueList.push_back(I);
  1469. unsigned NextValueNo = ValueList.size();
  1470. BasicBlock *CurBB = 0;
  1471. unsigned CurBBNo = 0;
  1472. // Read all the records.
  1473. SmallVector<uint64_t, 64> Record;
  1474. while (1) {
  1475. unsigned Code = Stream.ReadCode();
  1476. if (Code == bitc::END_BLOCK) {
  1477. if (Stream.ReadBlockEnd())
  1478. return Error("Error at end of function block");
  1479. break;
  1480. }
  1481. if (Code == bitc::ENTER_SUBBLOCK) {
  1482. switch (Stream.ReadSubBlockID()) {
  1483. default: // Skip unknown content.
  1484. if (Stream.SkipBlock())
  1485. return Error("Malformed block record");
  1486. break;
  1487. case bitc::CONSTANTS_BLOCK_ID:
  1488. if (ParseConstants()) return true;
  1489. NextValueNo = ValueList.size();
  1490. break;
  1491. case bitc::VALUE_SYMTAB_BLOCK_ID:
  1492. if (ParseValueSymbolTable()) return true;
  1493. break;
  1494. case bitc::METADATA_ATTACHMENT_ID:
  1495. if (ParseMetadataAttachment()) return true;
  1496. break;
  1497. case bitc::METADATA_BLOCK_ID:
  1498. if (ParseMetadata()) return true;
  1499. break;
  1500. }
  1501. continue;
  1502. }
  1503. if (Code == bitc::DEFINE_ABBREV) {
  1504. Stream.ReadAbbrevRecord();
  1505. continue;
  1506. }
  1507. // Read a record.
  1508. Record.clear();
  1509. Instruction *I = 0;
  1510. unsigned BitCode = Stream.ReadRecord(Code, Record);
  1511. switch (BitCode) {
  1512. default: // Default behavior: reject
  1513. return Error("Unknown instruction");
  1514. case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
  1515. if (Record.size() < 1 || Record[0] == 0)
  1516. return Error("Invalid DECLAREBLOCKS record");
  1517. // Create all the basic blocks for the function.
  1518. FunctionBBs.resize(Record[0]);
  1519. for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
  1520. FunctionBBs[i] = BasicBlock::Create(Context, "", F);
  1521. CurBB = FunctionBBs[0];
  1522. continue;
  1523. case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
  1524. unsigned OpNum = 0;
  1525. Value *LHS, *RHS;
  1526. if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
  1527. getValue(Record, OpNum, LHS->getType(), RHS) ||
  1528. OpNum+1 > Record.size())
  1529. return Error("Invalid BINOP record");
  1530. int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
  1531. if (Opc == -1) return Error("Invalid BINOP record");
  1532. I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
  1533. InstructionList.push_back(I);
  1534. if (OpNum < Record.size()) {
  1535. if (Opc == Instruction::Add ||
  1536. Opc == Instruction::Sub ||
  1537. Opc == Instruction::Mul) {
  1538. if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
  1539. cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
  1540. if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
  1541. cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
  1542. } else if (Opc == Instruction::SDiv) {
  1543. if (Record[OpNum] & (1 << bitc::SDIV_EXACT))
  1544. cast<BinaryOperator>(I)->setIsExact(true);
  1545. }
  1546. }
  1547. break;
  1548. }
  1549. case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
  1550. unsigned OpNum = 0;
  1551. Value *Op;
  1552. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  1553. OpNum+2 != Record.size())
  1554. return Error("Invalid CAST record");
  1555. const Type *ResTy = getTypeByID(Record[OpNum]);
  1556. int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
  1557. if (Opc == -1 || ResTy == 0)
  1558. return Error("Invalid CAST record");
  1559. I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
  1560. InstructionList.push_back(I);
  1561. break;
  1562. }
  1563. case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
  1564. case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
  1565. unsigned OpNum = 0;
  1566. Value *BasePtr;
  1567. if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
  1568. return Error("Invalid GEP record");
  1569. SmallVector<Value*, 16> GEPIdx;
  1570. while (OpNum != Record.size()) {
  1571. Value *Op;
  1572. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  1573. return Error("Invalid GEP record");
  1574. GEPIdx.push_back(Op);
  1575. }
  1576. I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
  1577. InstructionList.push_back(I);
  1578. if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
  1579. cast<GetElementPtrInst>(I)->setIsInBounds(true);
  1580. break;
  1581. }
  1582. case bitc::FUNC_CODE_INST_EXTRACTVAL: {
  1583. // EXTRACTVAL: [opty, opval, n x indices]
  1584. unsigned OpNum = 0;
  1585. Value *Agg;
  1586. if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
  1587. return Error("Invalid EXTRACTVAL record");
  1588. SmallVector<unsigned, 4> EXTRACTVALIdx;
  1589. for (unsigned RecSize = Record.size();
  1590. OpNum != RecSize; ++OpNum) {
  1591. uint64_t Index = Record[OpNum];
  1592. if ((unsigned)Index != Index)
  1593. return Error("Invalid EXTRACTVAL index");
  1594. EXTRACTVALIdx.push_back((unsigned)Index);
  1595. }
  1596. I = ExtractValueInst::Create(Agg,
  1597. EXTRACTVALIdx.begin(), EXTRACTVALIdx.end());
  1598. InstructionList.push_back(I);
  1599. break;
  1600. }
  1601. case bitc::FUNC_CODE_INST_INSERTVAL: {
  1602. // INSERTVAL: [opty, opval, opty, opval, n x indices]
  1603. unsigned OpNum = 0;
  1604. Value *Agg;
  1605. if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
  1606. return Error("Invalid INSERTVAL record");
  1607. Value *Val;
  1608. if (getValueTypePair(Record, OpNum, NextValueNo, Val))
  1609. return Error("Invalid INSERTVAL record");
  1610. SmallVector<unsigned, 4> INSERTVALIdx;
  1611. for (unsigned RecSize = Record.size();
  1612. OpNum != RecSize; ++OpNum) {
  1613. uint64_t Index = Record[OpNum];
  1614. if ((unsigned)Index != Index)
  1615. return Error("Invalid INSERTVAL index");
  1616. INSERTVALIdx.push_back((unsigned)Index);
  1617. }
  1618. I = InsertValueInst::Create(Agg, Val,
  1619. INSERTVALIdx.begin(), INSERTVALIdx.end());
  1620. InstructionList.push_back(I);
  1621. break;
  1622. }
  1623. case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
  1624. // obsolete form of select
  1625. // handles select i1 ... in old bitcode
  1626. unsigned OpNum = 0;
  1627. Value *TrueVal, *FalseVal, *Cond;
  1628. if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
  1629. getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
  1630. getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
  1631. return Error("Invalid SELECT record");
  1632. I = SelectInst::Create(Cond, TrueVal, FalseVal);
  1633. InstructionList.push_back(I);
  1634. break;
  1635. }
  1636. case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
  1637. // new form of select
  1638. // handles select i1 or select [N x i1]
  1639. unsigned OpNum = 0;
  1640. Value *TrueVal, *FalseVal, *Cond;
  1641. if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
  1642. getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
  1643. getValueTypePair(Record, OpNum, NextValueNo, Cond))
  1644. return Error("Invalid SELECT record");
  1645. // select condition can be either i1 or [N x i1]
  1646. if (const VectorType* vector_type =
  1647. dyn_cast<const VectorType>(Cond->getType())) {
  1648. // expect <n x i1>
  1649. if (vector_type->getElementType() != Type::getInt1Ty(Context))
  1650. return Error("Invalid SELECT condition type");
  1651. } else {
  1652. // expect i1
  1653. if (Cond->getType() != Type::getInt1Ty(Context))
  1654. return Error("Invalid SELECT condition type");
  1655. }
  1656. I = SelectInst::Create(Cond, TrueVal, FalseVal);
  1657. InstructionList.push_back(I);
  1658. break;
  1659. }
  1660. case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
  1661. unsigned OpNum = 0;
  1662. Value *Vec, *Idx;
  1663. if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
  1664. getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
  1665. return Error("Invalid EXTRACTELT record");
  1666. I = ExtractElementInst::Create(Vec, Idx);
  1667. InstructionList.push_back(I);
  1668. break;
  1669. }
  1670. case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
  1671. unsigned OpNum = 0;
  1672. Value *Vec, *Elt, *Idx;
  1673. if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
  1674. getValue(Record, OpNum,
  1675. cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
  1676. getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
  1677. return Error("Invalid INSERTELT record");
  1678. I = InsertElementInst::Create(Vec, Elt, Idx);
  1679. InstructionList.push_back(I);
  1680. break;
  1681. }
  1682. case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
  1683. unsigned OpNum = 0;
  1684. Value *Vec1, *Vec2, *Mask;
  1685. if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
  1686. getValue(Record, OpNum, Vec1->getType(), Vec2))
  1687. return Error("Invalid SHUFFLEVEC record");
  1688. if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
  1689. return Error("Invalid SHUFFLEVEC record");
  1690. I = new ShuffleVectorInst(Vec1, Vec2, Mask);
  1691. InstructionList.push_back(I);
  1692. break;
  1693. }
  1694. case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
  1695. // Old form of ICmp/FCmp returning bool
  1696. // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
  1697. // both legal on vectors but had different behaviour.
  1698. case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
  1699. // FCmp/ICmp returning bool or vector of bool
  1700. unsigned OpNum = 0;
  1701. Value *LHS, *RHS;
  1702. if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
  1703. getValue(Record, OpNum, LHS->getType(), RHS) ||
  1704. OpNum+1 != Record.size())
  1705. return Error("Invalid CMP record");
  1706. if (LHS->getType()->isFPOrFPVectorTy())
  1707. I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
  1708. else
  1709. I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
  1710. InstructionList.push_back(I);
  1711. break;
  1712. }
  1713. case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
  1714. if (Record.size() != 2)
  1715. return Error("Invalid GETRESULT record");
  1716. unsigned OpNum = 0;
  1717. Value *Op;
  1718. getValueTypePair(Record, OpNum, NextValueNo, Op);
  1719. unsigned Index = Record[1];
  1720. I = ExtractValueInst::Create(Op, Index);
  1721. InstructionList.push_back(I);
  1722. break;
  1723. }
  1724. case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
  1725. {
  1726. unsigned Size = Record.size();
  1727. if (Size == 0) {
  1728. I = ReturnInst::Create(Context);
  1729. InstructionList.push_back(I);
  1730. break;
  1731. }
  1732. unsigned OpNum = 0;
  1733. SmallVector<Value *,4> Vs;
  1734. do {
  1735. Value *Op = NULL;
  1736. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  1737. return Error("Invalid RET record");
  1738. Vs.push_back(Op);
  1739. } while(OpNum != Record.size());
  1740. const Type *ReturnType = F->getReturnType();
  1741. if (Vs.size() > 1 ||
  1742. (ReturnType->isStructTy() &&
  1743. (Vs.empty() || Vs[0]->getType() != ReturnType))) {
  1744. Value *RV = UndefValue::get(ReturnType);
  1745. for (unsigned i = 0, e = Vs.size(); i != e; ++i) {
  1746. I = InsertValueInst::Create(RV, Vs[i], i, "mrv");
  1747. InstructionList.push_back(I);
  1748. CurBB->getInstList().push_back(I);
  1749. ValueList.AssignValue(I, NextValueNo++);
  1750. RV = I;
  1751. }
  1752. I = ReturnInst::Create(Context, RV);
  1753. InstructionList.push_back(I);
  1754. break;
  1755. }
  1756. I = ReturnInst::Create(Context, Vs[0]);
  1757. InstructionList.push_back(I);
  1758. break;
  1759. }
  1760. case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
  1761. if (Record.size() != 1 && Record.size() != 3)
  1762. return Error("Invalid BR record");
  1763. BasicBlock *TrueDest = getBasicBlock(Record[0]);
  1764. if (TrueDest == 0)
  1765. return Error("Invalid BR record");
  1766. if (Record.size() == 1) {
  1767. I = BranchInst::Create(TrueDest);
  1768. InstructionList.push_back(I);
  1769. }
  1770. else {
  1771. BasicBlock *FalseDest = getBasicBlock(Record[1]);
  1772. Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
  1773. if (FalseDest == 0 || Cond == 0)
  1774. return Error("Invalid BR record");
  1775. I = BranchInst::Create(TrueDest, FalseDest, Cond);
  1776. InstructionList.push_back(I);
  1777. }
  1778. break;
  1779. }
  1780. case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
  1781. if (Record.size() < 3 || (Record.size() & 1) == 0)
  1782. return Error("Invalid SWITCH record");
  1783. const Type *OpTy = getTypeByID(Record[0]);
  1784. Value *Cond = getFnValueByID(Record[1], OpTy);
  1785. BasicBlock *Default = getBasicBlock(Record[2]);
  1786. if (OpTy == 0 || Cond == 0 || Default == 0)
  1787. return Error("Invalid SWITCH record");
  1788. unsigned NumCases = (Record.size()-3)/2;
  1789. SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
  1790. InstructionList.push_back(SI);
  1791. for (unsigned i = 0, e = NumCases; i != e; ++i) {
  1792. ConstantInt *CaseVal =
  1793. dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
  1794. BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
  1795. if (CaseVal == 0 || DestBB == 0) {
  1796. delete SI;
  1797. return Error("Invalid SWITCH record!");
  1798. }
  1799. SI->addCase(CaseVal, DestBB);
  1800. }
  1801. I = SI;
  1802. break;
  1803. }
  1804. case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
  1805. if (Record.size() < 2)
  1806. return Error("Invalid INDIRECTBR record");
  1807. const Type *OpTy = getTypeByID(Record[0]);
  1808. Value *Address = getFnValueByID(Record[1], OpTy);
  1809. if (OpTy == 0 || Address == 0)
  1810. return Error("Invalid INDIRECTBR record");
  1811. unsigned NumDests = Record.size()-2;
  1812. IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
  1813. InstructionList.push_back(IBI);
  1814. for (unsigned i = 0, e = NumDests; i != e; ++i) {
  1815. if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
  1816. IBI->addDestination(DestBB);
  1817. } else {
  1818. delete IBI;
  1819. return Error("Invalid INDIRECTBR record!");
  1820. }
  1821. }
  1822. I = IBI;
  1823. break;
  1824. }
  1825. case bitc::FUNC_CODE_INST_INVOKE: {
  1826. // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
  1827. if (Record.size() < 4) return Error("Invalid INVOKE record");
  1828. AttrListPtr PAL = getAttributes(Record[0]);
  1829. unsigned CCInfo = Record[1];
  1830. BasicBlock *NormalBB = getBasicBlock(Record[2]);
  1831. BasicBlock *UnwindBB = getBasicBlock(Record[3]);
  1832. unsigned OpNum = 4;
  1833. Value *Callee;
  1834. if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
  1835. return Error("Invalid INVOKE record");
  1836. const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
  1837. const FunctionType *FTy = !CalleeTy ? 0 :
  1838. dyn_cast<FunctionType>(CalleeTy->getElementType());
  1839. // Check that the right number of fixed parameters are here.
  1840. if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
  1841. Record.size() < OpNum+FTy->getNumParams())
  1842. return Error("Invalid INVOKE record");
  1843. SmallVector<Value*, 16> Ops;
  1844. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
  1845. Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
  1846. if (Ops.back() == 0) return Error("Invalid INVOKE record");
  1847. }
  1848. if (!FTy->isVarArg()) {
  1849. if (Record.size() != OpNum)
  1850. return Error("Invalid INVOKE record");
  1851. } else {
  1852. // Read type/value pairs for varargs params.
  1853. while (OpNum != Record.size()) {
  1854. Value *Op;
  1855. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  1856. return Error("Invalid INVOKE record");
  1857. Ops.push_back(Op);
  1858. }
  1859. }
  1860. I = InvokeInst::Create(Callee, NormalBB, UnwindBB,
  1861. Ops.begin(), Ops.end());
  1862. InstructionList.push_back(I);
  1863. cast<InvokeInst>(I)->setCallingConv(
  1864. static_cast<CallingConv::ID>(CCInfo));
  1865. cast<InvokeInst>(I)->setAttributes(PAL);
  1866. break;
  1867. }
  1868. case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
  1869. I = new UnwindInst(Context);
  1870. InstructionList.push_back(I);
  1871. break;
  1872. case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
  1873. I = new UnreachableInst(Context);
  1874. InstructionList.push_back(I);
  1875. break;
  1876. case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
  1877. if (Record.size() < 1 || ((Record.size()-1)&1))
  1878. return Error("Invalid PHI record");
  1879. const Type *Ty = getTypeByID(Record[0]);
  1880. if (!Ty) return Error("Invalid PHI record");
  1881. PHINode *PN = PHINode::Create(Ty);
  1882. InstructionList.push_back(PN);
  1883. PN->reserveOperandSpace((Record.size()-1)/2);
  1884. for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
  1885. Value *V = getFnValueByID(Record[1+i], Ty);
  1886. BasicBlock *BB = getBasicBlock(Record[2+i]);
  1887. if (!V || !BB) return Error("Invalid PHI record");
  1888. PN->addIncoming(V, BB);
  1889. }
  1890. I = PN;
  1891. break;
  1892. }
  1893. case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
  1894. // Autoupgrade malloc instruction to malloc call.
  1895. // FIXME: Remove in LLVM 3.0.
  1896. if (Record.size() < 3)
  1897. return Error("Invalid MALLOC record");
  1898. const PointerType *Ty =
  1899. dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
  1900. Value *Size = getFnValueByID(Record[1], Type::getInt32Ty(Context));
  1901. if (!Ty || !Size) return Error("Invalid MALLOC record");
  1902. if (!CurBB) return Error("Invalid malloc instruction with no BB");
  1903. const Type *Int32Ty = IntegerType::getInt32Ty(CurBB->getContext());
  1904. Constant *AllocSize = ConstantExpr::getSizeOf(Ty->getElementType());
  1905. AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, Int32Ty);
  1906. I = CallInst::CreateMalloc(CurBB, Int32Ty, Ty->getElementType(),
  1907. AllocSize, Size, NULL);
  1908. InstructionList.push_back(I);
  1909. break;
  1910. }
  1911. case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
  1912. unsigned OpNum = 0;
  1913. Value *Op;
  1914. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  1915. OpNum != Record.size())
  1916. return Error("Invalid FREE record");
  1917. if (!CurBB) return Error("Invalid free instruction with no BB");
  1918. I = CallInst::CreateFree(Op, CurBB);
  1919. InstructionList.push_back(I);
  1920. break;
  1921. }
  1922. case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
  1923. if (Record.size() < 3)
  1924. return Error("Invalid ALLOCA record");
  1925. const PointerType *Ty =
  1926. dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
  1927. Value *Size = getFnValueByID(Record[1], Type::getInt32Ty(Context));
  1928. unsigned Align = Record[2];
  1929. if (!Ty || !Size) return Error("Invalid ALLOCA record");
  1930. I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
  1931. InstructionList.push_back(I);
  1932. break;
  1933. }
  1934. case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
  1935. unsigned OpNum = 0;
  1936. Value *Op;
  1937. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  1938. OpNum+2 != Record.size())
  1939. return Error("Invalid LOAD record");
  1940. I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
  1941. InstructionList.push_back(I);
  1942. break;
  1943. }
  1944. case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
  1945. unsigned OpNum = 0;
  1946. Value *Val, *Ptr;
  1947. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
  1948. getValue(Record, OpNum,
  1949. cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
  1950. OpNum+2 != Record.size())
  1951. return Error("Invalid STORE record");
  1952. I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
  1953. InstructionList.push_back(I);
  1954. break;
  1955. }
  1956. case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
  1957. // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
  1958. unsigned OpNum = 0;
  1959. Value *Val, *Ptr;
  1960. if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
  1961. getValue(Record, OpNum,
  1962. PointerType::getUnqual(Val->getType()), Ptr)||
  1963. OpNum+2 != Record.size())
  1964. return Error("Invalid STORE record");
  1965. I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
  1966. InstructionList.push_back(I);
  1967. break;
  1968. }
  1969. case bitc::FUNC_CODE_INST_CALL: {
  1970. // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
  1971. if (Record.size() < 3)
  1972. return Error("Invalid CALL record");
  1973. AttrListPtr PAL = getAttributes(Record[0]);
  1974. unsigned CCInfo = Record[1];
  1975. unsigned OpNum = 2;
  1976. Value *Callee;
  1977. if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
  1978. return Error("Invalid CALL record");
  1979. const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
  1980. const FunctionType *FTy = 0;
  1981. if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
  1982. if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
  1983. return Error("Invalid CALL record");
  1984. SmallVector<Value*, 16> Args;
  1985. // Read the fixed params.
  1986. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
  1987. if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
  1988. Args.push_back(getBasicBlock(Record[OpNum]));
  1989. else
  1990. Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
  1991. if (Args.back() == 0) return Error("Invalid CALL record");
  1992. }
  1993. // Read type/value pairs for varargs params.
  1994. if (!FTy->isVarArg()) {
  1995. if (OpNum != Record.size())
  1996. return Error("Invalid CALL record");
  1997. } else {
  1998. while (OpNum != Record.size()) {
  1999. Value *Op;
  2000. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  2001. return Error("Invalid CALL record");
  2002. Args.push_back(Op);
  2003. }
  2004. }
  2005. I = CallInst::Create(Callee, Args.begin(), Args.end());
  2006. InstructionList.push_back(I);
  2007. cast<CallInst>(I)->setCallingConv(
  2008. static_cast<CallingConv::ID>(CCInfo>>1));
  2009. cast<CallInst>(I)->setTailCall(CCInfo & 1);
  2010. cast<CallInst>(I)->setAttributes(PAL);
  2011. break;
  2012. }
  2013. case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
  2014. if (Record.size() < 3)
  2015. return Error("Invalid VAARG record");
  2016. const Type *OpTy = getTypeByID(Record[0]);
  2017. Value *Op = getFnValueByID(Record[1], OpTy);
  2018. const Type *ResTy = getTypeByID(Record[2]);
  2019. if (!OpTy || !Op || !ResTy)
  2020. return Error("Invalid VAARG record");
  2021. I = new VAArgInst(Op, ResTy);
  2022. InstructionList.push_back(I);
  2023. break;
  2024. }
  2025. }
  2026. // Add instruction to end of current BB. If there is no current BB, reject
  2027. // this file.
  2028. if (CurBB == 0) {
  2029. delete I;
  2030. return Error("Invalid instruction with no BB");
  2031. }
  2032. CurBB->getInstList().push_back(I);
  2033. // If this was a terminator instruction, move to the next block.
  2034. if (isa<TerminatorInst>(I)) {
  2035. ++CurBBNo;
  2036. CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
  2037. }
  2038. // Non-void values get registered in the value table for future use.
  2039. if (I && !I->getType()->isVoidTy())
  2040. ValueList.AssignValue(I, NextValueNo++);
  2041. }
  2042. // Check the function list for unresolved values.
  2043. if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
  2044. if (A->getParent() == 0) {
  2045. // We found at least one unresolved value. Nuke them all to avoid leaks.
  2046. for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
  2047. if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
  2048. A->replaceAllUsesWith(UndefValue::get(A->getType()));
  2049. delete A;
  2050. }
  2051. }
  2052. return Error("Never resolved value found in function!");
  2053. }
  2054. }
  2055. // See if anything took the address of blocks in this function. If so,
  2056. // resolve them now.
  2057. /// BlockAddrFwdRefs - These are blockaddr references to basic blocks. These
  2058. /// are resolved lazily when functions are loaded.
  2059. DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
  2060. BlockAddrFwdRefs.find(F);
  2061. if (BAFRI != BlockAddrFwdRefs.end()) {
  2062. std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
  2063. for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
  2064. unsigned BlockIdx = RefList[i].first;
  2065. if (BlockIdx >= FunctionBBs.size())
  2066. return Error("Invalid blockaddress block #");
  2067. GlobalVariable *FwdRef = RefList[i].second;
  2068. FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
  2069. FwdRef->eraseFromParent();
  2070. }
  2071. BlockAddrFwdRefs.erase(BAFRI);
  2072. }
  2073. // Trim the value list down to the size it was before we parsed this function.
  2074. ValueList.shrinkTo(ModuleValueListSize);
  2075. std::vector<BasicBlock*>().swap(FunctionBBs);
  2076. return false;
  2077. }
  2078. //===----------------------------------------------------------------------===//
  2079. // GVMaterializer implementation
  2080. //===----------------------------------------------------------------------===//
  2081. bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
  2082. if (const Function *F = dyn_cast<Function>(GV)) {
  2083. return F->isDeclaration() &&
  2084. DeferredFunctionInfo.count(const_cast<Function*>(F));
  2085. }
  2086. return false;
  2087. }
  2088. bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
  2089. Function *F = dyn_cast<Function>(GV);
  2090. // If it's not a function or is already material, ignore the request.
  2091. if (!F || !F->isMaterializable()) return false;
  2092. DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
  2093. assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
  2094. // Move the bit stream to the saved position of the deferred function body.
  2095. Stream.JumpToBit(DFII->second);
  2096. if (ParseFunctionBody(F)) {
  2097. if (ErrInfo) *ErrInfo = ErrorString;
  2098. return true;
  2099. }
  2100. // Upgrade any old intrinsic calls in the function.
  2101. for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
  2102. E = UpgradedIntrinsics.end(); I != E; ++I) {
  2103. if (I->first != I->second) {
  2104. for (Value::use_iterator UI = I->first->use_begin(),
  2105. UE = I->first->use_end(); UI != UE; ) {
  2106. if (CallInst* CI = dyn_cast<CallInst>(*UI++))
  2107. UpgradeIntrinsicCall(CI, I->second);
  2108. }
  2109. }
  2110. }
  2111. return false;
  2112. }
  2113. bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
  2114. const Function *F = dyn_cast<Function>(GV);
  2115. if (!F || F->isDeclaration())
  2116. return false;
  2117. return DeferredFunctionInfo.count(const_cast<Function*>(F));
  2118. }
  2119. void BitcodeReader::Dematerialize(GlobalValue *GV) {
  2120. Function *F = dyn_cast<Function>(GV);
  2121. // If this function isn't dematerializable, this is a noop.
  2122. if (!F || !isDematerializable(F))
  2123. return;
  2124. assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
  2125. // Just forget the function body, we can remat it later.
  2126. F->deleteBody();
  2127. }
  2128. bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
  2129. assert(M == TheModule &&
  2130. "Can only Materialize the Module this BitcodeReader is attached to.");
  2131. // Iterate over the module, deserializing any functions that are still on
  2132. // disk.
  2133. for (Module::iterator F = TheModule->begin(), E = TheModule->end();
  2134. F != E; ++F)
  2135. if (F->isMaterializable() &&
  2136. Materialize(F, ErrInfo))
  2137. return true;
  2138. // Upgrade any intrinsic calls that slipped through (should not happen!) and
  2139. // delete the old functions to clean up. We can't do this unless the entire
  2140. // module is materialized because there could always be another function body
  2141. // with calls to the old function.
  2142. for (std::vector<std::pair<Function*, Function*> >::iterator I =
  2143. UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
  2144. if (I->first != I->second) {
  2145. for (Value::use_iterator UI = I->first->use_begin(),
  2146. UE = I->first->use_end(); UI != UE; ) {
  2147. if (CallInst* CI = dyn_cast<CallInst>(*UI++))
  2148. UpgradeIntrinsicCall(CI, I->second);
  2149. }
  2150. if (!I->first->use_empty())
  2151. I->first->replaceAllUsesWith(I->second);
  2152. I->first->eraseFromParent();
  2153. }
  2154. }
  2155. std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
  2156. // Check debug info intrinsics.
  2157. CheckDebugInfoIntrinsics(TheModule);
  2158. return false;
  2159. }
  2160. //===----------------------------------------------------------------------===//
  2161. // External interface
  2162. //===----------------------------------------------------------------------===//
  2163. /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
  2164. ///
  2165. Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
  2166. LLVMContext& Context,
  2167. std::string *ErrMsg) {
  2168. Module *M = new Module(Buffer->getBufferIdentifier(), Context);
  2169. BitcodeReader *R = new BitcodeReader(Buffer, Context);
  2170. M->setMaterializer(R);
  2171. if (R->ParseBitcodeInto(M)) {
  2172. if (ErrMsg)
  2173. *ErrMsg = R->getErrorString();
  2174. delete M; // Also deletes R.
  2175. return 0;
  2176. }
  2177. // Have the BitcodeReader dtor delete 'Buffer'.
  2178. R->setBufferOwned(true);
  2179. return M;
  2180. }
  2181. /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
  2182. /// If an error occurs, return null and fill in *ErrMsg if non-null.
  2183. Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
  2184. std::string *ErrMsg){
  2185. Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
  2186. if (!M) return 0;
  2187. // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
  2188. // there was an error.
  2189. static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
  2190. // Read in the entire module, and destroy the BitcodeReader.
  2191. if (M->MaterializeAllPermanently(ErrMsg)) {
  2192. delete M;
  2193. return NULL;
  2194. }
  2195. return M;
  2196. }