BitcodeReader.cpp 89 KB

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