BitcodeReader.cpp 87 KB

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