BitcodeReader.cpp 116 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394
  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. #include "llvm/Bitcode/ReaderWriter.h"
  10. #include "BitcodeReader.h"
  11. #include "llvm/ADT/SmallString.h"
  12. #include "llvm/ADT/SmallVector.h"
  13. #include "llvm/Bitcode/LLVMBitCodes.h"
  14. #include "llvm/IR/AutoUpgrade.h"
  15. #include "llvm/IR/Constants.h"
  16. #include "llvm/IR/DerivedTypes.h"
  17. #include "llvm/IR/InlineAsm.h"
  18. #include "llvm/IR/IntrinsicInst.h"
  19. #include "llvm/IR/LLVMContext.h"
  20. #include "llvm/IR/Module.h"
  21. #include "llvm/IR/OperandTraits.h"
  22. #include "llvm/IR/Operator.h"
  23. #include "llvm/Support/DataStream.h"
  24. #include "llvm/Support/MathExtras.h"
  25. #include "llvm/Support/MemoryBuffer.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. using namespace llvm;
  28. enum {
  29. SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
  30. };
  31. void BitcodeReader::materializeForwardReferencedFunctions() {
  32. while (!BlockAddrFwdRefs.empty()) {
  33. Function *F = BlockAddrFwdRefs.begin()->first;
  34. F->Materialize();
  35. }
  36. }
  37. void BitcodeReader::FreeState() {
  38. if (BufferOwned)
  39. delete Buffer;
  40. Buffer = 0;
  41. std::vector<Type*>().swap(TypeList);
  42. ValueList.clear();
  43. MDValueList.clear();
  44. std::vector<AttributeSet>().swap(MAttributes);
  45. std::vector<BasicBlock*>().swap(FunctionBBs);
  46. std::vector<Function*>().swap(FunctionsWithBodies);
  47. DeferredFunctionInfo.clear();
  48. MDKindMap.clear();
  49. assert(BlockAddrFwdRefs.empty() && "Unresolved blockaddress fwd references");
  50. }
  51. //===----------------------------------------------------------------------===//
  52. // Helper functions to implement forward reference resolution, etc.
  53. //===----------------------------------------------------------------------===//
  54. /// ConvertToString - Convert a string from a record into an std::string, return
  55. /// true on failure.
  56. template<typename StrTy>
  57. static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
  58. StrTy &Result) {
  59. if (Idx > Record.size())
  60. return true;
  61. for (unsigned i = Idx, e = Record.size(); i != e; ++i)
  62. Result += (char)Record[i];
  63. return false;
  64. }
  65. static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
  66. switch (Val) {
  67. default: // Map unknown/new linkages to external
  68. case 0: return GlobalValue::ExternalLinkage;
  69. case 1: return GlobalValue::WeakAnyLinkage;
  70. case 2: return GlobalValue::AppendingLinkage;
  71. case 3: return GlobalValue::InternalLinkage;
  72. case 4: return GlobalValue::LinkOnceAnyLinkage;
  73. case 5: return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
  74. case 6: return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
  75. case 7: return GlobalValue::ExternalWeakLinkage;
  76. case 8: return GlobalValue::CommonLinkage;
  77. case 9: return GlobalValue::PrivateLinkage;
  78. case 10: return GlobalValue::WeakODRLinkage;
  79. case 11: return GlobalValue::LinkOnceODRLinkage;
  80. case 12: return GlobalValue::AvailableExternallyLinkage;
  81. case 13:
  82. return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
  83. case 14:
  84. return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
  85. }
  86. }
  87. static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
  88. switch (Val) {
  89. default: // Map unknown visibilities to default.
  90. case 0: return GlobalValue::DefaultVisibility;
  91. case 1: return GlobalValue::HiddenVisibility;
  92. case 2: return GlobalValue::ProtectedVisibility;
  93. }
  94. }
  95. static GlobalValue::DLLStorageClassTypes
  96. GetDecodedDLLStorageClass(unsigned Val) {
  97. switch (Val) {
  98. default: // Map unknown values to default.
  99. case 0: return GlobalValue::DefaultStorageClass;
  100. case 1: return GlobalValue::DLLImportStorageClass;
  101. case 2: return GlobalValue::DLLExportStorageClass;
  102. }
  103. }
  104. static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
  105. switch (Val) {
  106. case 0: return GlobalVariable::NotThreadLocal;
  107. default: // Map unknown non-zero value to general dynamic.
  108. case 1: return GlobalVariable::GeneralDynamicTLSModel;
  109. case 2: return GlobalVariable::LocalDynamicTLSModel;
  110. case 3: return GlobalVariable::InitialExecTLSModel;
  111. case 4: return GlobalVariable::LocalExecTLSModel;
  112. }
  113. }
  114. static int GetDecodedCastOpcode(unsigned Val) {
  115. switch (Val) {
  116. default: return -1;
  117. case bitc::CAST_TRUNC : return Instruction::Trunc;
  118. case bitc::CAST_ZEXT : return Instruction::ZExt;
  119. case bitc::CAST_SEXT : return Instruction::SExt;
  120. case bitc::CAST_FPTOUI : return Instruction::FPToUI;
  121. case bitc::CAST_FPTOSI : return Instruction::FPToSI;
  122. case bitc::CAST_UITOFP : return Instruction::UIToFP;
  123. case bitc::CAST_SITOFP : return Instruction::SIToFP;
  124. case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
  125. case bitc::CAST_FPEXT : return Instruction::FPExt;
  126. case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
  127. case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
  128. case bitc::CAST_BITCAST : return Instruction::BitCast;
  129. case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
  130. }
  131. }
  132. static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
  133. switch (Val) {
  134. default: return -1;
  135. case bitc::BINOP_ADD:
  136. return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
  137. case bitc::BINOP_SUB:
  138. return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
  139. case bitc::BINOP_MUL:
  140. return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
  141. case bitc::BINOP_UDIV: return Instruction::UDiv;
  142. case bitc::BINOP_SDIV:
  143. return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
  144. case bitc::BINOP_UREM: return Instruction::URem;
  145. case bitc::BINOP_SREM:
  146. return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
  147. case bitc::BINOP_SHL: return Instruction::Shl;
  148. case bitc::BINOP_LSHR: return Instruction::LShr;
  149. case bitc::BINOP_ASHR: return Instruction::AShr;
  150. case bitc::BINOP_AND: return Instruction::And;
  151. case bitc::BINOP_OR: return Instruction::Or;
  152. case bitc::BINOP_XOR: return Instruction::Xor;
  153. }
  154. }
  155. static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
  156. switch (Val) {
  157. default: return AtomicRMWInst::BAD_BINOP;
  158. case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
  159. case bitc::RMW_ADD: return AtomicRMWInst::Add;
  160. case bitc::RMW_SUB: return AtomicRMWInst::Sub;
  161. case bitc::RMW_AND: return AtomicRMWInst::And;
  162. case bitc::RMW_NAND: return AtomicRMWInst::Nand;
  163. case bitc::RMW_OR: return AtomicRMWInst::Or;
  164. case bitc::RMW_XOR: return AtomicRMWInst::Xor;
  165. case bitc::RMW_MAX: return AtomicRMWInst::Max;
  166. case bitc::RMW_MIN: return AtomicRMWInst::Min;
  167. case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
  168. case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
  169. }
  170. }
  171. static AtomicOrdering GetDecodedOrdering(unsigned Val) {
  172. switch (Val) {
  173. case bitc::ORDERING_NOTATOMIC: return NotAtomic;
  174. case bitc::ORDERING_UNORDERED: return Unordered;
  175. case bitc::ORDERING_MONOTONIC: return Monotonic;
  176. case bitc::ORDERING_ACQUIRE: return Acquire;
  177. case bitc::ORDERING_RELEASE: return Release;
  178. case bitc::ORDERING_ACQREL: return AcquireRelease;
  179. default: // Map unknown orderings to sequentially-consistent.
  180. case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
  181. }
  182. }
  183. static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
  184. switch (Val) {
  185. case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
  186. default: // Map unknown scopes to cross-thread.
  187. case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
  188. }
  189. }
  190. static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
  191. switch (Val) {
  192. case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
  193. case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
  194. }
  195. }
  196. namespace llvm {
  197. namespace {
  198. /// @brief A class for maintaining the slot number definition
  199. /// as a placeholder for the actual definition for forward constants defs.
  200. class ConstantPlaceHolder : public ConstantExpr {
  201. void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
  202. public:
  203. // allocate space for exactly one operand
  204. void *operator new(size_t s) {
  205. return User::operator new(s, 1);
  206. }
  207. explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
  208. : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
  209. Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
  210. }
  211. /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
  212. static bool classof(const Value *V) {
  213. return isa<ConstantExpr>(V) &&
  214. cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
  215. }
  216. /// Provide fast operand accessors
  217. //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  218. };
  219. }
  220. // FIXME: can we inherit this from ConstantExpr?
  221. template <>
  222. struct OperandTraits<ConstantPlaceHolder> :
  223. public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
  224. };
  225. }
  226. void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
  227. if (Idx == size()) {
  228. push_back(V);
  229. return;
  230. }
  231. if (Idx >= size())
  232. resize(Idx+1);
  233. WeakVH &OldV = ValuePtrs[Idx];
  234. if (OldV == 0) {
  235. OldV = V;
  236. return;
  237. }
  238. // Handle constants and non-constants (e.g. instrs) differently for
  239. // efficiency.
  240. if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
  241. ResolveConstants.push_back(std::make_pair(PHC, Idx));
  242. OldV = V;
  243. } else {
  244. // If there was a forward reference to this value, replace it.
  245. Value *PrevVal = OldV;
  246. OldV->replaceAllUsesWith(V);
  247. delete PrevVal;
  248. }
  249. }
  250. Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
  251. Type *Ty) {
  252. if (Idx >= size())
  253. resize(Idx + 1);
  254. if (Value *V = ValuePtrs[Idx]) {
  255. assert(Ty == V->getType() && "Type mismatch in constant table!");
  256. return cast<Constant>(V);
  257. }
  258. // Create and return a placeholder, which will later be RAUW'd.
  259. Constant *C = new ConstantPlaceHolder(Ty, Context);
  260. ValuePtrs[Idx] = C;
  261. return C;
  262. }
  263. Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
  264. if (Idx >= size())
  265. resize(Idx + 1);
  266. if (Value *V = ValuePtrs[Idx]) {
  267. assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
  268. return V;
  269. }
  270. // No type specified, must be invalid reference.
  271. if (Ty == 0) return 0;
  272. // Create and return a placeholder, which will later be RAUW'd.
  273. Value *V = new Argument(Ty);
  274. ValuePtrs[Idx] = V;
  275. return V;
  276. }
  277. /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
  278. /// resolves any forward references. The idea behind this is that we sometimes
  279. /// get constants (such as large arrays) which reference *many* forward ref
  280. /// constants. Replacing each of these causes a lot of thrashing when
  281. /// building/reuniquing the constant. Instead of doing this, we look at all the
  282. /// uses and rewrite all the place holders at once for any constant that uses
  283. /// a placeholder.
  284. void BitcodeReaderValueList::ResolveConstantForwardRefs() {
  285. // Sort the values by-pointer so that they are efficient to look up with a
  286. // binary search.
  287. std::sort(ResolveConstants.begin(), ResolveConstants.end());
  288. SmallVector<Constant*, 64> NewOps;
  289. while (!ResolveConstants.empty()) {
  290. Value *RealVal = operator[](ResolveConstants.back().second);
  291. Constant *Placeholder = ResolveConstants.back().first;
  292. ResolveConstants.pop_back();
  293. // Loop over all users of the placeholder, updating them to reference the
  294. // new value. If they reference more than one placeholder, update them all
  295. // at once.
  296. while (!Placeholder->use_empty()) {
  297. auto UI = Placeholder->user_begin();
  298. User *U = *UI;
  299. // If the using object isn't uniqued, just update the operands. This
  300. // handles instructions and initializers for global variables.
  301. if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
  302. UI.getUse().set(RealVal);
  303. continue;
  304. }
  305. // Otherwise, we have a constant that uses the placeholder. Replace that
  306. // constant with a new constant that has *all* placeholder uses updated.
  307. Constant *UserC = cast<Constant>(U);
  308. for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
  309. I != E; ++I) {
  310. Value *NewOp;
  311. if (!isa<ConstantPlaceHolder>(*I)) {
  312. // Not a placeholder reference.
  313. NewOp = *I;
  314. } else if (*I == Placeholder) {
  315. // Common case is that it just references this one placeholder.
  316. NewOp = RealVal;
  317. } else {
  318. // Otherwise, look up the placeholder in ResolveConstants.
  319. ResolveConstantsTy::iterator It =
  320. std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
  321. std::pair<Constant*, unsigned>(cast<Constant>(*I),
  322. 0));
  323. assert(It != ResolveConstants.end() && It->first == *I);
  324. NewOp = operator[](It->second);
  325. }
  326. NewOps.push_back(cast<Constant>(NewOp));
  327. }
  328. // Make the new constant.
  329. Constant *NewC;
  330. if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
  331. NewC = ConstantArray::get(UserCA->getType(), NewOps);
  332. } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
  333. NewC = ConstantStruct::get(UserCS->getType(), NewOps);
  334. } else if (isa<ConstantVector>(UserC)) {
  335. NewC = ConstantVector::get(NewOps);
  336. } else {
  337. assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
  338. NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
  339. }
  340. UserC->replaceAllUsesWith(NewC);
  341. UserC->destroyConstant();
  342. NewOps.clear();
  343. }
  344. // Update all ValueHandles, they should be the only users at this point.
  345. Placeholder->replaceAllUsesWith(RealVal);
  346. delete Placeholder;
  347. }
  348. }
  349. void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
  350. if (Idx == size()) {
  351. push_back(V);
  352. return;
  353. }
  354. if (Idx >= size())
  355. resize(Idx+1);
  356. WeakVH &OldV = MDValuePtrs[Idx];
  357. if (OldV == 0) {
  358. OldV = V;
  359. return;
  360. }
  361. // If there was a forward reference to this value, replace it.
  362. MDNode *PrevVal = cast<MDNode>(OldV);
  363. OldV->replaceAllUsesWith(V);
  364. MDNode::deleteTemporary(PrevVal);
  365. // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
  366. // value for Idx.
  367. MDValuePtrs[Idx] = V;
  368. }
  369. Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
  370. if (Idx >= size())
  371. resize(Idx + 1);
  372. if (Value *V = MDValuePtrs[Idx]) {
  373. assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
  374. return V;
  375. }
  376. // Create and return a placeholder, which will later be RAUW'd.
  377. Value *V = MDNode::getTemporary(Context, None);
  378. MDValuePtrs[Idx] = V;
  379. return V;
  380. }
  381. Type *BitcodeReader::getTypeByID(unsigned ID) {
  382. // The type table size is always specified correctly.
  383. if (ID >= TypeList.size())
  384. return 0;
  385. if (Type *Ty = TypeList[ID])
  386. return Ty;
  387. // If we have a forward reference, the only possible case is when it is to a
  388. // named struct. Just create a placeholder for now.
  389. return TypeList[ID] = StructType::create(Context);
  390. }
  391. //===----------------------------------------------------------------------===//
  392. // Functions for parsing blocks from the bitcode file
  393. //===----------------------------------------------------------------------===//
  394. /// \brief This fills an AttrBuilder object with the LLVM attributes that have
  395. /// been decoded from the given integer. This function must stay in sync with
  396. /// 'encodeLLVMAttributesForBitcode'.
  397. static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
  398. uint64_t EncodedAttrs) {
  399. // FIXME: Remove in 4.0.
  400. // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
  401. // the bits above 31 down by 11 bits.
  402. unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
  403. assert((!Alignment || isPowerOf2_32(Alignment)) &&
  404. "Alignment must be a power of two.");
  405. if (Alignment)
  406. B.addAlignmentAttr(Alignment);
  407. B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
  408. (EncodedAttrs & 0xffff));
  409. }
  410. error_code BitcodeReader::ParseAttributeBlock() {
  411. if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
  412. return Error(InvalidRecord);
  413. if (!MAttributes.empty())
  414. return Error(InvalidMultipleBlocks);
  415. SmallVector<uint64_t, 64> Record;
  416. SmallVector<AttributeSet, 8> Attrs;
  417. // Read all the records.
  418. while (1) {
  419. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  420. switch (Entry.Kind) {
  421. case BitstreamEntry::SubBlock: // Handled for us already.
  422. case BitstreamEntry::Error:
  423. return Error(MalformedBlock);
  424. case BitstreamEntry::EndBlock:
  425. return error_code::success();
  426. case BitstreamEntry::Record:
  427. // The interesting case.
  428. break;
  429. }
  430. // Read a record.
  431. Record.clear();
  432. switch (Stream.readRecord(Entry.ID, Record)) {
  433. default: // Default behavior: ignore.
  434. break;
  435. case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
  436. // FIXME: Remove in 4.0.
  437. if (Record.size() & 1)
  438. return Error(InvalidRecord);
  439. for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
  440. AttrBuilder B;
  441. decodeLLVMAttributesForBitcode(B, Record[i+1]);
  442. Attrs.push_back(AttributeSet::get(Context, Record[i], B));
  443. }
  444. MAttributes.push_back(AttributeSet::get(Context, Attrs));
  445. Attrs.clear();
  446. break;
  447. }
  448. case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
  449. for (unsigned i = 0, e = Record.size(); i != e; ++i)
  450. Attrs.push_back(MAttributeGroups[Record[i]]);
  451. MAttributes.push_back(AttributeSet::get(Context, Attrs));
  452. Attrs.clear();
  453. break;
  454. }
  455. }
  456. }
  457. }
  458. // Returns Attribute::None on unrecognized codes.
  459. static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
  460. switch (Code) {
  461. default:
  462. return Attribute::None;
  463. case bitc::ATTR_KIND_ALIGNMENT:
  464. return Attribute::Alignment;
  465. case bitc::ATTR_KIND_ALWAYS_INLINE:
  466. return Attribute::AlwaysInline;
  467. case bitc::ATTR_KIND_BUILTIN:
  468. return Attribute::Builtin;
  469. case bitc::ATTR_KIND_BY_VAL:
  470. return Attribute::ByVal;
  471. case bitc::ATTR_KIND_IN_ALLOCA:
  472. return Attribute::InAlloca;
  473. case bitc::ATTR_KIND_COLD:
  474. return Attribute::Cold;
  475. case bitc::ATTR_KIND_INLINE_HINT:
  476. return Attribute::InlineHint;
  477. case bitc::ATTR_KIND_IN_REG:
  478. return Attribute::InReg;
  479. case bitc::ATTR_KIND_MIN_SIZE:
  480. return Attribute::MinSize;
  481. case bitc::ATTR_KIND_NAKED:
  482. return Attribute::Naked;
  483. case bitc::ATTR_KIND_NEST:
  484. return Attribute::Nest;
  485. case bitc::ATTR_KIND_NO_ALIAS:
  486. return Attribute::NoAlias;
  487. case bitc::ATTR_KIND_NO_BUILTIN:
  488. return Attribute::NoBuiltin;
  489. case bitc::ATTR_KIND_NO_CAPTURE:
  490. return Attribute::NoCapture;
  491. case bitc::ATTR_KIND_NO_DUPLICATE:
  492. return Attribute::NoDuplicate;
  493. case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
  494. return Attribute::NoImplicitFloat;
  495. case bitc::ATTR_KIND_NO_INLINE:
  496. return Attribute::NoInline;
  497. case bitc::ATTR_KIND_NON_LAZY_BIND:
  498. return Attribute::NonLazyBind;
  499. case bitc::ATTR_KIND_NO_RED_ZONE:
  500. return Attribute::NoRedZone;
  501. case bitc::ATTR_KIND_NO_RETURN:
  502. return Attribute::NoReturn;
  503. case bitc::ATTR_KIND_NO_UNWIND:
  504. return Attribute::NoUnwind;
  505. case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
  506. return Attribute::OptimizeForSize;
  507. case bitc::ATTR_KIND_OPTIMIZE_NONE:
  508. return Attribute::OptimizeNone;
  509. case bitc::ATTR_KIND_READ_NONE:
  510. return Attribute::ReadNone;
  511. case bitc::ATTR_KIND_READ_ONLY:
  512. return Attribute::ReadOnly;
  513. case bitc::ATTR_KIND_RETURNED:
  514. return Attribute::Returned;
  515. case bitc::ATTR_KIND_RETURNS_TWICE:
  516. return Attribute::ReturnsTwice;
  517. case bitc::ATTR_KIND_S_EXT:
  518. return Attribute::SExt;
  519. case bitc::ATTR_KIND_STACK_ALIGNMENT:
  520. return Attribute::StackAlignment;
  521. case bitc::ATTR_KIND_STACK_PROTECT:
  522. return Attribute::StackProtect;
  523. case bitc::ATTR_KIND_STACK_PROTECT_REQ:
  524. return Attribute::StackProtectReq;
  525. case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
  526. return Attribute::StackProtectStrong;
  527. case bitc::ATTR_KIND_STRUCT_RET:
  528. return Attribute::StructRet;
  529. case bitc::ATTR_KIND_SANITIZE_ADDRESS:
  530. return Attribute::SanitizeAddress;
  531. case bitc::ATTR_KIND_SANITIZE_THREAD:
  532. return Attribute::SanitizeThread;
  533. case bitc::ATTR_KIND_SANITIZE_MEMORY:
  534. return Attribute::SanitizeMemory;
  535. case bitc::ATTR_KIND_UW_TABLE:
  536. return Attribute::UWTable;
  537. case bitc::ATTR_KIND_Z_EXT:
  538. return Attribute::ZExt;
  539. }
  540. }
  541. error_code BitcodeReader::ParseAttrKind(uint64_t Code,
  542. Attribute::AttrKind *Kind) {
  543. *Kind = GetAttrFromCode(Code);
  544. if (*Kind == Attribute::None)
  545. return Error(InvalidValue);
  546. return error_code::success();
  547. }
  548. error_code BitcodeReader::ParseAttributeGroupBlock() {
  549. if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
  550. return Error(InvalidRecord);
  551. if (!MAttributeGroups.empty())
  552. return Error(InvalidMultipleBlocks);
  553. SmallVector<uint64_t, 64> Record;
  554. // Read all the records.
  555. while (1) {
  556. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  557. switch (Entry.Kind) {
  558. case BitstreamEntry::SubBlock: // Handled for us already.
  559. case BitstreamEntry::Error:
  560. return Error(MalformedBlock);
  561. case BitstreamEntry::EndBlock:
  562. return error_code::success();
  563. case BitstreamEntry::Record:
  564. // The interesting case.
  565. break;
  566. }
  567. // Read a record.
  568. Record.clear();
  569. switch (Stream.readRecord(Entry.ID, Record)) {
  570. default: // Default behavior: ignore.
  571. break;
  572. case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
  573. if (Record.size() < 3)
  574. return Error(InvalidRecord);
  575. uint64_t GrpID = Record[0];
  576. uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
  577. AttrBuilder B;
  578. for (unsigned i = 2, e = Record.size(); i != e; ++i) {
  579. if (Record[i] == 0) { // Enum attribute
  580. Attribute::AttrKind Kind;
  581. if (error_code EC = ParseAttrKind(Record[++i], &Kind))
  582. return EC;
  583. B.addAttribute(Kind);
  584. } else if (Record[i] == 1) { // Align attribute
  585. Attribute::AttrKind Kind;
  586. if (error_code EC = ParseAttrKind(Record[++i], &Kind))
  587. return EC;
  588. if (Kind == Attribute::Alignment)
  589. B.addAlignmentAttr(Record[++i]);
  590. else
  591. B.addStackAlignmentAttr(Record[++i]);
  592. } else { // String attribute
  593. assert((Record[i] == 3 || Record[i] == 4) &&
  594. "Invalid attribute group entry");
  595. bool HasValue = (Record[i++] == 4);
  596. SmallString<64> KindStr;
  597. SmallString<64> ValStr;
  598. while (Record[i] != 0 && i != e)
  599. KindStr += Record[i++];
  600. assert(Record[i] == 0 && "Kind string not null terminated");
  601. if (HasValue) {
  602. // Has a value associated with it.
  603. ++i; // Skip the '0' that terminates the "kind" string.
  604. while (Record[i] != 0 && i != e)
  605. ValStr += Record[i++];
  606. assert(Record[i] == 0 && "Value string not null terminated");
  607. }
  608. B.addAttribute(KindStr.str(), ValStr.str());
  609. }
  610. }
  611. MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
  612. break;
  613. }
  614. }
  615. }
  616. }
  617. error_code BitcodeReader::ParseTypeTable() {
  618. if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
  619. return Error(InvalidRecord);
  620. return ParseTypeTableBody();
  621. }
  622. error_code BitcodeReader::ParseTypeTableBody() {
  623. if (!TypeList.empty())
  624. return Error(InvalidMultipleBlocks);
  625. SmallVector<uint64_t, 64> Record;
  626. unsigned NumRecords = 0;
  627. SmallString<64> TypeName;
  628. // Read all the records for this type table.
  629. while (1) {
  630. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  631. switch (Entry.Kind) {
  632. case BitstreamEntry::SubBlock: // Handled for us already.
  633. case BitstreamEntry::Error:
  634. return Error(MalformedBlock);
  635. case BitstreamEntry::EndBlock:
  636. if (NumRecords != TypeList.size())
  637. return Error(MalformedBlock);
  638. return error_code::success();
  639. case BitstreamEntry::Record:
  640. // The interesting case.
  641. break;
  642. }
  643. // Read a record.
  644. Record.clear();
  645. Type *ResultTy = 0;
  646. switch (Stream.readRecord(Entry.ID, Record)) {
  647. default:
  648. return Error(InvalidValue);
  649. case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
  650. // TYPE_CODE_NUMENTRY contains a count of the number of types in the
  651. // type list. This allows us to reserve space.
  652. if (Record.size() < 1)
  653. return Error(InvalidRecord);
  654. TypeList.resize(Record[0]);
  655. continue;
  656. case bitc::TYPE_CODE_VOID: // VOID
  657. ResultTy = Type::getVoidTy(Context);
  658. break;
  659. case bitc::TYPE_CODE_HALF: // HALF
  660. ResultTy = Type::getHalfTy(Context);
  661. break;
  662. case bitc::TYPE_CODE_FLOAT: // FLOAT
  663. ResultTy = Type::getFloatTy(Context);
  664. break;
  665. case bitc::TYPE_CODE_DOUBLE: // DOUBLE
  666. ResultTy = Type::getDoubleTy(Context);
  667. break;
  668. case bitc::TYPE_CODE_X86_FP80: // X86_FP80
  669. ResultTy = Type::getX86_FP80Ty(Context);
  670. break;
  671. case bitc::TYPE_CODE_FP128: // FP128
  672. ResultTy = Type::getFP128Ty(Context);
  673. break;
  674. case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
  675. ResultTy = Type::getPPC_FP128Ty(Context);
  676. break;
  677. case bitc::TYPE_CODE_LABEL: // LABEL
  678. ResultTy = Type::getLabelTy(Context);
  679. break;
  680. case bitc::TYPE_CODE_METADATA: // METADATA
  681. ResultTy = Type::getMetadataTy(Context);
  682. break;
  683. case bitc::TYPE_CODE_X86_MMX: // X86_MMX
  684. ResultTy = Type::getX86_MMXTy(Context);
  685. break;
  686. case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
  687. if (Record.size() < 1)
  688. return Error(InvalidRecord);
  689. ResultTy = IntegerType::get(Context, Record[0]);
  690. break;
  691. case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
  692. // [pointee type, address space]
  693. if (Record.size() < 1)
  694. return Error(InvalidRecord);
  695. unsigned AddressSpace = 0;
  696. if (Record.size() == 2)
  697. AddressSpace = Record[1];
  698. ResultTy = getTypeByID(Record[0]);
  699. if (ResultTy == 0)
  700. return Error(InvalidType);
  701. ResultTy = PointerType::get(ResultTy, AddressSpace);
  702. break;
  703. }
  704. case bitc::TYPE_CODE_FUNCTION_OLD: {
  705. // FIXME: attrid is dead, remove it in LLVM 4.0
  706. // FUNCTION: [vararg, attrid, retty, paramty x N]
  707. if (Record.size() < 3)
  708. return Error(InvalidRecord);
  709. SmallVector<Type*, 8> ArgTys;
  710. for (unsigned i = 3, e = Record.size(); i != e; ++i) {
  711. if (Type *T = getTypeByID(Record[i]))
  712. ArgTys.push_back(T);
  713. else
  714. break;
  715. }
  716. ResultTy = getTypeByID(Record[2]);
  717. if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
  718. return Error(InvalidType);
  719. ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
  720. break;
  721. }
  722. case bitc::TYPE_CODE_FUNCTION: {
  723. // FUNCTION: [vararg, retty, paramty x N]
  724. if (Record.size() < 2)
  725. return Error(InvalidRecord);
  726. SmallVector<Type*, 8> ArgTys;
  727. for (unsigned i = 2, e = Record.size(); i != e; ++i) {
  728. if (Type *T = getTypeByID(Record[i]))
  729. ArgTys.push_back(T);
  730. else
  731. break;
  732. }
  733. ResultTy = getTypeByID(Record[1]);
  734. if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
  735. return Error(InvalidType);
  736. ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
  737. break;
  738. }
  739. case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
  740. if (Record.size() < 1)
  741. return Error(InvalidRecord);
  742. SmallVector<Type*, 8> EltTys;
  743. for (unsigned i = 1, e = Record.size(); i != e; ++i) {
  744. if (Type *T = getTypeByID(Record[i]))
  745. EltTys.push_back(T);
  746. else
  747. break;
  748. }
  749. if (EltTys.size() != Record.size()-1)
  750. return Error(InvalidType);
  751. ResultTy = StructType::get(Context, EltTys, Record[0]);
  752. break;
  753. }
  754. case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
  755. if (ConvertToString(Record, 0, TypeName))
  756. return Error(InvalidRecord);
  757. continue;
  758. case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
  759. if (Record.size() < 1)
  760. return Error(InvalidRecord);
  761. if (NumRecords >= TypeList.size())
  762. return Error(InvalidTYPETable);
  763. // Check to see if this was forward referenced, if so fill in the temp.
  764. StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
  765. if (Res) {
  766. Res->setName(TypeName);
  767. TypeList[NumRecords] = 0;
  768. } else // Otherwise, create a new struct.
  769. Res = StructType::create(Context, TypeName);
  770. TypeName.clear();
  771. SmallVector<Type*, 8> EltTys;
  772. for (unsigned i = 1, e = Record.size(); i != e; ++i) {
  773. if (Type *T = getTypeByID(Record[i]))
  774. EltTys.push_back(T);
  775. else
  776. break;
  777. }
  778. if (EltTys.size() != Record.size()-1)
  779. return Error(InvalidRecord);
  780. Res->setBody(EltTys, Record[0]);
  781. ResultTy = Res;
  782. break;
  783. }
  784. case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
  785. if (Record.size() != 1)
  786. return Error(InvalidRecord);
  787. if (NumRecords >= TypeList.size())
  788. return Error(InvalidTYPETable);
  789. // Check to see if this was forward referenced, if so fill in the temp.
  790. StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
  791. if (Res) {
  792. Res->setName(TypeName);
  793. TypeList[NumRecords] = 0;
  794. } else // Otherwise, create a new struct with no body.
  795. Res = StructType::create(Context, TypeName);
  796. TypeName.clear();
  797. ResultTy = Res;
  798. break;
  799. }
  800. case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
  801. if (Record.size() < 2)
  802. return Error(InvalidRecord);
  803. if ((ResultTy = getTypeByID(Record[1])))
  804. ResultTy = ArrayType::get(ResultTy, Record[0]);
  805. else
  806. return Error(InvalidType);
  807. break;
  808. case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
  809. if (Record.size() < 2)
  810. return Error(InvalidRecord);
  811. if ((ResultTy = getTypeByID(Record[1])))
  812. ResultTy = VectorType::get(ResultTy, Record[0]);
  813. else
  814. return Error(InvalidType);
  815. break;
  816. }
  817. if (NumRecords >= TypeList.size())
  818. return Error(InvalidTYPETable);
  819. assert(ResultTy && "Didn't read a type?");
  820. assert(TypeList[NumRecords] == 0 && "Already read type?");
  821. TypeList[NumRecords++] = ResultTy;
  822. }
  823. }
  824. error_code BitcodeReader::ParseValueSymbolTable() {
  825. if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
  826. return Error(InvalidRecord);
  827. SmallVector<uint64_t, 64> Record;
  828. // Read all the records for this value table.
  829. SmallString<128> ValueName;
  830. while (1) {
  831. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  832. switch (Entry.Kind) {
  833. case BitstreamEntry::SubBlock: // Handled for us already.
  834. case BitstreamEntry::Error:
  835. return Error(MalformedBlock);
  836. case BitstreamEntry::EndBlock:
  837. return error_code::success();
  838. case BitstreamEntry::Record:
  839. // The interesting case.
  840. break;
  841. }
  842. // Read a record.
  843. Record.clear();
  844. switch (Stream.readRecord(Entry.ID, Record)) {
  845. default: // Default behavior: unknown type.
  846. break;
  847. case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
  848. if (ConvertToString(Record, 1, ValueName))
  849. return Error(InvalidRecord);
  850. unsigned ValueID = Record[0];
  851. if (ValueID >= ValueList.size())
  852. return Error(InvalidRecord);
  853. Value *V = ValueList[ValueID];
  854. V->setName(StringRef(ValueName.data(), ValueName.size()));
  855. ValueName.clear();
  856. break;
  857. }
  858. case bitc::VST_CODE_BBENTRY: {
  859. if (ConvertToString(Record, 1, ValueName))
  860. return Error(InvalidRecord);
  861. BasicBlock *BB = getBasicBlock(Record[0]);
  862. if (BB == 0)
  863. return Error(InvalidRecord);
  864. BB->setName(StringRef(ValueName.data(), ValueName.size()));
  865. ValueName.clear();
  866. break;
  867. }
  868. }
  869. }
  870. }
  871. error_code BitcodeReader::ParseMetadata() {
  872. unsigned NextMDValueNo = MDValueList.size();
  873. if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
  874. return Error(InvalidRecord);
  875. SmallVector<uint64_t, 64> Record;
  876. // Read all the records.
  877. while (1) {
  878. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  879. switch (Entry.Kind) {
  880. case BitstreamEntry::SubBlock: // Handled for us already.
  881. case BitstreamEntry::Error:
  882. return Error(MalformedBlock);
  883. case BitstreamEntry::EndBlock:
  884. return error_code::success();
  885. case BitstreamEntry::Record:
  886. // The interesting case.
  887. break;
  888. }
  889. bool IsFunctionLocal = false;
  890. // Read a record.
  891. Record.clear();
  892. unsigned Code = Stream.readRecord(Entry.ID, Record);
  893. switch (Code) {
  894. default: // Default behavior: ignore.
  895. break;
  896. case bitc::METADATA_NAME: {
  897. // Read name of the named metadata.
  898. SmallString<8> Name(Record.begin(), Record.end());
  899. Record.clear();
  900. Code = Stream.ReadCode();
  901. // METADATA_NAME is always followed by METADATA_NAMED_NODE.
  902. unsigned NextBitCode = Stream.readRecord(Code, Record);
  903. assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
  904. // Read named metadata elements.
  905. unsigned Size = Record.size();
  906. NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
  907. for (unsigned i = 0; i != Size; ++i) {
  908. MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
  909. if (MD == 0)
  910. return Error(InvalidRecord);
  911. NMD->addOperand(MD);
  912. }
  913. break;
  914. }
  915. case bitc::METADATA_FN_NODE:
  916. IsFunctionLocal = true;
  917. // fall-through
  918. case bitc::METADATA_NODE: {
  919. if (Record.size() % 2 == 1)
  920. return Error(InvalidRecord);
  921. unsigned Size = Record.size();
  922. SmallVector<Value*, 8> Elts;
  923. for (unsigned i = 0; i != Size; i += 2) {
  924. Type *Ty = getTypeByID(Record[i]);
  925. if (!Ty)
  926. return Error(InvalidRecord);
  927. if (Ty->isMetadataTy())
  928. Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
  929. else if (!Ty->isVoidTy())
  930. Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
  931. else
  932. Elts.push_back(NULL);
  933. }
  934. Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
  935. IsFunctionLocal = false;
  936. MDValueList.AssignValue(V, NextMDValueNo++);
  937. break;
  938. }
  939. case bitc::METADATA_STRING: {
  940. SmallString<8> String(Record.begin(), Record.end());
  941. Value *V = MDString::get(Context, String);
  942. MDValueList.AssignValue(V, NextMDValueNo++);
  943. break;
  944. }
  945. case bitc::METADATA_KIND: {
  946. if (Record.size() < 2)
  947. return Error(InvalidRecord);
  948. unsigned Kind = Record[0];
  949. SmallString<8> Name(Record.begin()+1, Record.end());
  950. unsigned NewKind = TheModule->getMDKindID(Name.str());
  951. if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
  952. return Error(ConflictingMETADATA_KINDRecords);
  953. break;
  954. }
  955. }
  956. }
  957. }
  958. /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
  959. /// the LSB for dense VBR encoding.
  960. uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
  961. if ((V & 1) == 0)
  962. return V >> 1;
  963. if (V != 1)
  964. return -(V >> 1);
  965. // There is no such thing as -0 with integers. "-0" really means MININT.
  966. return 1ULL << 63;
  967. }
  968. /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
  969. /// values and aliases that we can.
  970. error_code BitcodeReader::ResolveGlobalAndAliasInits() {
  971. std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
  972. std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
  973. std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
  974. GlobalInitWorklist.swap(GlobalInits);
  975. AliasInitWorklist.swap(AliasInits);
  976. FunctionPrefixWorklist.swap(FunctionPrefixes);
  977. while (!GlobalInitWorklist.empty()) {
  978. unsigned ValID = GlobalInitWorklist.back().second;
  979. if (ValID >= ValueList.size()) {
  980. // Not ready to resolve this yet, it requires something later in the file.
  981. GlobalInits.push_back(GlobalInitWorklist.back());
  982. } else {
  983. if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
  984. GlobalInitWorklist.back().first->setInitializer(C);
  985. else
  986. return Error(ExpectedConstant);
  987. }
  988. GlobalInitWorklist.pop_back();
  989. }
  990. while (!AliasInitWorklist.empty()) {
  991. unsigned ValID = AliasInitWorklist.back().second;
  992. if (ValID >= ValueList.size()) {
  993. AliasInits.push_back(AliasInitWorklist.back());
  994. } else {
  995. if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
  996. AliasInitWorklist.back().first->setAliasee(C);
  997. else
  998. return Error(ExpectedConstant);
  999. }
  1000. AliasInitWorklist.pop_back();
  1001. }
  1002. while (!FunctionPrefixWorklist.empty()) {
  1003. unsigned ValID = FunctionPrefixWorklist.back().second;
  1004. if (ValID >= ValueList.size()) {
  1005. FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
  1006. } else {
  1007. if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
  1008. FunctionPrefixWorklist.back().first->setPrefixData(C);
  1009. else
  1010. return Error(ExpectedConstant);
  1011. }
  1012. FunctionPrefixWorklist.pop_back();
  1013. }
  1014. return error_code::success();
  1015. }
  1016. static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
  1017. SmallVector<uint64_t, 8> Words(Vals.size());
  1018. std::transform(Vals.begin(), Vals.end(), Words.begin(),
  1019. BitcodeReader::decodeSignRotatedValue);
  1020. return APInt(TypeBits, Words);
  1021. }
  1022. error_code BitcodeReader::ParseConstants() {
  1023. if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
  1024. return Error(InvalidRecord);
  1025. SmallVector<uint64_t, 64> Record;
  1026. // Read all the records for this value table.
  1027. Type *CurTy = Type::getInt32Ty(Context);
  1028. unsigned NextCstNo = ValueList.size();
  1029. while (1) {
  1030. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  1031. switch (Entry.Kind) {
  1032. case BitstreamEntry::SubBlock: // Handled for us already.
  1033. case BitstreamEntry::Error:
  1034. return Error(MalformedBlock);
  1035. case BitstreamEntry::EndBlock:
  1036. if (NextCstNo != ValueList.size())
  1037. return Error(InvalidConstantReference);
  1038. // Once all the constants have been read, go through and resolve forward
  1039. // references.
  1040. ValueList.ResolveConstantForwardRefs();
  1041. return error_code::success();
  1042. case BitstreamEntry::Record:
  1043. // The interesting case.
  1044. break;
  1045. }
  1046. // Read a record.
  1047. Record.clear();
  1048. Value *V = 0;
  1049. unsigned BitCode = Stream.readRecord(Entry.ID, Record);
  1050. switch (BitCode) {
  1051. default: // Default behavior: unknown constant
  1052. case bitc::CST_CODE_UNDEF: // UNDEF
  1053. V = UndefValue::get(CurTy);
  1054. break;
  1055. case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
  1056. if (Record.empty())
  1057. return Error(InvalidRecord);
  1058. if (Record[0] >= TypeList.size())
  1059. return Error(InvalidRecord);
  1060. CurTy = TypeList[Record[0]];
  1061. continue; // Skip the ValueList manipulation.
  1062. case bitc::CST_CODE_NULL: // NULL
  1063. V = Constant::getNullValue(CurTy);
  1064. break;
  1065. case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
  1066. if (!CurTy->isIntegerTy() || Record.empty())
  1067. return Error(InvalidRecord);
  1068. V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
  1069. break;
  1070. case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
  1071. if (!CurTy->isIntegerTy() || Record.empty())
  1072. return Error(InvalidRecord);
  1073. APInt VInt = ReadWideAPInt(Record,
  1074. cast<IntegerType>(CurTy)->getBitWidth());
  1075. V = ConstantInt::get(Context, VInt);
  1076. break;
  1077. }
  1078. case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
  1079. if (Record.empty())
  1080. return Error(InvalidRecord);
  1081. if (CurTy->isHalfTy())
  1082. V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
  1083. APInt(16, (uint16_t)Record[0])));
  1084. else if (CurTy->isFloatTy())
  1085. V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
  1086. APInt(32, (uint32_t)Record[0])));
  1087. else if (CurTy->isDoubleTy())
  1088. V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
  1089. APInt(64, Record[0])));
  1090. else if (CurTy->isX86_FP80Ty()) {
  1091. // Bits are not stored the same way as a normal i80 APInt, compensate.
  1092. uint64_t Rearrange[2];
  1093. Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
  1094. Rearrange[1] = Record[0] >> 48;
  1095. V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
  1096. APInt(80, Rearrange)));
  1097. } else if (CurTy->isFP128Ty())
  1098. V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
  1099. APInt(128, Record)));
  1100. else if (CurTy->isPPC_FP128Ty())
  1101. V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
  1102. APInt(128, Record)));
  1103. else
  1104. V = UndefValue::get(CurTy);
  1105. break;
  1106. }
  1107. case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
  1108. if (Record.empty())
  1109. return Error(InvalidRecord);
  1110. unsigned Size = Record.size();
  1111. SmallVector<Constant*, 16> Elts;
  1112. if (StructType *STy = dyn_cast<StructType>(CurTy)) {
  1113. for (unsigned i = 0; i != Size; ++i)
  1114. Elts.push_back(ValueList.getConstantFwdRef(Record[i],
  1115. STy->getElementType(i)));
  1116. V = ConstantStruct::get(STy, Elts);
  1117. } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
  1118. Type *EltTy = ATy->getElementType();
  1119. for (unsigned i = 0; i != Size; ++i)
  1120. Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
  1121. V = ConstantArray::get(ATy, Elts);
  1122. } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
  1123. Type *EltTy = VTy->getElementType();
  1124. for (unsigned i = 0; i != Size; ++i)
  1125. Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
  1126. V = ConstantVector::get(Elts);
  1127. } else {
  1128. V = UndefValue::get(CurTy);
  1129. }
  1130. break;
  1131. }
  1132. case bitc::CST_CODE_STRING: // STRING: [values]
  1133. case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
  1134. if (Record.empty())
  1135. return Error(InvalidRecord);
  1136. SmallString<16> Elts(Record.begin(), Record.end());
  1137. V = ConstantDataArray::getString(Context, Elts,
  1138. BitCode == bitc::CST_CODE_CSTRING);
  1139. break;
  1140. }
  1141. case bitc::CST_CODE_DATA: {// DATA: [n x value]
  1142. if (Record.empty())
  1143. return Error(InvalidRecord);
  1144. Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
  1145. unsigned Size = Record.size();
  1146. if (EltTy->isIntegerTy(8)) {
  1147. SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
  1148. if (isa<VectorType>(CurTy))
  1149. V = ConstantDataVector::get(Context, Elts);
  1150. else
  1151. V = ConstantDataArray::get(Context, Elts);
  1152. } else if (EltTy->isIntegerTy(16)) {
  1153. SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
  1154. if (isa<VectorType>(CurTy))
  1155. V = ConstantDataVector::get(Context, Elts);
  1156. else
  1157. V = ConstantDataArray::get(Context, Elts);
  1158. } else if (EltTy->isIntegerTy(32)) {
  1159. SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
  1160. if (isa<VectorType>(CurTy))
  1161. V = ConstantDataVector::get(Context, Elts);
  1162. else
  1163. V = ConstantDataArray::get(Context, Elts);
  1164. } else if (EltTy->isIntegerTy(64)) {
  1165. SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
  1166. if (isa<VectorType>(CurTy))
  1167. V = ConstantDataVector::get(Context, Elts);
  1168. else
  1169. V = ConstantDataArray::get(Context, Elts);
  1170. } else if (EltTy->isFloatTy()) {
  1171. SmallVector<float, 16> Elts(Size);
  1172. std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
  1173. if (isa<VectorType>(CurTy))
  1174. V = ConstantDataVector::get(Context, Elts);
  1175. else
  1176. V = ConstantDataArray::get(Context, Elts);
  1177. } else if (EltTy->isDoubleTy()) {
  1178. SmallVector<double, 16> Elts(Size);
  1179. std::transform(Record.begin(), Record.end(), Elts.begin(),
  1180. BitsToDouble);
  1181. if (isa<VectorType>(CurTy))
  1182. V = ConstantDataVector::get(Context, Elts);
  1183. else
  1184. V = ConstantDataArray::get(Context, Elts);
  1185. } else {
  1186. return Error(InvalidTypeForValue);
  1187. }
  1188. break;
  1189. }
  1190. case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
  1191. if (Record.size() < 3)
  1192. return Error(InvalidRecord);
  1193. int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
  1194. if (Opc < 0) {
  1195. V = UndefValue::get(CurTy); // Unknown binop.
  1196. } else {
  1197. Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
  1198. Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
  1199. unsigned Flags = 0;
  1200. if (Record.size() >= 4) {
  1201. if (Opc == Instruction::Add ||
  1202. Opc == Instruction::Sub ||
  1203. Opc == Instruction::Mul ||
  1204. Opc == Instruction::Shl) {
  1205. if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
  1206. Flags |= OverflowingBinaryOperator::NoSignedWrap;
  1207. if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
  1208. Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
  1209. } else if (Opc == Instruction::SDiv ||
  1210. Opc == Instruction::UDiv ||
  1211. Opc == Instruction::LShr ||
  1212. Opc == Instruction::AShr) {
  1213. if (Record[3] & (1 << bitc::PEO_EXACT))
  1214. Flags |= SDivOperator::IsExact;
  1215. }
  1216. }
  1217. V = ConstantExpr::get(Opc, LHS, RHS, Flags);
  1218. }
  1219. break;
  1220. }
  1221. case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
  1222. if (Record.size() < 3)
  1223. return Error(InvalidRecord);
  1224. int Opc = GetDecodedCastOpcode(Record[0]);
  1225. if (Opc < 0) {
  1226. V = UndefValue::get(CurTy); // Unknown cast.
  1227. } else {
  1228. Type *OpTy = getTypeByID(Record[1]);
  1229. if (!OpTy)
  1230. return Error(InvalidRecord);
  1231. Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
  1232. V = UpgradeBitCastExpr(Opc, Op, CurTy);
  1233. if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
  1234. }
  1235. break;
  1236. }
  1237. case bitc::CST_CODE_CE_INBOUNDS_GEP:
  1238. case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
  1239. if (Record.size() & 1)
  1240. return Error(InvalidRecord);
  1241. SmallVector<Constant*, 16> Elts;
  1242. for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
  1243. Type *ElTy = getTypeByID(Record[i]);
  1244. if (!ElTy)
  1245. return Error(InvalidRecord);
  1246. Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
  1247. }
  1248. ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
  1249. V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
  1250. BitCode ==
  1251. bitc::CST_CODE_CE_INBOUNDS_GEP);
  1252. break;
  1253. }
  1254. case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
  1255. if (Record.size() < 3)
  1256. return Error(InvalidRecord);
  1257. Type *SelectorTy = Type::getInt1Ty(Context);
  1258. // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
  1259. // vector. Otherwise, it must be a single bit.
  1260. if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
  1261. SelectorTy = VectorType::get(Type::getInt1Ty(Context),
  1262. VTy->getNumElements());
  1263. V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
  1264. SelectorTy),
  1265. ValueList.getConstantFwdRef(Record[1],CurTy),
  1266. ValueList.getConstantFwdRef(Record[2],CurTy));
  1267. break;
  1268. }
  1269. case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
  1270. if (Record.size() < 3)
  1271. return Error(InvalidRecord);
  1272. VectorType *OpTy =
  1273. dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
  1274. if (OpTy == 0)
  1275. return Error(InvalidRecord);
  1276. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  1277. Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
  1278. Type::getInt32Ty(Context));
  1279. V = ConstantExpr::getExtractElement(Op0, Op1);
  1280. break;
  1281. }
  1282. case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
  1283. VectorType *OpTy = dyn_cast<VectorType>(CurTy);
  1284. if (Record.size() < 3 || OpTy == 0)
  1285. return Error(InvalidRecord);
  1286. Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
  1287. Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
  1288. OpTy->getElementType());
  1289. Constant *Op2 = ValueList.getConstantFwdRef(Record[2],
  1290. Type::getInt32Ty(Context));
  1291. V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
  1292. break;
  1293. }
  1294. case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
  1295. VectorType *OpTy = dyn_cast<VectorType>(CurTy);
  1296. if (Record.size() < 3 || OpTy == 0)
  1297. return Error(InvalidRecord);
  1298. Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
  1299. Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
  1300. Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
  1301. OpTy->getNumElements());
  1302. Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
  1303. V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
  1304. break;
  1305. }
  1306. case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
  1307. VectorType *RTy = dyn_cast<VectorType>(CurTy);
  1308. VectorType *OpTy =
  1309. dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
  1310. if (Record.size() < 4 || RTy == 0 || OpTy == 0)
  1311. return Error(InvalidRecord);
  1312. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  1313. Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
  1314. Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
  1315. RTy->getNumElements());
  1316. Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
  1317. V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
  1318. break;
  1319. }
  1320. case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
  1321. if (Record.size() < 4)
  1322. return Error(InvalidRecord);
  1323. Type *OpTy = getTypeByID(Record[0]);
  1324. if (OpTy == 0)
  1325. return Error(InvalidRecord);
  1326. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  1327. Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
  1328. if (OpTy->isFPOrFPVectorTy())
  1329. V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
  1330. else
  1331. V = ConstantExpr::getICmp(Record[3], Op0, Op1);
  1332. break;
  1333. }
  1334. // This maintains backward compatibility, pre-asm dialect keywords.
  1335. // FIXME: Remove with the 4.0 release.
  1336. case bitc::CST_CODE_INLINEASM_OLD: {
  1337. if (Record.size() < 2)
  1338. return Error(InvalidRecord);
  1339. std::string AsmStr, ConstrStr;
  1340. bool HasSideEffects = Record[0] & 1;
  1341. bool IsAlignStack = Record[0] >> 1;
  1342. unsigned AsmStrSize = Record[1];
  1343. if (2+AsmStrSize >= Record.size())
  1344. return Error(InvalidRecord);
  1345. unsigned ConstStrSize = Record[2+AsmStrSize];
  1346. if (3+AsmStrSize+ConstStrSize > Record.size())
  1347. return Error(InvalidRecord);
  1348. for (unsigned i = 0; i != AsmStrSize; ++i)
  1349. AsmStr += (char)Record[2+i];
  1350. for (unsigned i = 0; i != ConstStrSize; ++i)
  1351. ConstrStr += (char)Record[3+AsmStrSize+i];
  1352. PointerType *PTy = cast<PointerType>(CurTy);
  1353. V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
  1354. AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
  1355. break;
  1356. }
  1357. // This version adds support for the asm dialect keywords (e.g.,
  1358. // inteldialect).
  1359. case bitc::CST_CODE_INLINEASM: {
  1360. if (Record.size() < 2)
  1361. return Error(InvalidRecord);
  1362. std::string AsmStr, ConstrStr;
  1363. bool HasSideEffects = Record[0] & 1;
  1364. bool IsAlignStack = (Record[0] >> 1) & 1;
  1365. unsigned AsmDialect = Record[0] >> 2;
  1366. unsigned AsmStrSize = Record[1];
  1367. if (2+AsmStrSize >= Record.size())
  1368. return Error(InvalidRecord);
  1369. unsigned ConstStrSize = Record[2+AsmStrSize];
  1370. if (3+AsmStrSize+ConstStrSize > Record.size())
  1371. return Error(InvalidRecord);
  1372. for (unsigned i = 0; i != AsmStrSize; ++i)
  1373. AsmStr += (char)Record[2+i];
  1374. for (unsigned i = 0; i != ConstStrSize; ++i)
  1375. ConstrStr += (char)Record[3+AsmStrSize+i];
  1376. PointerType *PTy = cast<PointerType>(CurTy);
  1377. V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
  1378. AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
  1379. InlineAsm::AsmDialect(AsmDialect));
  1380. break;
  1381. }
  1382. case bitc::CST_CODE_BLOCKADDRESS:{
  1383. if (Record.size() < 3)
  1384. return Error(InvalidRecord);
  1385. Type *FnTy = getTypeByID(Record[0]);
  1386. if (FnTy == 0)
  1387. return Error(InvalidRecord);
  1388. Function *Fn =
  1389. dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
  1390. if (Fn == 0)
  1391. return Error(InvalidRecord);
  1392. // If the function is already parsed we can insert the block address right
  1393. // away.
  1394. if (!Fn->empty()) {
  1395. Function::iterator BBI = Fn->begin(), BBE = Fn->end();
  1396. for (size_t I = 0, E = Record[2]; I != E; ++I) {
  1397. if (BBI == BBE)
  1398. return Error(InvalidID);
  1399. ++BBI;
  1400. }
  1401. V = BlockAddress::get(Fn, BBI);
  1402. } else {
  1403. // Otherwise insert a placeholder and remember it so it can be inserted
  1404. // when the function is parsed.
  1405. GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
  1406. Type::getInt8Ty(Context),
  1407. false, GlobalValue::InternalLinkage,
  1408. 0, "");
  1409. BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
  1410. V = FwdRef;
  1411. }
  1412. break;
  1413. }
  1414. }
  1415. ValueList.AssignValue(V, NextCstNo);
  1416. ++NextCstNo;
  1417. }
  1418. }
  1419. error_code BitcodeReader::ParseUseLists() {
  1420. if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
  1421. return Error(InvalidRecord);
  1422. SmallVector<uint64_t, 64> Record;
  1423. // Read all the records.
  1424. while (1) {
  1425. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  1426. switch (Entry.Kind) {
  1427. case BitstreamEntry::SubBlock: // Handled for us already.
  1428. case BitstreamEntry::Error:
  1429. return Error(MalformedBlock);
  1430. case BitstreamEntry::EndBlock:
  1431. return error_code::success();
  1432. case BitstreamEntry::Record:
  1433. // The interesting case.
  1434. break;
  1435. }
  1436. // Read a use list record.
  1437. Record.clear();
  1438. switch (Stream.readRecord(Entry.ID, Record)) {
  1439. default: // Default behavior: unknown type.
  1440. break;
  1441. case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
  1442. unsigned RecordLength = Record.size();
  1443. if (RecordLength < 1)
  1444. return Error(InvalidRecord);
  1445. UseListRecords.push_back(Record);
  1446. break;
  1447. }
  1448. }
  1449. }
  1450. }
  1451. /// RememberAndSkipFunctionBody - When we see the block for a function body,
  1452. /// remember where it is and then skip it. This lets us lazily deserialize the
  1453. /// functions.
  1454. error_code BitcodeReader::RememberAndSkipFunctionBody() {
  1455. // Get the function we are talking about.
  1456. if (FunctionsWithBodies.empty())
  1457. return Error(InsufficientFunctionProtos);
  1458. Function *Fn = FunctionsWithBodies.back();
  1459. FunctionsWithBodies.pop_back();
  1460. // Save the current stream state.
  1461. uint64_t CurBit = Stream.GetCurrentBitNo();
  1462. DeferredFunctionInfo[Fn] = CurBit;
  1463. // Skip over the function block for now.
  1464. if (Stream.SkipBlock())
  1465. return Error(InvalidRecord);
  1466. return error_code::success();
  1467. }
  1468. error_code BitcodeReader::GlobalCleanup() {
  1469. // Patch the initializers for globals and aliases up.
  1470. ResolveGlobalAndAliasInits();
  1471. if (!GlobalInits.empty() || !AliasInits.empty())
  1472. return Error(MalformedGlobalInitializerSet);
  1473. // Look for intrinsic functions which need to be upgraded at some point
  1474. for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
  1475. FI != FE; ++FI) {
  1476. Function *NewFn;
  1477. if (UpgradeIntrinsicFunction(FI, NewFn))
  1478. UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
  1479. }
  1480. // Look for global variables which need to be renamed.
  1481. for (Module::global_iterator
  1482. GI = TheModule->global_begin(), GE = TheModule->global_end();
  1483. GI != GE; ++GI)
  1484. UpgradeGlobalVariable(GI);
  1485. // Force deallocation of memory for these vectors to favor the client that
  1486. // want lazy deserialization.
  1487. std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
  1488. std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
  1489. return error_code::success();
  1490. }
  1491. error_code BitcodeReader::ParseModule(bool Resume) {
  1492. if (Resume)
  1493. Stream.JumpToBit(NextUnreadBit);
  1494. else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
  1495. return Error(InvalidRecord);
  1496. SmallVector<uint64_t, 64> Record;
  1497. std::vector<std::string> SectionTable;
  1498. std::vector<std::string> GCTable;
  1499. // Read all the records for this module.
  1500. while (1) {
  1501. BitstreamEntry Entry = Stream.advance();
  1502. switch (Entry.Kind) {
  1503. case BitstreamEntry::Error:
  1504. return Error(MalformedBlock);
  1505. case BitstreamEntry::EndBlock:
  1506. return GlobalCleanup();
  1507. case BitstreamEntry::SubBlock:
  1508. switch (Entry.ID) {
  1509. default: // Skip unknown content.
  1510. if (Stream.SkipBlock())
  1511. return Error(InvalidRecord);
  1512. break;
  1513. case bitc::BLOCKINFO_BLOCK_ID:
  1514. if (Stream.ReadBlockInfoBlock())
  1515. return Error(MalformedBlock);
  1516. break;
  1517. case bitc::PARAMATTR_BLOCK_ID:
  1518. if (error_code EC = ParseAttributeBlock())
  1519. return EC;
  1520. break;
  1521. case bitc::PARAMATTR_GROUP_BLOCK_ID:
  1522. if (error_code EC = ParseAttributeGroupBlock())
  1523. return EC;
  1524. break;
  1525. case bitc::TYPE_BLOCK_ID_NEW:
  1526. if (error_code EC = ParseTypeTable())
  1527. return EC;
  1528. break;
  1529. case bitc::VALUE_SYMTAB_BLOCK_ID:
  1530. if (error_code EC = ParseValueSymbolTable())
  1531. return EC;
  1532. SeenValueSymbolTable = true;
  1533. break;
  1534. case bitc::CONSTANTS_BLOCK_ID:
  1535. if (error_code EC = ParseConstants())
  1536. return EC;
  1537. if (error_code EC = ResolveGlobalAndAliasInits())
  1538. return EC;
  1539. break;
  1540. case bitc::METADATA_BLOCK_ID:
  1541. if (error_code EC = ParseMetadata())
  1542. return EC;
  1543. break;
  1544. case bitc::FUNCTION_BLOCK_ID:
  1545. // If this is the first function body we've seen, reverse the
  1546. // FunctionsWithBodies list.
  1547. if (!SeenFirstFunctionBody) {
  1548. std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
  1549. if (error_code EC = GlobalCleanup())
  1550. return EC;
  1551. SeenFirstFunctionBody = true;
  1552. }
  1553. if (error_code EC = RememberAndSkipFunctionBody())
  1554. return EC;
  1555. // For streaming bitcode, suspend parsing when we reach the function
  1556. // bodies. Subsequent materialization calls will resume it when
  1557. // necessary. For streaming, the function bodies must be at the end of
  1558. // the bitcode. If the bitcode file is old, the symbol table will be
  1559. // at the end instead and will not have been seen yet. In this case,
  1560. // just finish the parse now.
  1561. if (LazyStreamer && SeenValueSymbolTable) {
  1562. NextUnreadBit = Stream.GetCurrentBitNo();
  1563. return error_code::success();
  1564. }
  1565. break;
  1566. case bitc::USELIST_BLOCK_ID:
  1567. if (error_code EC = ParseUseLists())
  1568. return EC;
  1569. break;
  1570. }
  1571. continue;
  1572. case BitstreamEntry::Record:
  1573. // The interesting case.
  1574. break;
  1575. }
  1576. // Read a record.
  1577. switch (Stream.readRecord(Entry.ID, Record)) {
  1578. default: break; // Default behavior, ignore unknown content.
  1579. case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
  1580. if (Record.size() < 1)
  1581. return Error(InvalidRecord);
  1582. // Only version #0 and #1 are supported so far.
  1583. unsigned module_version = Record[0];
  1584. switch (module_version) {
  1585. default:
  1586. return Error(InvalidValue);
  1587. case 0:
  1588. UseRelativeIDs = false;
  1589. break;
  1590. case 1:
  1591. UseRelativeIDs = true;
  1592. break;
  1593. }
  1594. break;
  1595. }
  1596. case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
  1597. std::string S;
  1598. if (ConvertToString(Record, 0, S))
  1599. return Error(InvalidRecord);
  1600. TheModule->setTargetTriple(S);
  1601. break;
  1602. }
  1603. case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
  1604. std::string S;
  1605. if (ConvertToString(Record, 0, S))
  1606. return Error(InvalidRecord);
  1607. TheModule->setDataLayout(S);
  1608. break;
  1609. }
  1610. case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
  1611. std::string S;
  1612. if (ConvertToString(Record, 0, S))
  1613. return Error(InvalidRecord);
  1614. TheModule->setModuleInlineAsm(S);
  1615. break;
  1616. }
  1617. case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
  1618. // FIXME: Remove in 4.0.
  1619. std::string S;
  1620. if (ConvertToString(Record, 0, S))
  1621. return Error(InvalidRecord);
  1622. // Ignore value.
  1623. break;
  1624. }
  1625. case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
  1626. std::string S;
  1627. if (ConvertToString(Record, 0, S))
  1628. return Error(InvalidRecord);
  1629. SectionTable.push_back(S);
  1630. break;
  1631. }
  1632. case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
  1633. std::string S;
  1634. if (ConvertToString(Record, 0, S))
  1635. return Error(InvalidRecord);
  1636. GCTable.push_back(S);
  1637. break;
  1638. }
  1639. // GLOBALVAR: [pointer type, isconst, initid,
  1640. // linkage, alignment, section, visibility, threadlocal,
  1641. // unnamed_addr, dllstorageclass]
  1642. case bitc::MODULE_CODE_GLOBALVAR: {
  1643. if (Record.size() < 6)
  1644. return Error(InvalidRecord);
  1645. Type *Ty = getTypeByID(Record[0]);
  1646. if (!Ty)
  1647. return Error(InvalidRecord);
  1648. if (!Ty->isPointerTy())
  1649. return Error(InvalidTypeForValue);
  1650. unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
  1651. Ty = cast<PointerType>(Ty)->getElementType();
  1652. bool isConstant = Record[1];
  1653. GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
  1654. unsigned Alignment = (1 << Record[4]) >> 1;
  1655. std::string Section;
  1656. if (Record[5]) {
  1657. if (Record[5]-1 >= SectionTable.size())
  1658. return Error(InvalidID);
  1659. Section = SectionTable[Record[5]-1];
  1660. }
  1661. GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
  1662. if (Record.size() > 6)
  1663. Visibility = GetDecodedVisibility(Record[6]);
  1664. GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
  1665. if (Record.size() > 7)
  1666. TLM = GetDecodedThreadLocalMode(Record[7]);
  1667. bool UnnamedAddr = false;
  1668. if (Record.size() > 8)
  1669. UnnamedAddr = Record[8];
  1670. bool ExternallyInitialized = false;
  1671. if (Record.size() > 9)
  1672. ExternallyInitialized = Record[9];
  1673. GlobalVariable *NewGV =
  1674. new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
  1675. TLM, AddressSpace, ExternallyInitialized);
  1676. NewGV->setAlignment(Alignment);
  1677. if (!Section.empty())
  1678. NewGV->setSection(Section);
  1679. NewGV->setVisibility(Visibility);
  1680. NewGV->setUnnamedAddr(UnnamedAddr);
  1681. if (Record.size() > 10)
  1682. NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
  1683. else
  1684. UpgradeDLLImportExportLinkage(NewGV, Record[3]);
  1685. ValueList.push_back(NewGV);
  1686. // Remember which value to use for the global initializer.
  1687. if (unsigned InitID = Record[2])
  1688. GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
  1689. break;
  1690. }
  1691. // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
  1692. // alignment, section, visibility, gc, unnamed_addr,
  1693. // dllstorageclass]
  1694. case bitc::MODULE_CODE_FUNCTION: {
  1695. if (Record.size() < 8)
  1696. return Error(InvalidRecord);
  1697. Type *Ty = getTypeByID(Record[0]);
  1698. if (!Ty)
  1699. return Error(InvalidRecord);
  1700. if (!Ty->isPointerTy())
  1701. return Error(InvalidTypeForValue);
  1702. FunctionType *FTy =
  1703. dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
  1704. if (!FTy)
  1705. return Error(InvalidTypeForValue);
  1706. Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
  1707. "", TheModule);
  1708. Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
  1709. bool isProto = Record[2];
  1710. Func->setLinkage(GetDecodedLinkage(Record[3]));
  1711. Func->setAttributes(getAttributes(Record[4]));
  1712. Func->setAlignment((1 << Record[5]) >> 1);
  1713. if (Record[6]) {
  1714. if (Record[6]-1 >= SectionTable.size())
  1715. return Error(InvalidID);
  1716. Func->setSection(SectionTable[Record[6]-1]);
  1717. }
  1718. Func->setVisibility(GetDecodedVisibility(Record[7]));
  1719. if (Record.size() > 8 && Record[8]) {
  1720. if (Record[8]-1 > GCTable.size())
  1721. return Error(InvalidID);
  1722. Func->setGC(GCTable[Record[8]-1].c_str());
  1723. }
  1724. bool UnnamedAddr = false;
  1725. if (Record.size() > 9)
  1726. UnnamedAddr = Record[9];
  1727. Func->setUnnamedAddr(UnnamedAddr);
  1728. if (Record.size() > 10 && Record[10] != 0)
  1729. FunctionPrefixes.push_back(std::make_pair(Func, Record[10]-1));
  1730. if (Record.size() > 11)
  1731. Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
  1732. else
  1733. UpgradeDLLImportExportLinkage(Func, Record[3]);
  1734. ValueList.push_back(Func);
  1735. // If this is a function with a body, remember the prototype we are
  1736. // creating now, so that we can match up the body with them later.
  1737. if (!isProto) {
  1738. FunctionsWithBodies.push_back(Func);
  1739. if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
  1740. }
  1741. break;
  1742. }
  1743. // ALIAS: [alias type, aliasee val#, linkage]
  1744. // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
  1745. case bitc::MODULE_CODE_ALIAS: {
  1746. if (Record.size() < 3)
  1747. return Error(InvalidRecord);
  1748. Type *Ty = getTypeByID(Record[0]);
  1749. if (!Ty)
  1750. return Error(InvalidRecord);
  1751. if (!Ty->isPointerTy())
  1752. return Error(InvalidTypeForValue);
  1753. GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
  1754. "", 0, TheModule);
  1755. // Old bitcode files didn't have visibility field.
  1756. if (Record.size() > 3)
  1757. NewGA->setVisibility(GetDecodedVisibility(Record[3]));
  1758. if (Record.size() > 4)
  1759. NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
  1760. else
  1761. UpgradeDLLImportExportLinkage(NewGA, Record[2]);
  1762. ValueList.push_back(NewGA);
  1763. AliasInits.push_back(std::make_pair(NewGA, Record[1]));
  1764. break;
  1765. }
  1766. /// MODULE_CODE_PURGEVALS: [numvals]
  1767. case bitc::MODULE_CODE_PURGEVALS:
  1768. // Trim down the value list to the specified size.
  1769. if (Record.size() < 1 || Record[0] > ValueList.size())
  1770. return Error(InvalidRecord);
  1771. ValueList.shrinkTo(Record[0]);
  1772. break;
  1773. }
  1774. Record.clear();
  1775. }
  1776. }
  1777. error_code BitcodeReader::ParseBitcodeInto(Module *M) {
  1778. TheModule = 0;
  1779. if (error_code EC = InitStream())
  1780. return EC;
  1781. // Sniff for the signature.
  1782. if (Stream.Read(8) != 'B' ||
  1783. Stream.Read(8) != 'C' ||
  1784. Stream.Read(4) != 0x0 ||
  1785. Stream.Read(4) != 0xC ||
  1786. Stream.Read(4) != 0xE ||
  1787. Stream.Read(4) != 0xD)
  1788. return Error(InvalidBitcodeSignature);
  1789. // We expect a number of well-defined blocks, though we don't necessarily
  1790. // need to understand them all.
  1791. while (1) {
  1792. if (Stream.AtEndOfStream())
  1793. return error_code::success();
  1794. BitstreamEntry Entry =
  1795. Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
  1796. switch (Entry.Kind) {
  1797. case BitstreamEntry::Error:
  1798. return Error(MalformedBlock);
  1799. case BitstreamEntry::EndBlock:
  1800. return error_code::success();
  1801. case BitstreamEntry::SubBlock:
  1802. switch (Entry.ID) {
  1803. case bitc::BLOCKINFO_BLOCK_ID:
  1804. if (Stream.ReadBlockInfoBlock())
  1805. return Error(MalformedBlock);
  1806. break;
  1807. case bitc::MODULE_BLOCK_ID:
  1808. // Reject multiple MODULE_BLOCK's in a single bitstream.
  1809. if (TheModule)
  1810. return Error(InvalidMultipleBlocks);
  1811. TheModule = M;
  1812. if (error_code EC = ParseModule(false))
  1813. return EC;
  1814. if (LazyStreamer)
  1815. return error_code::success();
  1816. break;
  1817. default:
  1818. if (Stream.SkipBlock())
  1819. return Error(InvalidRecord);
  1820. break;
  1821. }
  1822. continue;
  1823. case BitstreamEntry::Record:
  1824. // There should be no records in the top-level of blocks.
  1825. // The ranlib in Xcode 4 will align archive members by appending newlines
  1826. // to the end of them. If this file size is a multiple of 4 but not 8, we
  1827. // have to read and ignore these final 4 bytes :-(
  1828. if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
  1829. Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
  1830. Stream.AtEndOfStream())
  1831. return error_code::success();
  1832. return Error(InvalidRecord);
  1833. }
  1834. }
  1835. }
  1836. error_code BitcodeReader::ParseModuleTriple(std::string &Triple) {
  1837. if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
  1838. return Error(InvalidRecord);
  1839. SmallVector<uint64_t, 64> Record;
  1840. // Read all the records for this module.
  1841. while (1) {
  1842. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  1843. switch (Entry.Kind) {
  1844. case BitstreamEntry::SubBlock: // Handled for us already.
  1845. case BitstreamEntry::Error:
  1846. return Error(MalformedBlock);
  1847. case BitstreamEntry::EndBlock:
  1848. return error_code::success();
  1849. case BitstreamEntry::Record:
  1850. // The interesting case.
  1851. break;
  1852. }
  1853. // Read a record.
  1854. switch (Stream.readRecord(Entry.ID, Record)) {
  1855. default: break; // Default behavior, ignore unknown content.
  1856. case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
  1857. std::string S;
  1858. if (ConvertToString(Record, 0, S))
  1859. return Error(InvalidRecord);
  1860. Triple = S;
  1861. break;
  1862. }
  1863. }
  1864. Record.clear();
  1865. }
  1866. }
  1867. error_code BitcodeReader::ParseTriple(std::string &Triple) {
  1868. if (error_code EC = InitStream())
  1869. return EC;
  1870. // Sniff for the signature.
  1871. if (Stream.Read(8) != 'B' ||
  1872. Stream.Read(8) != 'C' ||
  1873. Stream.Read(4) != 0x0 ||
  1874. Stream.Read(4) != 0xC ||
  1875. Stream.Read(4) != 0xE ||
  1876. Stream.Read(4) != 0xD)
  1877. return Error(InvalidBitcodeSignature);
  1878. // We expect a number of well-defined blocks, though we don't necessarily
  1879. // need to understand them all.
  1880. while (1) {
  1881. BitstreamEntry Entry = Stream.advance();
  1882. switch (Entry.Kind) {
  1883. case BitstreamEntry::Error:
  1884. return Error(MalformedBlock);
  1885. case BitstreamEntry::EndBlock:
  1886. return error_code::success();
  1887. case BitstreamEntry::SubBlock:
  1888. if (Entry.ID == bitc::MODULE_BLOCK_ID)
  1889. return ParseModuleTriple(Triple);
  1890. // Ignore other sub-blocks.
  1891. if (Stream.SkipBlock())
  1892. return Error(MalformedBlock);
  1893. continue;
  1894. case BitstreamEntry::Record:
  1895. Stream.skipRecord(Entry.ID);
  1896. continue;
  1897. }
  1898. }
  1899. }
  1900. /// ParseMetadataAttachment - Parse metadata attachments.
  1901. error_code BitcodeReader::ParseMetadataAttachment() {
  1902. if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
  1903. return Error(InvalidRecord);
  1904. SmallVector<uint64_t, 64> Record;
  1905. while (1) {
  1906. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  1907. switch (Entry.Kind) {
  1908. case BitstreamEntry::SubBlock: // Handled for us already.
  1909. case BitstreamEntry::Error:
  1910. return Error(MalformedBlock);
  1911. case BitstreamEntry::EndBlock:
  1912. return error_code::success();
  1913. case BitstreamEntry::Record:
  1914. // The interesting case.
  1915. break;
  1916. }
  1917. // Read a metadata attachment record.
  1918. Record.clear();
  1919. switch (Stream.readRecord(Entry.ID, Record)) {
  1920. default: // Default behavior: ignore.
  1921. break;
  1922. case bitc::METADATA_ATTACHMENT: {
  1923. unsigned RecordLength = Record.size();
  1924. if (Record.empty() || (RecordLength - 1) % 2 == 1)
  1925. return Error(InvalidRecord);
  1926. Instruction *Inst = InstructionList[Record[0]];
  1927. for (unsigned i = 1; i != RecordLength; i = i+2) {
  1928. unsigned Kind = Record[i];
  1929. DenseMap<unsigned, unsigned>::iterator I =
  1930. MDKindMap.find(Kind);
  1931. if (I == MDKindMap.end())
  1932. return Error(InvalidID);
  1933. Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
  1934. Inst->setMetadata(I->second, cast<MDNode>(Node));
  1935. if (I->second == LLVMContext::MD_tbaa)
  1936. InstsWithTBAATag.push_back(Inst);
  1937. }
  1938. break;
  1939. }
  1940. }
  1941. }
  1942. }
  1943. /// ParseFunctionBody - Lazily parse the specified function body block.
  1944. error_code BitcodeReader::ParseFunctionBody(Function *F) {
  1945. if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
  1946. return Error(InvalidRecord);
  1947. InstructionList.clear();
  1948. unsigned ModuleValueListSize = ValueList.size();
  1949. unsigned ModuleMDValueListSize = MDValueList.size();
  1950. // Add all the function arguments to the value table.
  1951. for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
  1952. ValueList.push_back(I);
  1953. unsigned NextValueNo = ValueList.size();
  1954. BasicBlock *CurBB = 0;
  1955. unsigned CurBBNo = 0;
  1956. DebugLoc LastLoc;
  1957. // Read all the records.
  1958. SmallVector<uint64_t, 64> Record;
  1959. while (1) {
  1960. BitstreamEntry Entry = Stream.advance();
  1961. switch (Entry.Kind) {
  1962. case BitstreamEntry::Error:
  1963. return Error(MalformedBlock);
  1964. case BitstreamEntry::EndBlock:
  1965. goto OutOfRecordLoop;
  1966. case BitstreamEntry::SubBlock:
  1967. switch (Entry.ID) {
  1968. default: // Skip unknown content.
  1969. if (Stream.SkipBlock())
  1970. return Error(InvalidRecord);
  1971. break;
  1972. case bitc::CONSTANTS_BLOCK_ID:
  1973. if (error_code EC = ParseConstants())
  1974. return EC;
  1975. NextValueNo = ValueList.size();
  1976. break;
  1977. case bitc::VALUE_SYMTAB_BLOCK_ID:
  1978. if (error_code EC = ParseValueSymbolTable())
  1979. return EC;
  1980. break;
  1981. case bitc::METADATA_ATTACHMENT_ID:
  1982. if (error_code EC = ParseMetadataAttachment())
  1983. return EC;
  1984. break;
  1985. case bitc::METADATA_BLOCK_ID:
  1986. if (error_code EC = ParseMetadata())
  1987. return EC;
  1988. break;
  1989. }
  1990. continue;
  1991. case BitstreamEntry::Record:
  1992. // The interesting case.
  1993. break;
  1994. }
  1995. // Read a record.
  1996. Record.clear();
  1997. Instruction *I = 0;
  1998. unsigned BitCode = Stream.readRecord(Entry.ID, Record);
  1999. switch (BitCode) {
  2000. default: // Default behavior: reject
  2001. return Error(InvalidValue);
  2002. case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
  2003. if (Record.size() < 1 || Record[0] == 0)
  2004. return Error(InvalidRecord);
  2005. // Create all the basic blocks for the function.
  2006. FunctionBBs.resize(Record[0]);
  2007. for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
  2008. FunctionBBs[i] = BasicBlock::Create(Context, "", F);
  2009. CurBB = FunctionBBs[0];
  2010. continue;
  2011. case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
  2012. // This record indicates that the last instruction is at the same
  2013. // location as the previous instruction with a location.
  2014. I = 0;
  2015. // Get the last instruction emitted.
  2016. if (CurBB && !CurBB->empty())
  2017. I = &CurBB->back();
  2018. else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
  2019. !FunctionBBs[CurBBNo-1]->empty())
  2020. I = &FunctionBBs[CurBBNo-1]->back();
  2021. if (I == 0)
  2022. return Error(InvalidRecord);
  2023. I->setDebugLoc(LastLoc);
  2024. I = 0;
  2025. continue;
  2026. case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
  2027. I = 0; // Get the last instruction emitted.
  2028. if (CurBB && !CurBB->empty())
  2029. I = &CurBB->back();
  2030. else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
  2031. !FunctionBBs[CurBBNo-1]->empty())
  2032. I = &FunctionBBs[CurBBNo-1]->back();
  2033. if (I == 0 || Record.size() < 4)
  2034. return Error(InvalidRecord);
  2035. unsigned Line = Record[0], Col = Record[1];
  2036. unsigned ScopeID = Record[2], IAID = Record[3];
  2037. MDNode *Scope = 0, *IA = 0;
  2038. if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
  2039. if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
  2040. LastLoc = DebugLoc::get(Line, Col, Scope, IA);
  2041. I->setDebugLoc(LastLoc);
  2042. I = 0;
  2043. continue;
  2044. }
  2045. case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
  2046. unsigned OpNum = 0;
  2047. Value *LHS, *RHS;
  2048. if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
  2049. popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
  2050. OpNum+1 > Record.size())
  2051. return Error(InvalidRecord);
  2052. int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
  2053. if (Opc == -1)
  2054. return Error(InvalidRecord);
  2055. I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
  2056. InstructionList.push_back(I);
  2057. if (OpNum < Record.size()) {
  2058. if (Opc == Instruction::Add ||
  2059. Opc == Instruction::Sub ||
  2060. Opc == Instruction::Mul ||
  2061. Opc == Instruction::Shl) {
  2062. if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
  2063. cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
  2064. if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
  2065. cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
  2066. } else if (Opc == Instruction::SDiv ||
  2067. Opc == Instruction::UDiv ||
  2068. Opc == Instruction::LShr ||
  2069. Opc == Instruction::AShr) {
  2070. if (Record[OpNum] & (1 << bitc::PEO_EXACT))
  2071. cast<BinaryOperator>(I)->setIsExact(true);
  2072. } else if (isa<FPMathOperator>(I)) {
  2073. FastMathFlags FMF;
  2074. if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
  2075. FMF.setUnsafeAlgebra();
  2076. if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
  2077. FMF.setNoNaNs();
  2078. if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
  2079. FMF.setNoInfs();
  2080. if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
  2081. FMF.setNoSignedZeros();
  2082. if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
  2083. FMF.setAllowReciprocal();
  2084. if (FMF.any())
  2085. I->setFastMathFlags(FMF);
  2086. }
  2087. }
  2088. break;
  2089. }
  2090. case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
  2091. unsigned OpNum = 0;
  2092. Value *Op;
  2093. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  2094. OpNum+2 != Record.size())
  2095. return Error(InvalidRecord);
  2096. Type *ResTy = getTypeByID(Record[OpNum]);
  2097. int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
  2098. if (Opc == -1 || ResTy == 0)
  2099. return Error(InvalidRecord);
  2100. Instruction *Temp = 0;
  2101. if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
  2102. if (Temp) {
  2103. InstructionList.push_back(Temp);
  2104. CurBB->getInstList().push_back(Temp);
  2105. }
  2106. } else {
  2107. I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
  2108. }
  2109. InstructionList.push_back(I);
  2110. break;
  2111. }
  2112. case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
  2113. case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
  2114. unsigned OpNum = 0;
  2115. Value *BasePtr;
  2116. if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
  2117. return Error(InvalidRecord);
  2118. SmallVector<Value*, 16> GEPIdx;
  2119. while (OpNum != Record.size()) {
  2120. Value *Op;
  2121. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  2122. return Error(InvalidRecord);
  2123. GEPIdx.push_back(Op);
  2124. }
  2125. I = GetElementPtrInst::Create(BasePtr, GEPIdx);
  2126. InstructionList.push_back(I);
  2127. if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
  2128. cast<GetElementPtrInst>(I)->setIsInBounds(true);
  2129. break;
  2130. }
  2131. case bitc::FUNC_CODE_INST_EXTRACTVAL: {
  2132. // EXTRACTVAL: [opty, opval, n x indices]
  2133. unsigned OpNum = 0;
  2134. Value *Agg;
  2135. if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
  2136. return Error(InvalidRecord);
  2137. SmallVector<unsigned, 4> EXTRACTVALIdx;
  2138. for (unsigned RecSize = Record.size();
  2139. OpNum != RecSize; ++OpNum) {
  2140. uint64_t Index = Record[OpNum];
  2141. if ((unsigned)Index != Index)
  2142. return Error(InvalidValue);
  2143. EXTRACTVALIdx.push_back((unsigned)Index);
  2144. }
  2145. I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
  2146. InstructionList.push_back(I);
  2147. break;
  2148. }
  2149. case bitc::FUNC_CODE_INST_INSERTVAL: {
  2150. // INSERTVAL: [opty, opval, opty, opval, n x indices]
  2151. unsigned OpNum = 0;
  2152. Value *Agg;
  2153. if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
  2154. return Error(InvalidRecord);
  2155. Value *Val;
  2156. if (getValueTypePair(Record, OpNum, NextValueNo, Val))
  2157. return Error(InvalidRecord);
  2158. SmallVector<unsigned, 4> INSERTVALIdx;
  2159. for (unsigned RecSize = Record.size();
  2160. OpNum != RecSize; ++OpNum) {
  2161. uint64_t Index = Record[OpNum];
  2162. if ((unsigned)Index != Index)
  2163. return Error(InvalidValue);
  2164. INSERTVALIdx.push_back((unsigned)Index);
  2165. }
  2166. I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
  2167. InstructionList.push_back(I);
  2168. break;
  2169. }
  2170. case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
  2171. // obsolete form of select
  2172. // handles select i1 ... in old bitcode
  2173. unsigned OpNum = 0;
  2174. Value *TrueVal, *FalseVal, *Cond;
  2175. if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
  2176. popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
  2177. popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
  2178. return Error(InvalidRecord);
  2179. I = SelectInst::Create(Cond, TrueVal, FalseVal);
  2180. InstructionList.push_back(I);
  2181. break;
  2182. }
  2183. case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
  2184. // new form of select
  2185. // handles select i1 or select [N x i1]
  2186. unsigned OpNum = 0;
  2187. Value *TrueVal, *FalseVal, *Cond;
  2188. if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
  2189. popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
  2190. getValueTypePair(Record, OpNum, NextValueNo, Cond))
  2191. return Error(InvalidRecord);
  2192. // select condition can be either i1 or [N x i1]
  2193. if (VectorType* vector_type =
  2194. dyn_cast<VectorType>(Cond->getType())) {
  2195. // expect <n x i1>
  2196. if (vector_type->getElementType() != Type::getInt1Ty(Context))
  2197. return Error(InvalidTypeForValue);
  2198. } else {
  2199. // expect i1
  2200. if (Cond->getType() != Type::getInt1Ty(Context))
  2201. return Error(InvalidTypeForValue);
  2202. }
  2203. I = SelectInst::Create(Cond, TrueVal, FalseVal);
  2204. InstructionList.push_back(I);
  2205. break;
  2206. }
  2207. case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
  2208. unsigned OpNum = 0;
  2209. Value *Vec, *Idx;
  2210. if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
  2211. popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
  2212. return Error(InvalidRecord);
  2213. I = ExtractElementInst::Create(Vec, Idx);
  2214. InstructionList.push_back(I);
  2215. break;
  2216. }
  2217. case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
  2218. unsigned OpNum = 0;
  2219. Value *Vec, *Elt, *Idx;
  2220. if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
  2221. popValue(Record, OpNum, NextValueNo,
  2222. cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
  2223. popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
  2224. return Error(InvalidRecord);
  2225. I = InsertElementInst::Create(Vec, Elt, Idx);
  2226. InstructionList.push_back(I);
  2227. break;
  2228. }
  2229. case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
  2230. unsigned OpNum = 0;
  2231. Value *Vec1, *Vec2, *Mask;
  2232. if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
  2233. popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
  2234. return Error(InvalidRecord);
  2235. if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
  2236. return Error(InvalidRecord);
  2237. I = new ShuffleVectorInst(Vec1, Vec2, Mask);
  2238. InstructionList.push_back(I);
  2239. break;
  2240. }
  2241. case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
  2242. // Old form of ICmp/FCmp returning bool
  2243. // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
  2244. // both legal on vectors but had different behaviour.
  2245. case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
  2246. // FCmp/ICmp returning bool or vector of bool
  2247. unsigned OpNum = 0;
  2248. Value *LHS, *RHS;
  2249. if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
  2250. popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
  2251. OpNum+1 != Record.size())
  2252. return Error(InvalidRecord);
  2253. if (LHS->getType()->isFPOrFPVectorTy())
  2254. I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
  2255. else
  2256. I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
  2257. InstructionList.push_back(I);
  2258. break;
  2259. }
  2260. case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
  2261. {
  2262. unsigned Size = Record.size();
  2263. if (Size == 0) {
  2264. I = ReturnInst::Create(Context);
  2265. InstructionList.push_back(I);
  2266. break;
  2267. }
  2268. unsigned OpNum = 0;
  2269. Value *Op = NULL;
  2270. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  2271. return Error(InvalidRecord);
  2272. if (OpNum != Record.size())
  2273. return Error(InvalidRecord);
  2274. I = ReturnInst::Create(Context, Op);
  2275. InstructionList.push_back(I);
  2276. break;
  2277. }
  2278. case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
  2279. if (Record.size() != 1 && Record.size() != 3)
  2280. return Error(InvalidRecord);
  2281. BasicBlock *TrueDest = getBasicBlock(Record[0]);
  2282. if (TrueDest == 0)
  2283. return Error(InvalidRecord);
  2284. if (Record.size() == 1) {
  2285. I = BranchInst::Create(TrueDest);
  2286. InstructionList.push_back(I);
  2287. }
  2288. else {
  2289. BasicBlock *FalseDest = getBasicBlock(Record[1]);
  2290. Value *Cond = getValue(Record, 2, NextValueNo,
  2291. Type::getInt1Ty(Context));
  2292. if (FalseDest == 0 || Cond == 0)
  2293. return Error(InvalidRecord);
  2294. I = BranchInst::Create(TrueDest, FalseDest, Cond);
  2295. InstructionList.push_back(I);
  2296. }
  2297. break;
  2298. }
  2299. case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
  2300. // Check magic
  2301. if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
  2302. // "New" SwitchInst format with case ranges. The changes to write this
  2303. // format were reverted but we still recognize bitcode that uses it.
  2304. // Hopefully someday we will have support for case ranges and can use
  2305. // this format again.
  2306. Type *OpTy = getTypeByID(Record[1]);
  2307. unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
  2308. Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
  2309. BasicBlock *Default = getBasicBlock(Record[3]);
  2310. if (OpTy == 0 || Cond == 0 || Default == 0)
  2311. return Error(InvalidRecord);
  2312. unsigned NumCases = Record[4];
  2313. SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
  2314. InstructionList.push_back(SI);
  2315. unsigned CurIdx = 5;
  2316. for (unsigned i = 0; i != NumCases; ++i) {
  2317. SmallVector<ConstantInt*, 1> CaseVals;
  2318. unsigned NumItems = Record[CurIdx++];
  2319. for (unsigned ci = 0; ci != NumItems; ++ci) {
  2320. bool isSingleNumber = Record[CurIdx++];
  2321. APInt Low;
  2322. unsigned ActiveWords = 1;
  2323. if (ValueBitWidth > 64)
  2324. ActiveWords = Record[CurIdx++];
  2325. Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
  2326. ValueBitWidth);
  2327. CurIdx += ActiveWords;
  2328. if (!isSingleNumber) {
  2329. ActiveWords = 1;
  2330. if (ValueBitWidth > 64)
  2331. ActiveWords = Record[CurIdx++];
  2332. APInt High =
  2333. ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
  2334. ValueBitWidth);
  2335. CurIdx += ActiveWords;
  2336. // FIXME: It is not clear whether values in the range should be
  2337. // compared as signed or unsigned values. The partially
  2338. // implemented changes that used this format in the past used
  2339. // unsigned comparisons.
  2340. for ( ; Low.ule(High); ++Low)
  2341. CaseVals.push_back(ConstantInt::get(Context, Low));
  2342. } else
  2343. CaseVals.push_back(ConstantInt::get(Context, Low));
  2344. }
  2345. BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
  2346. for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
  2347. cve = CaseVals.end(); cvi != cve; ++cvi)
  2348. SI->addCase(*cvi, DestBB);
  2349. }
  2350. I = SI;
  2351. break;
  2352. }
  2353. // Old SwitchInst format without case ranges.
  2354. if (Record.size() < 3 || (Record.size() & 1) == 0)
  2355. return Error(InvalidRecord);
  2356. Type *OpTy = getTypeByID(Record[0]);
  2357. Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
  2358. BasicBlock *Default = getBasicBlock(Record[2]);
  2359. if (OpTy == 0 || Cond == 0 || Default == 0)
  2360. return Error(InvalidRecord);
  2361. unsigned NumCases = (Record.size()-3)/2;
  2362. SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
  2363. InstructionList.push_back(SI);
  2364. for (unsigned i = 0, e = NumCases; i != e; ++i) {
  2365. ConstantInt *CaseVal =
  2366. dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
  2367. BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
  2368. if (CaseVal == 0 || DestBB == 0) {
  2369. delete SI;
  2370. return Error(InvalidRecord);
  2371. }
  2372. SI->addCase(CaseVal, DestBB);
  2373. }
  2374. I = SI;
  2375. break;
  2376. }
  2377. case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
  2378. if (Record.size() < 2)
  2379. return Error(InvalidRecord);
  2380. Type *OpTy = getTypeByID(Record[0]);
  2381. Value *Address = getValue(Record, 1, NextValueNo, OpTy);
  2382. if (OpTy == 0 || Address == 0)
  2383. return Error(InvalidRecord);
  2384. unsigned NumDests = Record.size()-2;
  2385. IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
  2386. InstructionList.push_back(IBI);
  2387. for (unsigned i = 0, e = NumDests; i != e; ++i) {
  2388. if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
  2389. IBI->addDestination(DestBB);
  2390. } else {
  2391. delete IBI;
  2392. return Error(InvalidRecord);
  2393. }
  2394. }
  2395. I = IBI;
  2396. break;
  2397. }
  2398. case bitc::FUNC_CODE_INST_INVOKE: {
  2399. // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
  2400. if (Record.size() < 4)
  2401. return Error(InvalidRecord);
  2402. AttributeSet PAL = getAttributes(Record[0]);
  2403. unsigned CCInfo = Record[1];
  2404. BasicBlock *NormalBB = getBasicBlock(Record[2]);
  2405. BasicBlock *UnwindBB = getBasicBlock(Record[3]);
  2406. unsigned OpNum = 4;
  2407. Value *Callee;
  2408. if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
  2409. return Error(InvalidRecord);
  2410. PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
  2411. FunctionType *FTy = !CalleeTy ? 0 :
  2412. dyn_cast<FunctionType>(CalleeTy->getElementType());
  2413. // Check that the right number of fixed parameters are here.
  2414. if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
  2415. Record.size() < OpNum+FTy->getNumParams())
  2416. return Error(InvalidRecord);
  2417. SmallVector<Value*, 16> Ops;
  2418. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
  2419. Ops.push_back(getValue(Record, OpNum, NextValueNo,
  2420. FTy->getParamType(i)));
  2421. if (Ops.back() == 0)
  2422. return Error(InvalidRecord);
  2423. }
  2424. if (!FTy->isVarArg()) {
  2425. if (Record.size() != OpNum)
  2426. return Error(InvalidRecord);
  2427. } else {
  2428. // Read type/value pairs for varargs params.
  2429. while (OpNum != Record.size()) {
  2430. Value *Op;
  2431. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  2432. return Error(InvalidRecord);
  2433. Ops.push_back(Op);
  2434. }
  2435. }
  2436. I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
  2437. InstructionList.push_back(I);
  2438. cast<InvokeInst>(I)->setCallingConv(
  2439. static_cast<CallingConv::ID>(CCInfo));
  2440. cast<InvokeInst>(I)->setAttributes(PAL);
  2441. break;
  2442. }
  2443. case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
  2444. unsigned Idx = 0;
  2445. Value *Val = 0;
  2446. if (getValueTypePair(Record, Idx, NextValueNo, Val))
  2447. return Error(InvalidRecord);
  2448. I = ResumeInst::Create(Val);
  2449. InstructionList.push_back(I);
  2450. break;
  2451. }
  2452. case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
  2453. I = new UnreachableInst(Context);
  2454. InstructionList.push_back(I);
  2455. break;
  2456. case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
  2457. if (Record.size() < 1 || ((Record.size()-1)&1))
  2458. return Error(InvalidRecord);
  2459. Type *Ty = getTypeByID(Record[0]);
  2460. if (!Ty)
  2461. return Error(InvalidRecord);
  2462. PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
  2463. InstructionList.push_back(PN);
  2464. for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
  2465. Value *V;
  2466. // With the new function encoding, it is possible that operands have
  2467. // negative IDs (for forward references). Use a signed VBR
  2468. // representation to keep the encoding small.
  2469. if (UseRelativeIDs)
  2470. V = getValueSigned(Record, 1+i, NextValueNo, Ty);
  2471. else
  2472. V = getValue(Record, 1+i, NextValueNo, Ty);
  2473. BasicBlock *BB = getBasicBlock(Record[2+i]);
  2474. if (!V || !BB)
  2475. return Error(InvalidRecord);
  2476. PN->addIncoming(V, BB);
  2477. }
  2478. I = PN;
  2479. break;
  2480. }
  2481. case bitc::FUNC_CODE_INST_LANDINGPAD: {
  2482. // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
  2483. unsigned Idx = 0;
  2484. if (Record.size() < 4)
  2485. return Error(InvalidRecord);
  2486. Type *Ty = getTypeByID(Record[Idx++]);
  2487. if (!Ty)
  2488. return Error(InvalidRecord);
  2489. Value *PersFn = 0;
  2490. if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
  2491. return Error(InvalidRecord);
  2492. bool IsCleanup = !!Record[Idx++];
  2493. unsigned NumClauses = Record[Idx++];
  2494. LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
  2495. LP->setCleanup(IsCleanup);
  2496. for (unsigned J = 0; J != NumClauses; ++J) {
  2497. LandingPadInst::ClauseType CT =
  2498. LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
  2499. Value *Val;
  2500. if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
  2501. delete LP;
  2502. return Error(InvalidRecord);
  2503. }
  2504. assert((CT != LandingPadInst::Catch ||
  2505. !isa<ArrayType>(Val->getType())) &&
  2506. "Catch clause has a invalid type!");
  2507. assert((CT != LandingPadInst::Filter ||
  2508. isa<ArrayType>(Val->getType())) &&
  2509. "Filter clause has invalid type!");
  2510. LP->addClause(Val);
  2511. }
  2512. I = LP;
  2513. InstructionList.push_back(I);
  2514. break;
  2515. }
  2516. case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
  2517. if (Record.size() != 4)
  2518. return Error(InvalidRecord);
  2519. PointerType *Ty =
  2520. dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
  2521. Type *OpTy = getTypeByID(Record[1]);
  2522. Value *Size = getFnValueByID(Record[2], OpTy);
  2523. unsigned Align = Record[3];
  2524. if (!Ty || !Size)
  2525. return Error(InvalidRecord);
  2526. I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
  2527. InstructionList.push_back(I);
  2528. break;
  2529. }
  2530. case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
  2531. unsigned OpNum = 0;
  2532. Value *Op;
  2533. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  2534. OpNum+2 != Record.size())
  2535. return Error(InvalidRecord);
  2536. I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
  2537. InstructionList.push_back(I);
  2538. break;
  2539. }
  2540. case bitc::FUNC_CODE_INST_LOADATOMIC: {
  2541. // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
  2542. unsigned OpNum = 0;
  2543. Value *Op;
  2544. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  2545. OpNum+4 != Record.size())
  2546. return Error(InvalidRecord);
  2547. AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
  2548. if (Ordering == NotAtomic || Ordering == Release ||
  2549. Ordering == AcquireRelease)
  2550. return Error(InvalidRecord);
  2551. if (Ordering != NotAtomic && Record[OpNum] == 0)
  2552. return Error(InvalidRecord);
  2553. SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
  2554. I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
  2555. Ordering, SynchScope);
  2556. InstructionList.push_back(I);
  2557. break;
  2558. }
  2559. case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
  2560. unsigned OpNum = 0;
  2561. Value *Val, *Ptr;
  2562. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
  2563. popValue(Record, OpNum, NextValueNo,
  2564. cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
  2565. OpNum+2 != Record.size())
  2566. return Error(InvalidRecord);
  2567. I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
  2568. InstructionList.push_back(I);
  2569. break;
  2570. }
  2571. case bitc::FUNC_CODE_INST_STOREATOMIC: {
  2572. // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
  2573. unsigned OpNum = 0;
  2574. Value *Val, *Ptr;
  2575. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
  2576. popValue(Record, OpNum, NextValueNo,
  2577. cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
  2578. OpNum+4 != Record.size())
  2579. return Error(InvalidRecord);
  2580. AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
  2581. if (Ordering == NotAtomic || Ordering == Acquire ||
  2582. Ordering == AcquireRelease)
  2583. return Error(InvalidRecord);
  2584. SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
  2585. if (Ordering != NotAtomic && Record[OpNum] == 0)
  2586. return Error(InvalidRecord);
  2587. I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
  2588. Ordering, SynchScope);
  2589. InstructionList.push_back(I);
  2590. break;
  2591. }
  2592. case bitc::FUNC_CODE_INST_CMPXCHG: {
  2593. // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
  2594. // failureordering]
  2595. unsigned OpNum = 0;
  2596. Value *Ptr, *Cmp, *New;
  2597. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
  2598. popValue(Record, OpNum, NextValueNo,
  2599. cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
  2600. popValue(Record, OpNum, NextValueNo,
  2601. cast<PointerType>(Ptr->getType())->getElementType(), New) ||
  2602. (OpNum + 3 != Record.size() && OpNum + 4 != Record.size()))
  2603. return Error(InvalidRecord);
  2604. AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
  2605. if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
  2606. return Error(InvalidRecord);
  2607. SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
  2608. AtomicOrdering FailureOrdering;
  2609. if (Record.size() < 7)
  2610. FailureOrdering =
  2611. AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
  2612. else
  2613. FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
  2614. I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
  2615. SynchScope);
  2616. cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
  2617. InstructionList.push_back(I);
  2618. break;
  2619. }
  2620. case bitc::FUNC_CODE_INST_ATOMICRMW: {
  2621. // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
  2622. unsigned OpNum = 0;
  2623. Value *Ptr, *Val;
  2624. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
  2625. popValue(Record, OpNum, NextValueNo,
  2626. cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
  2627. OpNum+4 != Record.size())
  2628. return Error(InvalidRecord);
  2629. AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
  2630. if (Operation < AtomicRMWInst::FIRST_BINOP ||
  2631. Operation > AtomicRMWInst::LAST_BINOP)
  2632. return Error(InvalidRecord);
  2633. AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
  2634. if (Ordering == NotAtomic || Ordering == Unordered)
  2635. return Error(InvalidRecord);
  2636. SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
  2637. I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
  2638. cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
  2639. InstructionList.push_back(I);
  2640. break;
  2641. }
  2642. case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
  2643. if (2 != Record.size())
  2644. return Error(InvalidRecord);
  2645. AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
  2646. if (Ordering == NotAtomic || Ordering == Unordered ||
  2647. Ordering == Monotonic)
  2648. return Error(InvalidRecord);
  2649. SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
  2650. I = new FenceInst(Context, Ordering, SynchScope);
  2651. InstructionList.push_back(I);
  2652. break;
  2653. }
  2654. case bitc::FUNC_CODE_INST_CALL: {
  2655. // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
  2656. if (Record.size() < 3)
  2657. return Error(InvalidRecord);
  2658. AttributeSet PAL = getAttributes(Record[0]);
  2659. unsigned CCInfo = Record[1];
  2660. unsigned OpNum = 2;
  2661. Value *Callee;
  2662. if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
  2663. return Error(InvalidRecord);
  2664. PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
  2665. FunctionType *FTy = 0;
  2666. if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
  2667. if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
  2668. return Error(InvalidRecord);
  2669. SmallVector<Value*, 16> Args;
  2670. // Read the fixed params.
  2671. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
  2672. if (FTy->getParamType(i)->isLabelTy())
  2673. Args.push_back(getBasicBlock(Record[OpNum]));
  2674. else
  2675. Args.push_back(getValue(Record, OpNum, NextValueNo,
  2676. FTy->getParamType(i)));
  2677. if (Args.back() == 0)
  2678. return Error(InvalidRecord);
  2679. }
  2680. // Read type/value pairs for varargs params.
  2681. if (!FTy->isVarArg()) {
  2682. if (OpNum != Record.size())
  2683. return Error(InvalidRecord);
  2684. } else {
  2685. while (OpNum != Record.size()) {
  2686. Value *Op;
  2687. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  2688. return Error(InvalidRecord);
  2689. Args.push_back(Op);
  2690. }
  2691. }
  2692. I = CallInst::Create(Callee, Args);
  2693. InstructionList.push_back(I);
  2694. cast<CallInst>(I)->setCallingConv(
  2695. static_cast<CallingConv::ID>(CCInfo>>1));
  2696. cast<CallInst>(I)->setTailCall(CCInfo & 1);
  2697. cast<CallInst>(I)->setAttributes(PAL);
  2698. break;
  2699. }
  2700. case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
  2701. if (Record.size() < 3)
  2702. return Error(InvalidRecord);
  2703. Type *OpTy = getTypeByID(Record[0]);
  2704. Value *Op = getValue(Record, 1, NextValueNo, OpTy);
  2705. Type *ResTy = getTypeByID(Record[2]);
  2706. if (!OpTy || !Op || !ResTy)
  2707. return Error(InvalidRecord);
  2708. I = new VAArgInst(Op, ResTy);
  2709. InstructionList.push_back(I);
  2710. break;
  2711. }
  2712. }
  2713. // Add instruction to end of current BB. If there is no current BB, reject
  2714. // this file.
  2715. if (CurBB == 0) {
  2716. delete I;
  2717. return Error(InvalidInstructionWithNoBB);
  2718. }
  2719. CurBB->getInstList().push_back(I);
  2720. // If this was a terminator instruction, move to the next block.
  2721. if (isa<TerminatorInst>(I)) {
  2722. ++CurBBNo;
  2723. CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
  2724. }
  2725. // Non-void values get registered in the value table for future use.
  2726. if (I && !I->getType()->isVoidTy())
  2727. ValueList.AssignValue(I, NextValueNo++);
  2728. }
  2729. OutOfRecordLoop:
  2730. // Check the function list for unresolved values.
  2731. if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
  2732. if (A->getParent() == 0) {
  2733. // We found at least one unresolved value. Nuke them all to avoid leaks.
  2734. for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
  2735. if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
  2736. A->replaceAllUsesWith(UndefValue::get(A->getType()));
  2737. delete A;
  2738. }
  2739. }
  2740. return Error(NeverResolvedValueFoundInFunction);
  2741. }
  2742. }
  2743. // FIXME: Check for unresolved forward-declared metadata references
  2744. // and clean up leaks.
  2745. // See if anything took the address of blocks in this function. If so,
  2746. // resolve them now.
  2747. DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
  2748. BlockAddrFwdRefs.find(F);
  2749. if (BAFRI != BlockAddrFwdRefs.end()) {
  2750. std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
  2751. for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
  2752. unsigned BlockIdx = RefList[i].first;
  2753. if (BlockIdx >= FunctionBBs.size())
  2754. return Error(InvalidID);
  2755. GlobalVariable *FwdRef = RefList[i].second;
  2756. FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
  2757. FwdRef->eraseFromParent();
  2758. }
  2759. BlockAddrFwdRefs.erase(BAFRI);
  2760. }
  2761. // Trim the value list down to the size it was before we parsed this function.
  2762. ValueList.shrinkTo(ModuleValueListSize);
  2763. MDValueList.shrinkTo(ModuleMDValueListSize);
  2764. std::vector<BasicBlock*>().swap(FunctionBBs);
  2765. return error_code::success();
  2766. }
  2767. /// Find the function body in the bitcode stream
  2768. error_code BitcodeReader::FindFunctionInStream(Function *F,
  2769. DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
  2770. while (DeferredFunctionInfoIterator->second == 0) {
  2771. if (Stream.AtEndOfStream())
  2772. return Error(CouldNotFindFunctionInStream);
  2773. // ParseModule will parse the next body in the stream and set its
  2774. // position in the DeferredFunctionInfo map.
  2775. if (error_code EC = ParseModule(true))
  2776. return EC;
  2777. }
  2778. return error_code::success();
  2779. }
  2780. //===----------------------------------------------------------------------===//
  2781. // GVMaterializer implementation
  2782. //===----------------------------------------------------------------------===//
  2783. bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
  2784. if (const Function *F = dyn_cast<Function>(GV)) {
  2785. return F->isDeclaration() &&
  2786. DeferredFunctionInfo.count(const_cast<Function*>(F));
  2787. }
  2788. return false;
  2789. }
  2790. error_code BitcodeReader::Materialize(GlobalValue *GV) {
  2791. Function *F = dyn_cast<Function>(GV);
  2792. // If it's not a function or is already material, ignore the request.
  2793. if (!F || !F->isMaterializable())
  2794. return error_code::success();
  2795. DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
  2796. assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
  2797. // If its position is recorded as 0, its body is somewhere in the stream
  2798. // but we haven't seen it yet.
  2799. if (DFII->second == 0 && LazyStreamer)
  2800. if (error_code EC = FindFunctionInStream(F, DFII))
  2801. return EC;
  2802. // Move the bit stream to the saved position of the deferred function body.
  2803. Stream.JumpToBit(DFII->second);
  2804. if (error_code EC = ParseFunctionBody(F))
  2805. return EC;
  2806. // Upgrade any old intrinsic calls in the function.
  2807. for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
  2808. E = UpgradedIntrinsics.end(); I != E; ++I) {
  2809. if (I->first != I->second) {
  2810. for (auto UI = I->first->user_begin(), UE = I->first->user_end();
  2811. UI != UE;) {
  2812. if (CallInst* CI = dyn_cast<CallInst>(*UI++))
  2813. UpgradeIntrinsicCall(CI, I->second);
  2814. }
  2815. }
  2816. }
  2817. return error_code::success();
  2818. }
  2819. bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
  2820. const Function *F = dyn_cast<Function>(GV);
  2821. if (!F || F->isDeclaration())
  2822. return false;
  2823. return DeferredFunctionInfo.count(const_cast<Function*>(F));
  2824. }
  2825. void BitcodeReader::Dematerialize(GlobalValue *GV) {
  2826. Function *F = dyn_cast<Function>(GV);
  2827. // If this function isn't dematerializable, this is a noop.
  2828. if (!F || !isDematerializable(F))
  2829. return;
  2830. assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
  2831. // Just forget the function body, we can remat it later.
  2832. F->deleteBody();
  2833. }
  2834. error_code BitcodeReader::MaterializeModule(Module *M) {
  2835. assert(M == TheModule &&
  2836. "Can only Materialize the Module this BitcodeReader is attached to.");
  2837. // Iterate over the module, deserializing any functions that are still on
  2838. // disk.
  2839. for (Module::iterator F = TheModule->begin(), E = TheModule->end();
  2840. F != E; ++F) {
  2841. if (F->isMaterializable()) {
  2842. if (error_code EC = Materialize(F))
  2843. return EC;
  2844. }
  2845. }
  2846. // At this point, if there are any function bodies, the current bit is
  2847. // pointing to the END_BLOCK record after them. Now make sure the rest
  2848. // of the bits in the module have been read.
  2849. if (NextUnreadBit)
  2850. ParseModule(true);
  2851. // Upgrade any intrinsic calls that slipped through (should not happen!) and
  2852. // delete the old functions to clean up. We can't do this unless the entire
  2853. // module is materialized because there could always be another function body
  2854. // with calls to the old function.
  2855. for (std::vector<std::pair<Function*, Function*> >::iterator I =
  2856. UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
  2857. if (I->first != I->second) {
  2858. for (auto UI = I->first->user_begin(), UE = I->first->user_end();
  2859. UI != UE;) {
  2860. if (CallInst* CI = dyn_cast<CallInst>(*UI++))
  2861. UpgradeIntrinsicCall(CI, I->second);
  2862. }
  2863. if (!I->first->use_empty())
  2864. I->first->replaceAllUsesWith(I->second);
  2865. I->first->eraseFromParent();
  2866. }
  2867. }
  2868. std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
  2869. for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
  2870. UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
  2871. UpgradeDebugInfo(*M);
  2872. return error_code::success();
  2873. }
  2874. error_code BitcodeReader::InitStream() {
  2875. if (LazyStreamer)
  2876. return InitLazyStream();
  2877. return InitStreamFromBuffer();
  2878. }
  2879. error_code BitcodeReader::InitStreamFromBuffer() {
  2880. const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
  2881. const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
  2882. if (Buffer->getBufferSize() & 3) {
  2883. if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
  2884. return Error(InvalidBitcodeSignature);
  2885. else
  2886. return Error(BitcodeStreamInvalidSize);
  2887. }
  2888. // If we have a wrapper header, parse it and ignore the non-bc file contents.
  2889. // The magic number is 0x0B17C0DE stored in little endian.
  2890. if (isBitcodeWrapper(BufPtr, BufEnd))
  2891. if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
  2892. return Error(InvalidBitcodeWrapperHeader);
  2893. StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
  2894. Stream.init(*StreamFile);
  2895. return error_code::success();
  2896. }
  2897. error_code BitcodeReader::InitLazyStream() {
  2898. // Check and strip off the bitcode wrapper; BitstreamReader expects never to
  2899. // see it.
  2900. StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
  2901. StreamFile.reset(new BitstreamReader(Bytes));
  2902. Stream.init(*StreamFile);
  2903. unsigned char buf[16];
  2904. if (Bytes->readBytes(0, 16, buf) == -1)
  2905. return Error(BitcodeStreamInvalidSize);
  2906. if (!isBitcode(buf, buf + 16))
  2907. return Error(InvalidBitcodeSignature);
  2908. if (isBitcodeWrapper(buf, buf + 4)) {
  2909. const unsigned char *bitcodeStart = buf;
  2910. const unsigned char *bitcodeEnd = buf + 16;
  2911. SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
  2912. Bytes->dropLeadingBytes(bitcodeStart - buf);
  2913. Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
  2914. }
  2915. return error_code::success();
  2916. }
  2917. namespace {
  2918. class BitcodeErrorCategoryType : public _do_message {
  2919. const char *name() const override {
  2920. return "llvm.bitcode";
  2921. }
  2922. std::string message(int IE) const override {
  2923. BitcodeReader::ErrorType E = static_cast<BitcodeReader::ErrorType>(IE);
  2924. switch (E) {
  2925. case BitcodeReader::BitcodeStreamInvalidSize:
  2926. return "Bitcode stream length should be >= 16 bytes and a multiple of 4";
  2927. case BitcodeReader::ConflictingMETADATA_KINDRecords:
  2928. return "Conflicting METADATA_KIND records";
  2929. case BitcodeReader::CouldNotFindFunctionInStream:
  2930. return "Could not find function in stream";
  2931. case BitcodeReader::ExpectedConstant:
  2932. return "Expected a constant";
  2933. case BitcodeReader::InsufficientFunctionProtos:
  2934. return "Insufficient function protos";
  2935. case BitcodeReader::InvalidBitcodeSignature:
  2936. return "Invalid bitcode signature";
  2937. case BitcodeReader::InvalidBitcodeWrapperHeader:
  2938. return "Invalid bitcode wrapper header";
  2939. case BitcodeReader::InvalidConstantReference:
  2940. return "Invalid ronstant reference";
  2941. case BitcodeReader::InvalidID:
  2942. return "Invalid ID";
  2943. case BitcodeReader::InvalidInstructionWithNoBB:
  2944. return "Invalid instruction with no BB";
  2945. case BitcodeReader::InvalidRecord:
  2946. return "Invalid record";
  2947. case BitcodeReader::InvalidTypeForValue:
  2948. return "Invalid type for value";
  2949. case BitcodeReader::InvalidTYPETable:
  2950. return "Invalid TYPE table";
  2951. case BitcodeReader::InvalidType:
  2952. return "Invalid type";
  2953. case BitcodeReader::MalformedBlock:
  2954. return "Malformed block";
  2955. case BitcodeReader::MalformedGlobalInitializerSet:
  2956. return "Malformed global initializer set";
  2957. case BitcodeReader::InvalidMultipleBlocks:
  2958. return "Invalid multiple blocks";
  2959. case BitcodeReader::NeverResolvedValueFoundInFunction:
  2960. return "Never resolved value found in function";
  2961. case BitcodeReader::InvalidValue:
  2962. return "Invalid value";
  2963. }
  2964. llvm_unreachable("Unknown error type!");
  2965. }
  2966. };
  2967. }
  2968. const error_category &BitcodeReader::BitcodeErrorCategory() {
  2969. static BitcodeErrorCategoryType O;
  2970. return O;
  2971. }
  2972. //===----------------------------------------------------------------------===//
  2973. // External interface
  2974. //===----------------------------------------------------------------------===//
  2975. /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
  2976. ///
  2977. ErrorOr<Module *> llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
  2978. LLVMContext &Context) {
  2979. Module *M = new Module(Buffer->getBufferIdentifier(), Context);
  2980. BitcodeReader *R = new BitcodeReader(Buffer, Context);
  2981. M->setMaterializer(R);
  2982. if (error_code EC = R->ParseBitcodeInto(M)) {
  2983. delete M; // Also deletes R.
  2984. return EC;
  2985. }
  2986. // Have the BitcodeReader dtor delete 'Buffer'.
  2987. R->setBufferOwned(true);
  2988. R->materializeForwardReferencedFunctions();
  2989. return M;
  2990. }
  2991. Module *llvm::getStreamedBitcodeModule(const std::string &name,
  2992. DataStreamer *streamer,
  2993. LLVMContext &Context,
  2994. std::string *ErrMsg) {
  2995. Module *M = new Module(name, Context);
  2996. BitcodeReader *R = new BitcodeReader(streamer, Context);
  2997. M->setMaterializer(R);
  2998. if (error_code EC = R->ParseBitcodeInto(M)) {
  2999. if (ErrMsg)
  3000. *ErrMsg = EC.message();
  3001. delete M; // Also deletes R.
  3002. return 0;
  3003. }
  3004. R->setBufferOwned(false); // no buffer to delete
  3005. return M;
  3006. }
  3007. ErrorOr<Module *> llvm::parseBitcodeFile(MemoryBuffer *Buffer,
  3008. LLVMContext &Context) {
  3009. ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModule(Buffer, Context);
  3010. if (!ModuleOrErr)
  3011. return ModuleOrErr;
  3012. Module *M = ModuleOrErr.get();
  3013. // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
  3014. // there was an error.
  3015. static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
  3016. // Read in the entire module, and destroy the BitcodeReader.
  3017. if (error_code EC = M->materializeAllPermanently()) {
  3018. delete M;
  3019. return EC;
  3020. }
  3021. // TODO: Restore the use-lists to the in-memory state when the bitcode was
  3022. // written. We must defer until the Module has been fully materialized.
  3023. return M;
  3024. }
  3025. std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
  3026. LLVMContext& Context,
  3027. std::string *ErrMsg) {
  3028. BitcodeReader *R = new BitcodeReader(Buffer, Context);
  3029. // Don't let the BitcodeReader dtor delete 'Buffer'.
  3030. R->setBufferOwned(false);
  3031. std::string Triple("");
  3032. if (error_code EC = R->ParseTriple(Triple))
  3033. if (ErrMsg)
  3034. *ErrMsg = EC.message();
  3035. delete R;
  3036. return Triple;
  3037. }