BitcodeReader.cpp 90 KB

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