BitcodeReader.cpp 84 KB

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