BitcodeReader.cpp 85 KB

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