BitcodeReader.cpp 107 KB

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