BitcodeReader.cpp 116 KB

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