BitcodeReader.cpp 89 KB

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