BitcodeReader.cpp 127 KB

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