BitcodeReader.cpp 170 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844
  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 "llvm/ADT/STLExtras.h"
  11. #include "llvm/ADT/SmallString.h"
  12. #include "llvm/ADT/SmallVector.h"
  13. #include "llvm/ADT/Triple.h"
  14. #include "llvm/Bitcode/BitstreamReader.h"
  15. #include "llvm/Bitcode/LLVMBitCodes.h"
  16. #include "llvm/IR/AutoUpgrade.h"
  17. #include "llvm/IR/Constants.h"
  18. #include "llvm/IR/DebugInfo.h"
  19. #include "llvm/IR/DebugInfoMetadata.h"
  20. #include "llvm/IR/DerivedTypes.h"
  21. #include "llvm/IR/DiagnosticPrinter.h"
  22. #include "llvm/IR/GVMaterializer.h"
  23. #include "llvm/IR/InlineAsm.h"
  24. #include "llvm/IR/IntrinsicInst.h"
  25. #include "llvm/IR/LLVMContext.h"
  26. #include "llvm/IR/Module.h"
  27. #include "llvm/IR/OperandTraits.h"
  28. #include "llvm/IR/Operator.h"
  29. #include "llvm/IR/ValueHandle.h"
  30. #include "llvm/Support/DataStream.h"
  31. #include "llvm/Support/ManagedStatic.h"
  32. #include "llvm/Support/MathExtras.h"
  33. #include "llvm/Support/MemoryBuffer.h"
  34. #include "llvm/Support/raw_ostream.h"
  35. #include <deque>
  36. #include "dxc/HLSL/DxilOperations.h" // HLSL Change
  37. using namespace llvm;
  38. namespace {
  39. enum {
  40. SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
  41. };
  42. class BitcodeReaderValueList {
  43. std::vector<WeakVH> ValuePtrs;
  44. /// As we resolve forward-referenced constants, we add information about them
  45. /// to this vector. This allows us to resolve them in bulk instead of
  46. /// resolving each reference at a time. See the code in
  47. /// ResolveConstantForwardRefs for more information about this.
  48. ///
  49. /// The key of this vector is the placeholder constant, the value is the slot
  50. /// number that holds the resolved value.
  51. typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
  52. ResolveConstantsTy ResolveConstants;
  53. LLVMContext &Context;
  54. public:
  55. BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
  56. ~BitcodeReaderValueList() {
  57. assert(ResolveConstants.empty() && "Constants not resolved?");
  58. }
  59. // vector compatibility methods
  60. unsigned size() const { return ValuePtrs.size(); }
  61. void resize(unsigned N) { ValuePtrs.resize(N); }
  62. void push_back(Value *V) { ValuePtrs.emplace_back(V); }
  63. void clear() {
  64. assert(ResolveConstants.empty() && "Constants not resolved?");
  65. ValuePtrs.clear();
  66. }
  67. Value *operator[](unsigned i) const {
  68. assert(i < ValuePtrs.size());
  69. return ValuePtrs[i];
  70. }
  71. Value *back() const { return ValuePtrs.back(); }
  72. void pop_back() { ValuePtrs.pop_back(); }
  73. bool empty() const { return ValuePtrs.empty(); }
  74. void shrinkTo(unsigned N) {
  75. assert(N <= size() && "Invalid shrinkTo request!");
  76. ValuePtrs.resize(N);
  77. }
  78. Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
  79. Value *getValueFwdRef(unsigned Idx, Type *Ty);
  80. void assignValue(Value *V, unsigned Idx);
  81. /// Once all constants are read, this method bulk resolves any forward
  82. /// references.
  83. void resolveConstantForwardRefs();
  84. };
  85. class BitcodeReaderMDValueList {
  86. unsigned NumFwdRefs;
  87. bool AnyFwdRefs;
  88. unsigned MinFwdRef;
  89. unsigned MaxFwdRef;
  90. std::vector<TrackingMDRef> MDValuePtrs;
  91. LLVMContext &Context;
  92. public:
  93. BitcodeReaderMDValueList(LLVMContext &C)
  94. : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
  95. // vector compatibility methods
  96. unsigned size() const { return MDValuePtrs.size(); }
  97. void resize(unsigned N) { MDValuePtrs.resize(N); }
  98. void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); }
  99. void clear() { MDValuePtrs.clear(); }
  100. Metadata *back() const { return MDValuePtrs.back(); }
  101. void pop_back() { MDValuePtrs.pop_back(); }
  102. bool empty() const { return MDValuePtrs.empty(); }
  103. Metadata *operator[](unsigned i) const {
  104. assert(i < MDValuePtrs.size());
  105. return MDValuePtrs[i];
  106. }
  107. void shrinkTo(unsigned N) {
  108. assert(N <= size() && "Invalid shrinkTo request!");
  109. MDValuePtrs.resize(N);
  110. }
  111. Metadata *getValueFwdRef(unsigned Idx);
  112. void assignValue(Metadata *MD, unsigned Idx);
  113. void tryToResolveCycles();
  114. };
  115. class BitcodeReader : public GVMaterializer {
  116. LLVMContext &Context;
  117. DiagnosticHandlerFunction DiagnosticHandler;
  118. Module *TheModule = nullptr;
  119. std::unique_ptr<MemoryBuffer> Buffer;
  120. std::unique_ptr<BitstreamReader> StreamFile;
  121. BitstreamCursor Stream;
  122. uint64_t NextUnreadBit = 0;
  123. bool SeenValueSymbolTable = false;
  124. std::vector<Type*> TypeList;
  125. BitcodeReaderValueList ValueList;
  126. BitcodeReaderMDValueList MDValueList;
  127. std::vector<Comdat *> ComdatList;
  128. SmallVector<Instruction *, 64> InstructionList;
  129. std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
  130. std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
  131. std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
  132. std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
  133. std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
  134. SmallVector<Instruction*, 64> InstsWithTBAATag;
  135. /// The set of attributes by index. Index zero in the file is for null, and
  136. /// is thus not represented here. As such all indices are off by one.
  137. std::vector<AttributeSet> MAttributes;
  138. /// \brief The set of attribute groups.
  139. std::map<unsigned, AttributeSet> MAttributeGroups;
  140. /// While parsing a function body, this is a list of the basic blocks for the
  141. /// function.
  142. std::vector<BasicBlock*> FunctionBBs;
  143. // When reading the module header, this list is populated with functions that
  144. // have bodies later in the file.
  145. std::vector<Function*> FunctionsWithBodies;
  146. // When intrinsic functions are encountered which require upgrading they are
  147. // stored here with their replacement function.
  148. typedef DenseMap<Function*, Function*> UpgradedIntrinsicMap;
  149. UpgradedIntrinsicMap UpgradedIntrinsics;
  150. // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
  151. DenseMap<unsigned, unsigned> MDKindMap;
  152. // Several operations happen after the module header has been read, but
  153. // before function bodies are processed. This keeps track of whether
  154. // we've done this yet.
  155. bool SeenFirstFunctionBody = false;
  156. /// When function bodies are initially scanned, this map contains info about
  157. /// where to find deferred function body in the stream.
  158. DenseMap<Function*, uint64_t> DeferredFunctionInfo;
  159. /// When Metadata block is initially scanned when parsing the module, we may
  160. /// choose to defer parsing of the metadata. This vector contains info about
  161. /// which Metadata blocks are deferred.
  162. std::vector<uint64_t> DeferredMetadataInfo;
  163. /// These are basic blocks forward-referenced by block addresses. They are
  164. /// inserted lazily into functions when they're loaded. The basic block ID is
  165. /// its index into the vector.
  166. DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
  167. std::deque<Function *> BasicBlockFwdRefQueue;
  168. /// Indicates that we are using a new encoding for instruction operands where
  169. /// most operands in the current FUNCTION_BLOCK are encoded relative to the
  170. /// instruction number, for a more compact encoding. Some instruction
  171. /// operands are not relative to the instruction ID: basic block numbers, and
  172. /// types. Once the old style function blocks have been phased out, we would
  173. /// not need this flag.
  174. bool UseRelativeIDs = false;
  175. /// True if all functions will be materialized, negating the need to process
  176. /// (e.g.) blockaddress forward references.
  177. bool WillMaterializeAllForwardRefs = false;
  178. /// Functions that have block addresses taken. This is usually empty.
  179. SmallPtrSet<const Function *, 4> BlockAddressesTaken;
  180. /// True if any Metadata block has been materialized.
  181. bool IsMetadataMaterialized = false;
  182. bool StripDebugInfo = false;
  183. public:
  184. std::error_code error(BitcodeError E, const Twine &Message);
  185. std::error_code error(BitcodeError E);
  186. std::error_code error(const Twine &Message);
  187. BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
  188. DiagnosticHandlerFunction DiagnosticHandler);
  189. BitcodeReader(LLVMContext &Context,
  190. DiagnosticHandlerFunction DiagnosticHandler);
  191. ~BitcodeReader() override { freeState(); }
  192. std::error_code materializeForwardReferencedFunctions();
  193. void freeState();
  194. void releaseBuffer();
  195. BitstreamUseTracker Tracker; // HLSL Change
  196. bool isDematerializable(const GlobalValue *GV) const override;
  197. std::error_code materialize(GlobalValue *GV) override;
  198. std::error_code materializeModule(Module *M) override;
  199. std::vector<StructType *> getIdentifiedStructTypes() const override;
  200. void dematerialize(GlobalValue *GV) override;
  201. /// \brief Main interface to parsing a bitcode buffer.
  202. /// \returns true if an error occurred.
  203. std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
  204. Module *M,
  205. bool ShouldLazyLoadMetadata = false);
  206. /// \brief Cheap mechanism to just extract module triple
  207. /// \returns true if an error occurred.
  208. ErrorOr<std::string> parseTriple();
  209. static uint64_t decodeSignRotatedValue(uint64_t V);
  210. /// Materialize any deferred Metadata block.
  211. std::error_code materializeMetadata() override;
  212. void setStripDebugInfo() override;
  213. private:
  214. std::vector<StructType *> IdentifiedStructTypes;
  215. StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
  216. StructType *createIdentifiedStructType(LLVMContext &Context);
  217. Type *getTypeByID(unsigned ID);
  218. Value *getFnValueByID(unsigned ID, Type *Ty) {
  219. if (Ty && Ty->isMetadataTy())
  220. return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
  221. return ValueList.getValueFwdRef(ID, Ty);
  222. }
  223. Metadata *getFnMetadataByID(unsigned ID) {
  224. return MDValueList.getValueFwdRef(ID);
  225. }
  226. BasicBlock *getBasicBlock(unsigned ID) const {
  227. if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
  228. return FunctionBBs[ID];
  229. }
  230. AttributeSet getAttributes(unsigned i) const {
  231. if (i-1 < MAttributes.size())
  232. return MAttributes[i-1];
  233. return AttributeSet();
  234. }
  235. /// Read a value/type pair out of the specified record from slot 'Slot'.
  236. /// Increment Slot past the number of slots used in the record. Return true on
  237. /// failure.
  238. bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
  239. unsigned InstNum, Value *&ResVal) {
  240. if (Slot == Record.size()) return true;
  241. unsigned ValNo = (unsigned)Record[Slot++];
  242. // Adjust the ValNo, if it was encoded relative to the InstNum.
  243. if (UseRelativeIDs)
  244. ValNo = InstNum - ValNo;
  245. if (ValNo < InstNum) {
  246. // If this is not a forward reference, just return the value we already
  247. // have.
  248. ResVal = getFnValueByID(ValNo, nullptr);
  249. return ResVal == nullptr;
  250. }
  251. if (Slot == Record.size())
  252. return true;
  253. unsigned TypeNo = (unsigned)Record[Slot++];
  254. ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
  255. return ResVal == nullptr;
  256. }
  257. /// Read a value out of the specified record from slot 'Slot'. Increment Slot
  258. /// past the number of slots used by the value in the record. Return true if
  259. /// there is an error.
  260. bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
  261. unsigned InstNum, Type *Ty, Value *&ResVal) {
  262. if (getValue(Record, Slot, InstNum, Ty, ResVal))
  263. return true;
  264. // All values currently take a single record slot.
  265. ++Slot;
  266. return false;
  267. }
  268. /// Like popValue, but does not increment the Slot number.
  269. bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
  270. unsigned InstNum, Type *Ty, Value *&ResVal) {
  271. ResVal = getValue(Record, Slot, InstNum, Ty);
  272. return ResVal == nullptr;
  273. }
  274. /// Version of getValue that returns ResVal directly, or 0 if there is an
  275. /// error.
  276. Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
  277. unsigned InstNum, Type *Ty) {
  278. if (Slot == Record.size()) return nullptr;
  279. unsigned ValNo = (unsigned)Record[Slot];
  280. // Adjust the ValNo, if it was encoded relative to the InstNum.
  281. if (UseRelativeIDs)
  282. ValNo = InstNum - ValNo;
  283. return getFnValueByID(ValNo, Ty);
  284. }
  285. /// Like getValue, but decodes signed VBRs.
  286. Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
  287. unsigned InstNum, Type *Ty) {
  288. if (Slot == Record.size()) return nullptr;
  289. unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
  290. // Adjust the ValNo, if it was encoded relative to the InstNum.
  291. if (UseRelativeIDs)
  292. ValNo = InstNum - ValNo;
  293. return getFnValueByID(ValNo, Ty);
  294. }
  295. /// Converts alignment exponent (i.e. power of two (or zero)) to the
  296. /// corresponding alignment to use. If alignment is too large, returns
  297. /// a corresponding error code.
  298. std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
  299. std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
  300. std::error_code parseModule(bool Resume, bool ShouldLazyLoadMetadata = false);
  301. std::error_code parseAttributeBlock();
  302. std::error_code parseAttributeGroupBlock();
  303. std::error_code parseTypeTable();
  304. std::error_code parseTypeTableBody();
  305. std::error_code parseValueSymbolTable();
  306. std::error_code parseConstants();
  307. std::error_code rememberAndSkipFunctionBody();
  308. /// Save the positions of the Metadata blocks and skip parsing the blocks.
  309. std::error_code rememberAndSkipMetadata();
  310. std::error_code parseFunctionBody(Function *F);
  311. std::error_code globalCleanup();
  312. std::error_code resolveGlobalAndAliasInits();
  313. std::error_code parseMetadata();
  314. std::error_code parseMetadataAttachment(Function &F);
  315. ErrorOr<std::string> parseModuleTriple();
  316. std::error_code parseUseLists();
  317. std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
  318. std::error_code initStreamFromBuffer();
  319. std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
  320. std::error_code findFunctionInStream(
  321. Function *F,
  322. DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
  323. };
  324. } // namespace
  325. BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
  326. DiagnosticSeverity Severity,
  327. const Twine &Msg)
  328. : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
  329. void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
  330. static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
  331. std::error_code EC, const Twine &Message) {
  332. BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
  333. DiagnosticHandler(DI);
  334. return EC;
  335. }
  336. static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
  337. std::error_code EC) {
  338. return error(DiagnosticHandler, EC, EC.message());
  339. }
  340. static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
  341. const Twine &Message) {
  342. return error(DiagnosticHandler,
  343. make_error_code(BitcodeError::CorruptedBitcode), Message);
  344. }
  345. std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
  346. return ::error(DiagnosticHandler, make_error_code(E), Message);
  347. }
  348. std::error_code BitcodeReader::error(const Twine &Message) {
  349. return ::error(DiagnosticHandler,
  350. make_error_code(BitcodeError::CorruptedBitcode), Message);
  351. }
  352. std::error_code BitcodeReader::error(BitcodeError E) {
  353. return ::error(DiagnosticHandler, make_error_code(E));
  354. }
  355. static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
  356. LLVMContext &C) {
  357. if (F)
  358. return F;
  359. return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
  360. }
  361. // HLSL Change Starts
  362. static void ReportWarning(DiagnosticHandlerFunction F, const char *Msg) {
  363. BitcodeDiagnosticInfo BDI(std::error_code(), DiagnosticSeverity::DS_Warning,
  364. Msg);
  365. F(BDI);
  366. }
  367. // HLSL Change Ends
  368. BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
  369. DiagnosticHandlerFunction DiagnosticHandler)
  370. : Context(Context),
  371. DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
  372. Buffer(Buffer), ValueList(Context), MDValueList(Context) {}
  373. BitcodeReader::BitcodeReader(LLVMContext &Context,
  374. DiagnosticHandlerFunction DiagnosticHandler)
  375. : Context(Context),
  376. DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
  377. Buffer(nullptr), ValueList(Context), MDValueList(Context) {}
  378. std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
  379. if (WillMaterializeAllForwardRefs)
  380. return std::error_code();
  381. // Prevent recursion.
  382. WillMaterializeAllForwardRefs = true;
  383. while (!BasicBlockFwdRefQueue.empty()) {
  384. Function *F = BasicBlockFwdRefQueue.front();
  385. BasicBlockFwdRefQueue.pop_front();
  386. assert(F && "Expected valid function");
  387. if (!BasicBlockFwdRefs.count(F))
  388. // Already materialized.
  389. continue;
  390. // Check for a function that isn't materializable to prevent an infinite
  391. // loop. When parsing a blockaddress stored in a global variable, there
  392. // isn't a trivial way to check if a function will have a body without a
  393. // linear search through FunctionsWithBodies, so just check it here.
  394. if (!F->isMaterializable())
  395. return error("Never resolved function from blockaddress");
  396. // Try to materialize F.
  397. if (std::error_code EC = materialize(F))
  398. return EC;
  399. }
  400. assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
  401. // Reset state.
  402. WillMaterializeAllForwardRefs = false;
  403. return std::error_code();
  404. }
  405. void BitcodeReader::freeState() {
  406. Buffer = nullptr;
  407. std::vector<Type*>().swap(TypeList);
  408. ValueList.clear();
  409. MDValueList.clear();
  410. std::vector<Comdat *>().swap(ComdatList);
  411. std::vector<AttributeSet>().swap(MAttributes);
  412. std::vector<BasicBlock*>().swap(FunctionBBs);
  413. std::vector<Function*>().swap(FunctionsWithBodies);
  414. DeferredFunctionInfo.clear();
  415. DeferredMetadataInfo.clear();
  416. MDKindMap.clear();
  417. assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
  418. BasicBlockFwdRefQueue.clear();
  419. }
  420. //===----------------------------------------------------------------------===//
  421. // Helper functions to implement forward reference resolution, etc.
  422. //===----------------------------------------------------------------------===//
  423. /// Convert a string from a record into an std::string, return true on failure.
  424. template <typename StrTy>
  425. static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
  426. StrTy &Result) {
  427. if (Idx > Record.size())
  428. return true;
  429. for (unsigned i = Idx, e = Record.size(); i != e; ++i)
  430. Result += (char)Record[i];
  431. return false;
  432. }
  433. static bool hasImplicitComdat(size_t Val) {
  434. switch (Val) {
  435. default:
  436. return false;
  437. case 1: // Old WeakAnyLinkage
  438. case 4: // Old LinkOnceAnyLinkage
  439. case 10: // Old WeakODRLinkage
  440. case 11: // Old LinkOnceODRLinkage
  441. return true;
  442. }
  443. }
  444. static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
  445. switch (Val) {
  446. default: // Map unknown/new linkages to external
  447. case 0:
  448. return GlobalValue::ExternalLinkage;
  449. case 2:
  450. return GlobalValue::AppendingLinkage;
  451. case 3:
  452. return GlobalValue::InternalLinkage;
  453. case 5:
  454. return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
  455. case 6:
  456. return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
  457. case 7:
  458. return GlobalValue::ExternalWeakLinkage;
  459. case 8:
  460. return GlobalValue::CommonLinkage;
  461. case 9:
  462. return GlobalValue::PrivateLinkage;
  463. case 12:
  464. return GlobalValue::AvailableExternallyLinkage;
  465. case 13:
  466. return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
  467. case 14:
  468. return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
  469. case 15:
  470. return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
  471. case 1: // Old value with implicit comdat.
  472. case 16:
  473. return GlobalValue::WeakAnyLinkage;
  474. case 10: // Old value with implicit comdat.
  475. case 17:
  476. return GlobalValue::WeakODRLinkage;
  477. case 4: // Old value with implicit comdat.
  478. case 18:
  479. return GlobalValue::LinkOnceAnyLinkage;
  480. case 11: // Old value with implicit comdat.
  481. case 19:
  482. return GlobalValue::LinkOnceODRLinkage;
  483. }
  484. }
  485. static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
  486. switch (Val) {
  487. default: // Map unknown visibilities to default.
  488. case 0: return GlobalValue::DefaultVisibility;
  489. case 1: return GlobalValue::HiddenVisibility;
  490. case 2: return GlobalValue::ProtectedVisibility;
  491. }
  492. }
  493. static GlobalValue::DLLStorageClassTypes
  494. getDecodedDLLStorageClass(unsigned Val) {
  495. switch (Val) {
  496. default: // Map unknown values to default.
  497. case 0: return GlobalValue::DefaultStorageClass;
  498. case 1: return GlobalValue::DLLImportStorageClass;
  499. case 2: return GlobalValue::DLLExportStorageClass;
  500. }
  501. }
  502. static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
  503. switch (Val) {
  504. case 0: return GlobalVariable::NotThreadLocal;
  505. default: // Map unknown non-zero value to general dynamic.
  506. case 1: return GlobalVariable::GeneralDynamicTLSModel;
  507. case 2: return GlobalVariable::LocalDynamicTLSModel;
  508. case 3: return GlobalVariable::InitialExecTLSModel;
  509. case 4: return GlobalVariable::LocalExecTLSModel;
  510. }
  511. }
  512. static int getDecodedCastOpcode(unsigned Val) {
  513. switch (Val) {
  514. default: return -1;
  515. case bitc::CAST_TRUNC : return Instruction::Trunc;
  516. case bitc::CAST_ZEXT : return Instruction::ZExt;
  517. case bitc::CAST_SEXT : return Instruction::SExt;
  518. case bitc::CAST_FPTOUI : return Instruction::FPToUI;
  519. case bitc::CAST_FPTOSI : return Instruction::FPToSI;
  520. case bitc::CAST_UITOFP : return Instruction::UIToFP;
  521. case bitc::CAST_SITOFP : return Instruction::SIToFP;
  522. case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
  523. case bitc::CAST_FPEXT : return Instruction::FPExt;
  524. case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
  525. case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
  526. case bitc::CAST_BITCAST : return Instruction::BitCast;
  527. case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
  528. }
  529. }
  530. static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
  531. bool IsFP = Ty->isFPOrFPVectorTy();
  532. // BinOps are only valid for int/fp or vector of int/fp types
  533. if (!IsFP && !Ty->isIntOrIntVectorTy())
  534. return -1;
  535. switch (Val) {
  536. default:
  537. return -1;
  538. case bitc::BINOP_ADD:
  539. return IsFP ? Instruction::FAdd : Instruction::Add;
  540. case bitc::BINOP_SUB:
  541. return IsFP ? Instruction::FSub : Instruction::Sub;
  542. case bitc::BINOP_MUL:
  543. return IsFP ? Instruction::FMul : Instruction::Mul;
  544. case bitc::BINOP_UDIV:
  545. return IsFP ? -1 : Instruction::UDiv;
  546. case bitc::BINOP_SDIV:
  547. return IsFP ? Instruction::FDiv : Instruction::SDiv;
  548. case bitc::BINOP_UREM:
  549. return IsFP ? -1 : Instruction::URem;
  550. case bitc::BINOP_SREM:
  551. return IsFP ? Instruction::FRem : Instruction::SRem;
  552. case bitc::BINOP_SHL:
  553. return IsFP ? -1 : Instruction::Shl;
  554. case bitc::BINOP_LSHR:
  555. return IsFP ? -1 : Instruction::LShr;
  556. case bitc::BINOP_ASHR:
  557. return IsFP ? -1 : Instruction::AShr;
  558. case bitc::BINOP_AND:
  559. return IsFP ? -1 : Instruction::And;
  560. case bitc::BINOP_OR:
  561. return IsFP ? -1 : Instruction::Or;
  562. case bitc::BINOP_XOR:
  563. return IsFP ? -1 : Instruction::Xor;
  564. }
  565. }
  566. static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
  567. switch (Val) {
  568. default: return AtomicRMWInst::BAD_BINOP;
  569. case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
  570. case bitc::RMW_ADD: return AtomicRMWInst::Add;
  571. case bitc::RMW_SUB: return AtomicRMWInst::Sub;
  572. case bitc::RMW_AND: return AtomicRMWInst::And;
  573. case bitc::RMW_NAND: return AtomicRMWInst::Nand;
  574. case bitc::RMW_OR: return AtomicRMWInst::Or;
  575. case bitc::RMW_XOR: return AtomicRMWInst::Xor;
  576. case bitc::RMW_MAX: return AtomicRMWInst::Max;
  577. case bitc::RMW_MIN: return AtomicRMWInst::Min;
  578. case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
  579. case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
  580. }
  581. }
  582. static AtomicOrdering getDecodedOrdering(unsigned Val) {
  583. switch (Val) {
  584. case bitc::ORDERING_NOTATOMIC: return NotAtomic;
  585. case bitc::ORDERING_UNORDERED: return Unordered;
  586. case bitc::ORDERING_MONOTONIC: return Monotonic;
  587. case bitc::ORDERING_ACQUIRE: return Acquire;
  588. case bitc::ORDERING_RELEASE: return Release;
  589. case bitc::ORDERING_ACQREL: return AcquireRelease;
  590. default: // Map unknown orderings to sequentially-consistent.
  591. case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
  592. }
  593. }
  594. static SynchronizationScope getDecodedSynchScope(unsigned Val) {
  595. switch (Val) {
  596. case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
  597. default: // Map unknown scopes to cross-thread.
  598. case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
  599. }
  600. }
  601. static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
  602. switch (Val) {
  603. default: // Map unknown selection kinds to any.
  604. case bitc::COMDAT_SELECTION_KIND_ANY:
  605. return Comdat::Any;
  606. case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
  607. return Comdat::ExactMatch;
  608. case bitc::COMDAT_SELECTION_KIND_LARGEST:
  609. return Comdat::Largest;
  610. case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
  611. return Comdat::NoDuplicates;
  612. case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
  613. return Comdat::SameSize;
  614. }
  615. }
  616. static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
  617. FastMathFlags FMF;
  618. if (0 != (Val & FastMathFlags::UnsafeAlgebra))
  619. FMF.setUnsafeAlgebra();
  620. if (0 != (Val & FastMathFlags::NoNaNs))
  621. FMF.setNoNaNs();
  622. if (0 != (Val & FastMathFlags::NoInfs))
  623. FMF.setNoInfs();
  624. if (0 != (Val & FastMathFlags::NoSignedZeros))
  625. FMF.setNoSignedZeros();
  626. if (0 != (Val & FastMathFlags::AllowReciprocal))
  627. FMF.setAllowReciprocal();
  628. return FMF;
  629. }
  630. static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
  631. switch (Val) {
  632. case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
  633. case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
  634. }
  635. }
  636. namespace llvm {
  637. namespace {
  638. /// \brief A class for maintaining the slot number definition
  639. /// as a placeholder for the actual definition for forward constants defs.
  640. class ConstantPlaceHolder : public ConstantExpr {
  641. void operator=(const ConstantPlaceHolder &) = delete;
  642. public:
  643. // allocate space for exactly one operand
  644. void *operator new(size_t s) { return User::operator new(s, 1); }
  645. explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
  646. : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
  647. Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
  648. }
  649. /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
  650. static bool classof(const Value *V) {
  651. return isa<ConstantExpr>(V) &&
  652. cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
  653. }
  654. /// Provide fast operand accessors
  655. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  656. };
  657. }
  658. // FIXME: can we inherit this from ConstantExpr?
  659. template <>
  660. struct OperandTraits<ConstantPlaceHolder> :
  661. public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
  662. };
  663. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
  664. }
  665. void BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
  666. if (Idx == size()) {
  667. push_back(V);
  668. return;
  669. }
  670. if (Idx >= size())
  671. resize(Idx+1);
  672. WeakVH &OldV = ValuePtrs[Idx];
  673. if (!OldV) {
  674. OldV = V;
  675. return;
  676. }
  677. // Handle constants and non-constants (e.g. instrs) differently for
  678. // efficiency.
  679. if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
  680. ResolveConstants.push_back(std::make_pair(PHC, Idx));
  681. OldV = V;
  682. } else {
  683. // If there was a forward reference to this value, replace it.
  684. Value *PrevVal = OldV;
  685. OldV->replaceAllUsesWith(V);
  686. delete PrevVal;
  687. }
  688. }
  689. Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
  690. Type *Ty) {
  691. if (Idx >= size())
  692. resize(Idx + 1);
  693. if (Value *V = ValuePtrs[Idx]) {
  694. if (Ty != V->getType())
  695. report_fatal_error("Type mismatch in constant table!");
  696. return cast<Constant>(V);
  697. }
  698. // Create and return a placeholder, which will later be RAUW'd.
  699. Constant *C = new ConstantPlaceHolder(Ty, Context);
  700. ValuePtrs[Idx] = C;
  701. return C;
  702. }
  703. Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
  704. // Bail out for a clearly invalid value. This would make us call resize(0)
  705. if (Idx == UINT_MAX)
  706. return nullptr;
  707. if (Idx >= size())
  708. resize(Idx + 1);
  709. if (Value *V = ValuePtrs[Idx]) {
  710. // If the types don't match, it's invalid.
  711. if (Ty && Ty != V->getType())
  712. return nullptr;
  713. return V;
  714. }
  715. // No type specified, must be invalid reference.
  716. if (!Ty) return nullptr;
  717. // Create and return a placeholder, which will later be RAUW'd.
  718. Value *V = new Argument(Ty);
  719. ValuePtrs[Idx] = V;
  720. return V;
  721. }
  722. /// Once all constants are read, this method bulk resolves any forward
  723. /// references. The idea behind this is that we sometimes get constants (such
  724. /// as large arrays) which reference *many* forward ref constants. Replacing
  725. /// each of these causes a lot of thrashing when building/reuniquing the
  726. /// constant. Instead of doing this, we look at all the uses and rewrite all
  727. /// the place holders at once for any constant that uses a placeholder.
  728. void BitcodeReaderValueList::resolveConstantForwardRefs() {
  729. // Sort the values by-pointer so that they are efficient to look up with a
  730. // binary search.
  731. std::sort(ResolveConstants.begin(), ResolveConstants.end());
  732. SmallVector<Constant*, 64> NewOps;
  733. while (!ResolveConstants.empty()) {
  734. Value *RealVal = operator[](ResolveConstants.back().second);
  735. Constant *Placeholder = ResolveConstants.back().first;
  736. ResolveConstants.pop_back();
  737. // Loop over all users of the placeholder, updating them to reference the
  738. // new value. If they reference more than one placeholder, update them all
  739. // at once.
  740. while (!Placeholder->use_empty()) {
  741. auto UI = Placeholder->user_begin();
  742. User *U = *UI;
  743. // If the using object isn't uniqued, just update the operands. This
  744. // handles instructions and initializers for global variables.
  745. if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
  746. UI.getUse().set(RealVal);
  747. continue;
  748. }
  749. // Otherwise, we have a constant that uses the placeholder. Replace that
  750. // constant with a new constant that has *all* placeholder uses updated.
  751. Constant *UserC = cast<Constant>(U);
  752. for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
  753. I != E; ++I) {
  754. Value *NewOp;
  755. if (!isa<ConstantPlaceHolder>(*I)) {
  756. // Not a placeholder reference.
  757. NewOp = *I;
  758. } else if (*I == Placeholder) {
  759. // Common case is that it just references this one placeholder.
  760. NewOp = RealVal;
  761. } else {
  762. // Otherwise, look up the placeholder in ResolveConstants.
  763. ResolveConstantsTy::iterator It =
  764. std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
  765. std::pair<Constant*, unsigned>(cast<Constant>(*I),
  766. 0));
  767. assert(It != ResolveConstants.end() && It->first == *I);
  768. NewOp = operator[](It->second);
  769. }
  770. NewOps.push_back(cast<Constant>(NewOp));
  771. }
  772. // Make the new constant.
  773. Constant *NewC;
  774. if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
  775. NewC = ConstantArray::get(UserCA->getType(), NewOps);
  776. } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
  777. NewC = ConstantStruct::get(UserCS->getType(), NewOps);
  778. } else if (isa<ConstantVector>(UserC)) {
  779. NewC = ConstantVector::get(NewOps);
  780. } else {
  781. assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
  782. NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
  783. }
  784. UserC->replaceAllUsesWith(NewC);
  785. UserC->destroyConstant();
  786. NewOps.clear();
  787. }
  788. // Update all ValueHandles, they should be the only users at this point.
  789. Placeholder->replaceAllUsesWith(RealVal);
  790. delete Placeholder;
  791. }
  792. }
  793. void BitcodeReaderMDValueList::assignValue(Metadata *MD, unsigned Idx) {
  794. if (Idx == size()) {
  795. push_back(MD);
  796. return;
  797. }
  798. if (Idx >= size())
  799. resize(Idx+1);
  800. TrackingMDRef &OldMD = MDValuePtrs[Idx];
  801. if (!OldMD) {
  802. OldMD.reset(MD);
  803. return;
  804. }
  805. // If there was a forward reference to this value, replace it.
  806. TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
  807. PrevMD->replaceAllUsesWith(MD);
  808. --NumFwdRefs;
  809. }
  810. Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
  811. if (Idx >= size())
  812. resize(Idx + 1);
  813. if (Metadata *MD = MDValuePtrs[Idx])
  814. return MD;
  815. // Track forward refs to be resolved later.
  816. if (AnyFwdRefs) {
  817. MinFwdRef = std::min(MinFwdRef, Idx);
  818. MaxFwdRef = std::max(MaxFwdRef, Idx);
  819. } else {
  820. AnyFwdRefs = true;
  821. MinFwdRef = MaxFwdRef = Idx;
  822. }
  823. ++NumFwdRefs;
  824. // Create and return a placeholder, which will later be RAUW'd.
  825. Metadata *MD = MDNode::getTemporary(Context, None).release();
  826. MDValuePtrs[Idx].reset(MD);
  827. return MD;
  828. }
  829. void BitcodeReaderMDValueList::tryToResolveCycles() {
  830. if (!AnyFwdRefs)
  831. // Nothing to do.
  832. return;
  833. if (NumFwdRefs)
  834. // Still forward references... can't resolve cycles.
  835. return;
  836. // Resolve any cycles.
  837. for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
  838. auto &MD = MDValuePtrs[I];
  839. auto *N = dyn_cast_or_null<MDNode>(MD);
  840. if (!N)
  841. continue;
  842. assert(!N->isTemporary() && "Unexpected forward reference");
  843. N->resolveCycles();
  844. }
  845. // Make sure we return early again until there's another forward ref.
  846. AnyFwdRefs = false;
  847. }
  848. Type *BitcodeReader::getTypeByID(unsigned ID) {
  849. // The type table size is always specified correctly.
  850. if (ID >= TypeList.size())
  851. return nullptr;
  852. if (Type *Ty = TypeList[ID])
  853. return Ty;
  854. // If we have a forward reference, the only possible case is when it is to a
  855. // named struct. Just create a placeholder for now.
  856. return TypeList[ID] = createIdentifiedStructType(Context);
  857. }
  858. StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
  859. StringRef Name) {
  860. auto *Ret = StructType::create(Context, Name);
  861. IdentifiedStructTypes.push_back(Ret);
  862. return Ret;
  863. }
  864. StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
  865. auto *Ret = StructType::create(Context);
  866. IdentifiedStructTypes.push_back(Ret);
  867. return Ret;
  868. }
  869. //===----------------------------------------------------------------------===//
  870. // Functions for parsing blocks from the bitcode file
  871. //===----------------------------------------------------------------------===//
  872. /// \brief This fills an AttrBuilder object with the LLVM attributes that have
  873. /// been decoded from the given integer. This function must stay in sync with
  874. /// 'encodeLLVMAttributesForBitcode'.
  875. static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
  876. uint64_t EncodedAttrs) {
  877. // FIXME: Remove in 4.0.
  878. // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
  879. // the bits above 31 down by 11 bits.
  880. unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
  881. assert((!Alignment || isPowerOf2_32(Alignment)) &&
  882. "Alignment must be a power of two.");
  883. if (Alignment)
  884. B.addAlignmentAttr(Alignment);
  885. B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
  886. (EncodedAttrs & 0xffff));
  887. }
  888. std::error_code BitcodeReader::parseAttributeBlock() {
  889. if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
  890. return error("Invalid record");
  891. if (!MAttributes.empty())
  892. return error("Invalid multiple blocks");
  893. SmallVector<uint64_t, 64> Record;
  894. SmallVector<AttributeSet, 8> Attrs;
  895. // Read all the records.
  896. while (1) {
  897. // HLSL Change Starts - count skipped blocks
  898. unsigned skipCount = 0;
  899. BitstreamEntry Entry = Stream.advanceSkippingSubblocks(0, &skipCount);
  900. if (skipCount) ReportWarning(DiagnosticHandler, "Unrecognized subblock");
  901. // HLSL Change End
  902. switch (Entry.Kind) {
  903. case BitstreamEntry::SubBlock: // Handled for us already.
  904. case BitstreamEntry::Error:
  905. return error("Malformed block");
  906. case BitstreamEntry::EndBlock:
  907. return std::error_code();
  908. case BitstreamEntry::Record:
  909. // The interesting case.
  910. break;
  911. }
  912. // Read a record.
  913. Record.clear();
  914. switch (Stream.readRecord(Entry.ID, Record)) {
  915. default: // Default behavior: ignore.
  916. break;
  917. case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
  918. // FIXME: Remove in 4.0.
  919. if (Record.size() & 1)
  920. return error("Invalid record");
  921. for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
  922. AttrBuilder B;
  923. decodeLLVMAttributesForBitcode(B, Record[i+1]);
  924. Attrs.push_back(AttributeSet::get(Context, Record[i], B));
  925. }
  926. MAttributes.push_back(AttributeSet::get(Context, Attrs));
  927. Attrs.clear();
  928. break;
  929. }
  930. case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
  931. for (unsigned i = 0, e = Record.size(); i != e; ++i)
  932. Attrs.push_back(MAttributeGroups[Record[i]]);
  933. MAttributes.push_back(AttributeSet::get(Context, Attrs));
  934. Attrs.clear();
  935. break;
  936. }
  937. }
  938. }
  939. }
  940. // Returns Attribute::None on unrecognized codes.
  941. static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
  942. switch (Code) {
  943. default:
  944. return Attribute::None;
  945. case bitc::ATTR_KIND_ALIGNMENT:
  946. return Attribute::Alignment;
  947. case bitc::ATTR_KIND_ALWAYS_INLINE:
  948. return Attribute::AlwaysInline;
  949. case bitc::ATTR_KIND_ARGMEMONLY:
  950. return Attribute::ArgMemOnly;
  951. case bitc::ATTR_KIND_BUILTIN:
  952. return Attribute::Builtin;
  953. case bitc::ATTR_KIND_BY_VAL:
  954. return Attribute::ByVal;
  955. case bitc::ATTR_KIND_IN_ALLOCA:
  956. return Attribute::InAlloca;
  957. case bitc::ATTR_KIND_COLD:
  958. return Attribute::Cold;
  959. case bitc::ATTR_KIND_CONVERGENT:
  960. return Attribute::Convergent;
  961. case bitc::ATTR_KIND_INLINE_HINT:
  962. return Attribute::InlineHint;
  963. case bitc::ATTR_KIND_IN_REG:
  964. return Attribute::InReg;
  965. case bitc::ATTR_KIND_JUMP_TABLE:
  966. return Attribute::JumpTable;
  967. case bitc::ATTR_KIND_MIN_SIZE:
  968. return Attribute::MinSize;
  969. case bitc::ATTR_KIND_NAKED:
  970. return Attribute::Naked;
  971. case bitc::ATTR_KIND_NEST:
  972. return Attribute::Nest;
  973. case bitc::ATTR_KIND_NO_ALIAS:
  974. return Attribute::NoAlias;
  975. case bitc::ATTR_KIND_NO_BUILTIN:
  976. return Attribute::NoBuiltin;
  977. case bitc::ATTR_KIND_NO_CAPTURE:
  978. return Attribute::NoCapture;
  979. case bitc::ATTR_KIND_NO_DUPLICATE:
  980. return Attribute::NoDuplicate;
  981. case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
  982. return Attribute::NoImplicitFloat;
  983. case bitc::ATTR_KIND_NO_INLINE:
  984. return Attribute::NoInline;
  985. case bitc::ATTR_KIND_NON_LAZY_BIND:
  986. return Attribute::NonLazyBind;
  987. case bitc::ATTR_KIND_NON_NULL:
  988. return Attribute::NonNull;
  989. case bitc::ATTR_KIND_DEREFERENCEABLE:
  990. return Attribute::Dereferenceable;
  991. case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
  992. return Attribute::DereferenceableOrNull;
  993. case bitc::ATTR_KIND_NO_RED_ZONE:
  994. return Attribute::NoRedZone;
  995. case bitc::ATTR_KIND_NO_RETURN:
  996. return Attribute::NoReturn;
  997. case bitc::ATTR_KIND_NO_UNWIND:
  998. return Attribute::NoUnwind;
  999. case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
  1000. return Attribute::OptimizeForSize;
  1001. case bitc::ATTR_KIND_OPTIMIZE_NONE:
  1002. return Attribute::OptimizeNone;
  1003. case bitc::ATTR_KIND_READ_NONE:
  1004. return Attribute::ReadNone;
  1005. case bitc::ATTR_KIND_READ_ONLY:
  1006. return Attribute::ReadOnly;
  1007. case bitc::ATTR_KIND_RETURNED:
  1008. return Attribute::Returned;
  1009. case bitc::ATTR_KIND_RETURNS_TWICE:
  1010. return Attribute::ReturnsTwice;
  1011. case bitc::ATTR_KIND_S_EXT:
  1012. return Attribute::SExt;
  1013. case bitc::ATTR_KIND_STACK_ALIGNMENT:
  1014. return Attribute::StackAlignment;
  1015. case bitc::ATTR_KIND_STACK_PROTECT:
  1016. return Attribute::StackProtect;
  1017. case bitc::ATTR_KIND_STACK_PROTECT_REQ:
  1018. return Attribute::StackProtectReq;
  1019. case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
  1020. return Attribute::StackProtectStrong;
  1021. case bitc::ATTR_KIND_SAFESTACK:
  1022. return Attribute::SafeStack;
  1023. case bitc::ATTR_KIND_STRUCT_RET:
  1024. return Attribute::StructRet;
  1025. case bitc::ATTR_KIND_SANITIZE_ADDRESS:
  1026. return Attribute::SanitizeAddress;
  1027. case bitc::ATTR_KIND_SANITIZE_THREAD:
  1028. return Attribute::SanitizeThread;
  1029. case bitc::ATTR_KIND_SANITIZE_MEMORY:
  1030. return Attribute::SanitizeMemory;
  1031. case bitc::ATTR_KIND_UW_TABLE:
  1032. return Attribute::UWTable;
  1033. case bitc::ATTR_KIND_Z_EXT:
  1034. return Attribute::ZExt;
  1035. }
  1036. }
  1037. std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
  1038. unsigned &Alignment) {
  1039. // Note: Alignment in bitcode files is incremented by 1, so that zero
  1040. // can be used for default alignment.
  1041. if (Exponent > Value::MaxAlignmentExponent + 1)
  1042. return error("Invalid alignment value");
  1043. Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
  1044. return std::error_code();
  1045. }
  1046. std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
  1047. Attribute::AttrKind *Kind) {
  1048. *Kind = getAttrFromCode(Code);
  1049. if (*Kind == Attribute::None)
  1050. return error(BitcodeError::CorruptedBitcode,
  1051. "Unknown attribute kind (" + Twine(Code) + ")");
  1052. return std::error_code();
  1053. }
  1054. std::error_code BitcodeReader::parseAttributeGroupBlock() {
  1055. if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
  1056. return error("Invalid record");
  1057. if (!MAttributeGroups.empty())
  1058. return error("Invalid multiple blocks");
  1059. SmallVector<uint64_t, 64> Record;
  1060. // Read all the records.
  1061. while (1) {
  1062. // HLSL Change Starts - count skipped blocks
  1063. unsigned skipCount = 0;
  1064. BitstreamEntry Entry = Stream.advanceSkippingSubblocks(0, &skipCount);
  1065. if (skipCount) ReportWarning(DiagnosticHandler, "Unrecognized subblock");
  1066. // HLSL Change End
  1067. switch (Entry.Kind) {
  1068. case BitstreamEntry::SubBlock: // Handled for us already.
  1069. case BitstreamEntry::Error:
  1070. return error("Malformed block");
  1071. case BitstreamEntry::EndBlock:
  1072. return std::error_code();
  1073. case BitstreamEntry::Record:
  1074. // The interesting case.
  1075. break;
  1076. }
  1077. // Read a record.
  1078. Record.clear();
  1079. switch (Stream.readRecord(Entry.ID, Record)) {
  1080. default: // Default behavior: ignore.
  1081. break;
  1082. case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
  1083. if (Record.size() < 3)
  1084. return error("Invalid record");
  1085. uint64_t GrpID = Record[0];
  1086. uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
  1087. AttrBuilder B;
  1088. for (unsigned i = 2, e = Record.size(); i != e; ++i) {
  1089. if (Record[i] == 0) { // Enum attribute
  1090. Attribute::AttrKind Kind;
  1091. if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
  1092. return EC;
  1093. B.addAttribute(Kind);
  1094. } else if (Record[i] == 1) { // Integer attribute
  1095. Attribute::AttrKind Kind;
  1096. if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
  1097. return EC;
  1098. if (Kind == Attribute::Alignment)
  1099. B.addAlignmentAttr(Record[++i]);
  1100. else if (Kind == Attribute::StackAlignment)
  1101. B.addStackAlignmentAttr(Record[++i]);
  1102. else if (Kind == Attribute::Dereferenceable)
  1103. B.addDereferenceableAttr(Record[++i]);
  1104. else if (Kind == Attribute::DereferenceableOrNull)
  1105. B.addDereferenceableOrNullAttr(Record[++i]);
  1106. } else { // String attribute
  1107. assert((Record[i] == 3 || Record[i] == 4) &&
  1108. "Invalid attribute group entry");
  1109. bool HasValue = (Record[i++] == 4);
  1110. SmallString<64> KindStr;
  1111. SmallString<64> ValStr;
  1112. while (Record[i] != 0 && i != e)
  1113. KindStr += Record[i++];
  1114. assert(Record[i] == 0 && "Kind string not null terminated");
  1115. if (HasValue) {
  1116. // Has a value associated with it.
  1117. ++i; // Skip the '0' that terminates the "kind" string.
  1118. while (Record[i] != 0 && i != e)
  1119. ValStr += Record[i++];
  1120. assert(Record[i] == 0 && "Value string not null terminated");
  1121. }
  1122. B.addAttribute(KindStr.str(), ValStr.str());
  1123. }
  1124. }
  1125. MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
  1126. break;
  1127. }
  1128. }
  1129. }
  1130. }
  1131. std::error_code BitcodeReader::parseTypeTable() {
  1132. if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
  1133. return error("Invalid record");
  1134. return parseTypeTableBody();
  1135. }
  1136. std::error_code BitcodeReader::parseTypeTableBody() {
  1137. if (!TypeList.empty())
  1138. return error("Invalid multiple blocks");
  1139. SmallVector<uint64_t, 64> Record;
  1140. unsigned NumRecords = 0;
  1141. SmallString<64> TypeName;
  1142. // Read all the records for this type table.
  1143. while (1) {
  1144. // HLSL Change Starts - count skipped blocks
  1145. unsigned skipCount = 0;
  1146. BitstreamEntry Entry = Stream.advanceSkippingSubblocks(0, &skipCount);
  1147. if (skipCount) ReportWarning(DiagnosticHandler, "Unrecognized subblock");
  1148. // HLSL Change End
  1149. switch (Entry.Kind) {
  1150. case BitstreamEntry::SubBlock: // Handled for us already.
  1151. case BitstreamEntry::Error:
  1152. return error("Malformed block");
  1153. case BitstreamEntry::EndBlock:
  1154. if (NumRecords != TypeList.size())
  1155. return error("Malformed block");
  1156. return std::error_code();
  1157. case BitstreamEntry::Record:
  1158. // The interesting case.
  1159. break;
  1160. }
  1161. // Read a record.
  1162. Record.clear();
  1163. Type *ResultTy = nullptr;
  1164. switch (Stream.readRecord(Entry.ID, Record)) {
  1165. default:
  1166. return error("Invalid value");
  1167. case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
  1168. // TYPE_CODE_NUMENTRY contains a count of the number of types in the
  1169. // type list. This allows us to reserve space.
  1170. if (Record.size() < 1)
  1171. return error("Invalid record");
  1172. TypeList.resize(Record[0]);
  1173. continue;
  1174. case bitc::TYPE_CODE_VOID: // VOID
  1175. ResultTy = Type::getVoidTy(Context);
  1176. break;
  1177. case bitc::TYPE_CODE_HALF: // HALF
  1178. ResultTy = Type::getHalfTy(Context);
  1179. break;
  1180. case bitc::TYPE_CODE_FLOAT: // FLOAT
  1181. ResultTy = Type::getFloatTy(Context);
  1182. break;
  1183. case bitc::TYPE_CODE_DOUBLE: // DOUBLE
  1184. ResultTy = Type::getDoubleTy(Context);
  1185. break;
  1186. case bitc::TYPE_CODE_X86_FP80: // X86_FP80
  1187. ResultTy = Type::getX86_FP80Ty(Context);
  1188. break;
  1189. case bitc::TYPE_CODE_FP128: // FP128
  1190. ResultTy = Type::getFP128Ty(Context);
  1191. break;
  1192. case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
  1193. ResultTy = Type::getPPC_FP128Ty(Context);
  1194. break;
  1195. case bitc::TYPE_CODE_LABEL: // LABEL
  1196. ResultTy = Type::getLabelTy(Context);
  1197. break;
  1198. case bitc::TYPE_CODE_METADATA: // METADATA
  1199. ResultTy = Type::getMetadataTy(Context);
  1200. break;
  1201. case bitc::TYPE_CODE_X86_MMX: // X86_MMX
  1202. ResultTy = Type::getX86_MMXTy(Context);
  1203. break;
  1204. case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
  1205. if (Record.size() < 1)
  1206. return error("Invalid record");
  1207. uint64_t NumBits = Record[0];
  1208. if (NumBits < IntegerType::MIN_INT_BITS ||
  1209. NumBits > IntegerType::MAX_INT_BITS)
  1210. return error("Bitwidth for integer type out of range");
  1211. ResultTy = IntegerType::get(Context, NumBits);
  1212. break;
  1213. }
  1214. case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
  1215. // [pointee type, address space]
  1216. if (Record.size() < 1)
  1217. return error("Invalid record");
  1218. unsigned AddressSpace = 0;
  1219. if (Record.size() == 2)
  1220. AddressSpace = Record[1];
  1221. ResultTy = getTypeByID(Record[0]);
  1222. if (!ResultTy ||
  1223. !PointerType::isValidElementType(ResultTy))
  1224. return error("Invalid type");
  1225. ResultTy = PointerType::get(ResultTy, AddressSpace);
  1226. break;
  1227. }
  1228. case bitc::TYPE_CODE_FUNCTION_OLD: {
  1229. // FIXME: attrid is dead, remove it in LLVM 4.0
  1230. // FUNCTION: [vararg, attrid, retty, paramty x N]
  1231. if (Record.size() < 3)
  1232. return error("Invalid record");
  1233. SmallVector<Type*, 8> ArgTys;
  1234. for (unsigned i = 3, e = Record.size(); i != e; ++i) {
  1235. if (Type *T = getTypeByID(Record[i]))
  1236. ArgTys.push_back(T);
  1237. else
  1238. break;
  1239. }
  1240. ResultTy = getTypeByID(Record[2]);
  1241. if (!ResultTy || ArgTys.size() < Record.size()-3)
  1242. return error("Invalid type");
  1243. ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
  1244. break;
  1245. }
  1246. case bitc::TYPE_CODE_FUNCTION: {
  1247. // FUNCTION: [vararg, retty, paramty x N]
  1248. if (Record.size() < 2)
  1249. return error("Invalid record");
  1250. SmallVector<Type*, 8> ArgTys;
  1251. for (unsigned i = 2, e = Record.size(); i != e; ++i) {
  1252. if (Type *T = getTypeByID(Record[i])) {
  1253. if (!FunctionType::isValidArgumentType(T))
  1254. return error("Invalid function argument type");
  1255. ArgTys.push_back(T);
  1256. }
  1257. else
  1258. break;
  1259. }
  1260. ResultTy = getTypeByID(Record[1]);
  1261. if (!ResultTy || ArgTys.size() < Record.size()-2)
  1262. return error("Invalid type");
  1263. ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
  1264. break;
  1265. }
  1266. case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
  1267. if (Record.size() < 1)
  1268. return error("Invalid record");
  1269. SmallVector<Type*, 8> EltTys;
  1270. for (unsigned i = 1, e = Record.size(); i != e; ++i) {
  1271. if (Type *T = getTypeByID(Record[i]))
  1272. EltTys.push_back(T);
  1273. else
  1274. break;
  1275. }
  1276. if (EltTys.size() != Record.size()-1)
  1277. return error("Invalid type");
  1278. ResultTy = StructType::get(Context, EltTys, Record[0]);
  1279. break;
  1280. }
  1281. case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
  1282. if (convertToString(Record, 0, TypeName))
  1283. return error("Invalid record");
  1284. continue;
  1285. case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
  1286. if (Record.size() < 1)
  1287. return error("Invalid record");
  1288. if (NumRecords >= TypeList.size())
  1289. return error("Invalid TYPE table");
  1290. // Check to see if this was forward referenced, if so fill in the temp.
  1291. StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
  1292. if (Res) {
  1293. Res->setName(TypeName);
  1294. TypeList[NumRecords] = nullptr;
  1295. } else // Otherwise, create a new struct.
  1296. Res = createIdentifiedStructType(Context, TypeName);
  1297. // HLSL Change Begin - avoid name collision for dxil types.
  1298. bool bNameCollision = Res->getName().size() > TypeName.size();
  1299. // HLSL Change End.
  1300. TypeName.clear();
  1301. SmallVector<Type*, 8> EltTys;
  1302. for (unsigned i = 1, e = Record.size(); i != e; ++i) {
  1303. if (Type *T = getTypeByID(Record[i]))
  1304. EltTys.push_back(T);
  1305. else
  1306. break;
  1307. }
  1308. if (EltTys.size() != Record.size()-1)
  1309. return error("Invalid record");
  1310. Res->setBody(EltTys, Record[0]);
  1311. // HLSL Change Begin - avoid name collision for dxil types.
  1312. if (bNameCollision) {
  1313. if (hlsl::OP::IsDupDxilOpType(Res)) {
  1314. Res = hlsl::OP::GetOriginalDxilOpType(Res, *TheModule);
  1315. }
  1316. }
  1317. // HLSL Change End.
  1318. ResultTy = Res;
  1319. break;
  1320. }
  1321. case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
  1322. if (Record.size() != 1)
  1323. return error("Invalid record");
  1324. if (NumRecords >= TypeList.size())
  1325. return error("Invalid TYPE table");
  1326. // Check to see if this was forward referenced, if so fill in the temp.
  1327. StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
  1328. if (Res) {
  1329. Res->setName(TypeName);
  1330. TypeList[NumRecords] = nullptr;
  1331. } else // Otherwise, create a new struct with no body.
  1332. Res = createIdentifiedStructType(Context, TypeName);
  1333. TypeName.clear();
  1334. ResultTy = Res;
  1335. break;
  1336. }
  1337. case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
  1338. if (Record.size() < 2)
  1339. return error("Invalid record");
  1340. ResultTy = getTypeByID(Record[1]);
  1341. if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
  1342. return error("Invalid type");
  1343. ResultTy = ArrayType::get(ResultTy, Record[0]);
  1344. break;
  1345. case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
  1346. if (Record.size() < 2)
  1347. return error("Invalid record");
  1348. if (Record[0] == 0)
  1349. return error("Invalid vector length");
  1350. ResultTy = getTypeByID(Record[1]);
  1351. if (!ResultTy || !StructType::isValidElementType(ResultTy))
  1352. return error("Invalid type");
  1353. ResultTy = VectorType::get(ResultTy, Record[0]);
  1354. break;
  1355. }
  1356. if (NumRecords >= TypeList.size())
  1357. return error("Invalid TYPE table");
  1358. if (TypeList[NumRecords])
  1359. return error(
  1360. "Invalid TYPE table: Only named structs can be forward referenced");
  1361. assert(ResultTy && "Didn't read a type?");
  1362. TypeList[NumRecords++] = ResultTy;
  1363. }
  1364. }
  1365. std::error_code BitcodeReader::parseValueSymbolTable() {
  1366. if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
  1367. return error("Invalid record");
  1368. SmallVector<uint64_t, 64> Record;
  1369. Triple TT(TheModule->getTargetTriple());
  1370. // Read all the records for this value table.
  1371. SmallString<128> ValueName;
  1372. while (1) {
  1373. // HLSL Change Starts - count skipped blocks
  1374. unsigned skipCount = 0;
  1375. BitstreamEntry Entry = Stream.advanceSkippingSubblocks(0, &skipCount);
  1376. if (skipCount) ReportWarning(DiagnosticHandler, "Unrecognized subblock");
  1377. // HLSL Change End
  1378. switch (Entry.Kind) {
  1379. case BitstreamEntry::SubBlock: // Handled for us already.
  1380. case BitstreamEntry::Error:
  1381. return error("Malformed block");
  1382. case BitstreamEntry::EndBlock:
  1383. return std::error_code();
  1384. case BitstreamEntry::Record:
  1385. // The interesting case.
  1386. break;
  1387. }
  1388. // Read a record.
  1389. Record.clear();
  1390. switch (Stream.readRecord(Entry.ID, Record)) {
  1391. default: // Default behavior: unknown type.
  1392. break;
  1393. case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
  1394. if (convertToString(Record, 1, ValueName))
  1395. return error("Invalid record");
  1396. unsigned ValueID = Record[0];
  1397. if (ValueID >= ValueList.size() || !ValueList[ValueID])
  1398. return error("Invalid record");
  1399. Value *V = ValueList[ValueID];
  1400. V->setName(StringRef(ValueName.data(), ValueName.size()));
  1401. if (auto *GO = dyn_cast<GlobalObject>(V)) {
  1402. if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
  1403. if (TT.isOSBinFormatMachO())
  1404. GO->setComdat(nullptr);
  1405. else
  1406. GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
  1407. }
  1408. }
  1409. ValueName.clear();
  1410. break;
  1411. }
  1412. case bitc::VST_CODE_BBENTRY: {
  1413. if (convertToString(Record, 1, ValueName))
  1414. return error("Invalid record");
  1415. BasicBlock *BB = getBasicBlock(Record[0]);
  1416. if (!BB)
  1417. return error("Invalid record");
  1418. BB->setName(StringRef(ValueName.data(), ValueName.size()));
  1419. ValueName.clear();
  1420. break;
  1421. }
  1422. }
  1423. }
  1424. }
  1425. static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
  1426. std::error_code BitcodeReader::parseMetadata() {
  1427. IsMetadataMaterialized = true;
  1428. unsigned NextMDValueNo = MDValueList.size();
  1429. if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
  1430. return error("Invalid record");
  1431. SmallVector<uint64_t, 64> Record;
  1432. auto getMD =
  1433. [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
  1434. auto getMDOrNull = [&](unsigned ID) -> Metadata *{
  1435. if (ID)
  1436. return getMD(ID - 1);
  1437. return nullptr;
  1438. };
  1439. auto getMDString = [&](unsigned ID) -> MDString *{
  1440. // This requires that the ID is not really a forward reference. In
  1441. // particular, the MDString must already have been resolved.
  1442. return cast_or_null<MDString>(getMDOrNull(ID));
  1443. };
  1444. #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
  1445. (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
  1446. // Read all the records.
  1447. while (1) {
  1448. // HLSL Change Starts - count skipped blocks
  1449. unsigned skipCount = 0;
  1450. BitstreamEntry Entry = Stream.advanceSkippingSubblocks(0, &skipCount);
  1451. if (skipCount) ReportWarning(DiagnosticHandler, "Unrecognized subblock");
  1452. // HLSL Change End
  1453. switch (Entry.Kind) {
  1454. case BitstreamEntry::SubBlock: // Handled for us already.
  1455. case BitstreamEntry::Error:
  1456. return error("Malformed block");
  1457. case BitstreamEntry::EndBlock:
  1458. MDValueList.tryToResolveCycles();
  1459. return std::error_code();
  1460. case BitstreamEntry::Record:
  1461. // The interesting case.
  1462. break;
  1463. }
  1464. // Read a record.
  1465. Record.clear();
  1466. unsigned Code = Stream.readRecord(Entry.ID, Record);
  1467. bool IsDistinct = false;
  1468. switch (Code) {
  1469. default: // Default behavior: ignore.
  1470. break;
  1471. case bitc::METADATA_NAME: {
  1472. // Read name of the named metadata.
  1473. SmallString<8> Name(Record.begin(), Record.end());
  1474. Record.clear();
  1475. Code = Stream.ReadCode();
  1476. unsigned NextBitCode = Stream.readRecord(Code, Record);
  1477. if (NextBitCode != bitc::METADATA_NAMED_NODE)
  1478. return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
  1479. // Read named metadata elements.
  1480. unsigned Size = Record.size();
  1481. NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
  1482. for (unsigned i = 0; i != Size; ++i) {
  1483. MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
  1484. if (!MD)
  1485. return error("Invalid record");
  1486. NMD->addOperand(MD);
  1487. }
  1488. break;
  1489. }
  1490. case bitc::METADATA_OLD_FN_NODE: {
  1491. // FIXME: Remove in 4.0.
  1492. // This is a LocalAsMetadata record, the only type of function-local
  1493. // metadata.
  1494. if (Record.size() % 2 == 1)
  1495. return error("Invalid record");
  1496. // If this isn't a LocalAsMetadata record, we're dropping it. This used
  1497. // to be legal, but there's no upgrade path.
  1498. auto dropRecord = [&] {
  1499. MDValueList.assignValue(MDNode::get(Context, None), NextMDValueNo++);
  1500. };
  1501. if (Record.size() != 2) {
  1502. dropRecord();
  1503. break;
  1504. }
  1505. Type *Ty = getTypeByID(Record[0]);
  1506. if (Ty->isMetadataTy() || Ty->isVoidTy()) {
  1507. dropRecord();
  1508. break;
  1509. }
  1510. MDValueList.assignValue(
  1511. LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
  1512. NextMDValueNo++);
  1513. break;
  1514. }
  1515. case bitc::METADATA_OLD_NODE: {
  1516. // FIXME: Remove in 4.0.
  1517. if (Record.size() % 2 == 1)
  1518. return error("Invalid record");
  1519. unsigned Size = Record.size();
  1520. SmallVector<Metadata *, 8> Elts;
  1521. for (unsigned i = 0; i != Size; i += 2) {
  1522. Type *Ty = getTypeByID(Record[i]);
  1523. if (!Ty)
  1524. return error("Invalid record");
  1525. if (Ty->isMetadataTy())
  1526. Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
  1527. else if (!Ty->isVoidTy()) {
  1528. auto *MD =
  1529. ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
  1530. assert(isa<ConstantAsMetadata>(MD) &&
  1531. "Expected non-function-local metadata");
  1532. Elts.push_back(MD);
  1533. } else
  1534. Elts.push_back(nullptr);
  1535. }
  1536. MDValueList.assignValue(MDNode::get(Context, Elts), NextMDValueNo++);
  1537. break;
  1538. }
  1539. case bitc::METADATA_VALUE: {
  1540. if (Record.size() != 2)
  1541. return error("Invalid record");
  1542. Type *Ty = getTypeByID(Record[0]);
  1543. if (Ty->isMetadataTy() || Ty->isVoidTy())
  1544. return error("Invalid record");
  1545. MDValueList.assignValue(
  1546. ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
  1547. NextMDValueNo++);
  1548. break;
  1549. }
  1550. case bitc::METADATA_DISTINCT_NODE:
  1551. IsDistinct = true;
  1552. // fallthrough...
  1553. case bitc::METADATA_NODE: {
  1554. SmallVector<Metadata *, 8> Elts;
  1555. Elts.reserve(Record.size());
  1556. for (unsigned ID : Record)
  1557. Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
  1558. MDValueList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
  1559. : MDNode::get(Context, Elts),
  1560. NextMDValueNo++);
  1561. break;
  1562. }
  1563. case bitc::METADATA_LOCATION: {
  1564. if (Record.size() != 5)
  1565. return error("Invalid record");
  1566. unsigned Line = Record[1];
  1567. unsigned Column = Record[2];
  1568. MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
  1569. Metadata *InlinedAt =
  1570. Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
  1571. MDValueList.assignValue(
  1572. GET_OR_DISTINCT(DILocation, Record[0],
  1573. (Context, Line, Column, Scope, InlinedAt)),
  1574. NextMDValueNo++);
  1575. break;
  1576. }
  1577. case bitc::METADATA_GENERIC_DEBUG: {
  1578. if (Record.size() < 4)
  1579. return error("Invalid record");
  1580. unsigned Tag = Record[1];
  1581. unsigned Version = Record[2];
  1582. if (Tag >= 1u << 16 || Version != 0)
  1583. return error("Invalid record");
  1584. auto *Header = getMDString(Record[3]);
  1585. SmallVector<Metadata *, 8> DwarfOps;
  1586. for (unsigned I = 4, E = Record.size(); I != E; ++I)
  1587. DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
  1588. : nullptr);
  1589. MDValueList.assignValue(GET_OR_DISTINCT(GenericDINode, Record[0],
  1590. (Context, Tag, Header, DwarfOps)),
  1591. NextMDValueNo++);
  1592. break;
  1593. }
  1594. case bitc::METADATA_SUBRANGE: {
  1595. if (Record.size() != 3)
  1596. return error("Invalid record");
  1597. MDValueList.assignValue(
  1598. GET_OR_DISTINCT(DISubrange, Record[0],
  1599. (Context, Record[1], unrotateSign(Record[2]))),
  1600. NextMDValueNo++);
  1601. break;
  1602. }
  1603. case bitc::METADATA_ENUMERATOR: {
  1604. if (Record.size() != 3)
  1605. return error("Invalid record");
  1606. MDValueList.assignValue(GET_OR_DISTINCT(DIEnumerator, Record[0],
  1607. (Context, unrotateSign(Record[1]),
  1608. getMDString(Record[2]))),
  1609. NextMDValueNo++);
  1610. break;
  1611. }
  1612. case bitc::METADATA_BASIC_TYPE: {
  1613. if (Record.size() != 6)
  1614. return error("Invalid record");
  1615. MDValueList.assignValue(
  1616. GET_OR_DISTINCT(DIBasicType, Record[0],
  1617. (Context, Record[1], getMDString(Record[2]),
  1618. Record[3], Record[4], Record[5])),
  1619. NextMDValueNo++);
  1620. break;
  1621. }
  1622. case bitc::METADATA_DERIVED_TYPE: {
  1623. if (Record.size() != 12)
  1624. return error("Invalid record");
  1625. MDValueList.assignValue(
  1626. GET_OR_DISTINCT(DIDerivedType, Record[0],
  1627. (Context, Record[1], getMDString(Record[2]),
  1628. getMDOrNull(Record[3]), Record[4],
  1629. getMDOrNull(Record[5]), getMDOrNull(Record[6]),
  1630. Record[7], Record[8], Record[9], Record[10],
  1631. getMDOrNull(Record[11]))),
  1632. NextMDValueNo++);
  1633. break;
  1634. }
  1635. case bitc::METADATA_COMPOSITE_TYPE: {
  1636. if (Record.size() != 16)
  1637. return error("Invalid record");
  1638. MDValueList.assignValue(
  1639. GET_OR_DISTINCT(DICompositeType, Record[0],
  1640. (Context, Record[1], getMDString(Record[2]),
  1641. getMDOrNull(Record[3]), Record[4],
  1642. getMDOrNull(Record[5]), getMDOrNull(Record[6]),
  1643. Record[7], Record[8], Record[9], Record[10],
  1644. getMDOrNull(Record[11]), Record[12],
  1645. getMDOrNull(Record[13]), getMDOrNull(Record[14]),
  1646. getMDString(Record[15]))),
  1647. NextMDValueNo++);
  1648. break;
  1649. }
  1650. case bitc::METADATA_SUBROUTINE_TYPE: {
  1651. if (Record.size() != 3)
  1652. return error("Invalid record");
  1653. MDValueList.assignValue(
  1654. GET_OR_DISTINCT(DISubroutineType, Record[0],
  1655. (Context, Record[1], getMDOrNull(Record[2]))),
  1656. NextMDValueNo++);
  1657. break;
  1658. }
  1659. case bitc::METADATA_MODULE: {
  1660. if (Record.size() != 6)
  1661. return error("Invalid record");
  1662. MDValueList.assignValue(
  1663. GET_OR_DISTINCT(DIModule, Record[0],
  1664. (Context, getMDOrNull(Record[1]),
  1665. getMDString(Record[2]), getMDString(Record[3]),
  1666. getMDString(Record[4]), getMDString(Record[5]))),
  1667. NextMDValueNo++);
  1668. break;
  1669. }
  1670. case bitc::METADATA_FILE: {
  1671. if (Record.size() != 3)
  1672. return error("Invalid record");
  1673. MDValueList.assignValue(
  1674. GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
  1675. getMDString(Record[2]))),
  1676. NextMDValueNo++);
  1677. break;
  1678. }
  1679. case bitc::METADATA_COMPILE_UNIT: {
  1680. if (Record.size() < 14 || Record.size() > 15)
  1681. return error("Invalid record");
  1682. MDValueList.assignValue(
  1683. GET_OR_DISTINCT(
  1684. DICompileUnit, Record[0],
  1685. (Context, Record[1], getMDOrNull(Record[2]),
  1686. getMDString(Record[3]), Record[4], getMDString(Record[5]),
  1687. Record[6], getMDString(Record[7]), Record[8],
  1688. getMDOrNull(Record[9]), getMDOrNull(Record[10]),
  1689. getMDOrNull(Record[11]), getMDOrNull(Record[12]),
  1690. getMDOrNull(Record[13]), Record.size() == 14 ? 0 : Record[14])),
  1691. NextMDValueNo++);
  1692. break;
  1693. }
  1694. case bitc::METADATA_SUBPROGRAM: {
  1695. if (Record.size() != 19)
  1696. return error("Invalid record");
  1697. MDValueList.assignValue(
  1698. GET_OR_DISTINCT(
  1699. DISubprogram, Record[0],
  1700. (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
  1701. getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
  1702. getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
  1703. getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
  1704. Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
  1705. getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
  1706. NextMDValueNo++);
  1707. break;
  1708. }
  1709. case bitc::METADATA_LEXICAL_BLOCK: {
  1710. if (Record.size() != 5)
  1711. return error("Invalid record");
  1712. MDValueList.assignValue(
  1713. GET_OR_DISTINCT(DILexicalBlock, Record[0],
  1714. (Context, getMDOrNull(Record[1]),
  1715. getMDOrNull(Record[2]), Record[3], Record[4])),
  1716. NextMDValueNo++);
  1717. break;
  1718. }
  1719. case bitc::METADATA_LEXICAL_BLOCK_FILE: {
  1720. if (Record.size() != 4)
  1721. return error("Invalid record");
  1722. MDValueList.assignValue(
  1723. GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
  1724. (Context, getMDOrNull(Record[1]),
  1725. getMDOrNull(Record[2]), Record[3])),
  1726. NextMDValueNo++);
  1727. break;
  1728. }
  1729. case bitc::METADATA_NAMESPACE: {
  1730. if (Record.size() != 5)
  1731. return error("Invalid record");
  1732. MDValueList.assignValue(
  1733. GET_OR_DISTINCT(DINamespace, Record[0],
  1734. (Context, getMDOrNull(Record[1]),
  1735. getMDOrNull(Record[2]), getMDString(Record[3]),
  1736. Record[4])),
  1737. NextMDValueNo++);
  1738. break;
  1739. }
  1740. case bitc::METADATA_TEMPLATE_TYPE: {
  1741. if (Record.size() != 3)
  1742. return error("Invalid record");
  1743. MDValueList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
  1744. Record[0],
  1745. (Context, getMDString(Record[1]),
  1746. getMDOrNull(Record[2]))),
  1747. NextMDValueNo++);
  1748. break;
  1749. }
  1750. case bitc::METADATA_TEMPLATE_VALUE: {
  1751. if (Record.size() != 5)
  1752. return error("Invalid record");
  1753. MDValueList.assignValue(
  1754. GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
  1755. (Context, Record[1], getMDString(Record[2]),
  1756. getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
  1757. NextMDValueNo++);
  1758. break;
  1759. }
  1760. case bitc::METADATA_GLOBAL_VAR: {
  1761. if (Record.size() != 11)
  1762. return error("Invalid record");
  1763. MDValueList.assignValue(
  1764. GET_OR_DISTINCT(DIGlobalVariable, Record[0],
  1765. (Context, getMDOrNull(Record[1]),
  1766. getMDString(Record[2]), getMDString(Record[3]),
  1767. getMDOrNull(Record[4]), Record[5],
  1768. getMDOrNull(Record[6]), Record[7], Record[8],
  1769. getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
  1770. NextMDValueNo++);
  1771. break;
  1772. }
  1773. case bitc::METADATA_LOCAL_VAR: {
  1774. // 10th field is for the obseleted 'inlinedAt:' field.
  1775. if (Record.size() != 9 && Record.size() != 10)
  1776. return error("Invalid record");
  1777. MDValueList.assignValue(
  1778. GET_OR_DISTINCT(DILocalVariable, Record[0],
  1779. (Context, Record[1], getMDOrNull(Record[2]),
  1780. getMDString(Record[3]), getMDOrNull(Record[4]),
  1781. Record[5], getMDOrNull(Record[6]), Record[7],
  1782. Record[8])),
  1783. NextMDValueNo++);
  1784. break;
  1785. }
  1786. case bitc::METADATA_EXPRESSION: {
  1787. if (Record.size() < 1)
  1788. return error("Invalid record");
  1789. MDValueList.assignValue(
  1790. GET_OR_DISTINCT(DIExpression, Record[0],
  1791. (Context, makeArrayRef(Record).slice(1))),
  1792. NextMDValueNo++);
  1793. break;
  1794. }
  1795. case bitc::METADATA_OBJC_PROPERTY: {
  1796. if (Record.size() != 8)
  1797. return error("Invalid record");
  1798. MDValueList.assignValue(
  1799. GET_OR_DISTINCT(DIObjCProperty, Record[0],
  1800. (Context, getMDString(Record[1]),
  1801. getMDOrNull(Record[2]), Record[3],
  1802. getMDString(Record[4]), getMDString(Record[5]),
  1803. Record[6], getMDOrNull(Record[7]))),
  1804. NextMDValueNo++);
  1805. break;
  1806. }
  1807. case bitc::METADATA_IMPORTED_ENTITY: {
  1808. if (Record.size() != 6)
  1809. return error("Invalid record");
  1810. MDValueList.assignValue(
  1811. GET_OR_DISTINCT(DIImportedEntity, Record[0],
  1812. (Context, Record[1], getMDOrNull(Record[2]),
  1813. getMDOrNull(Record[3]), Record[4],
  1814. getMDString(Record[5]))),
  1815. NextMDValueNo++);
  1816. break;
  1817. }
  1818. case bitc::METADATA_STRING: {
  1819. std::string String(Record.begin(), Record.end());
  1820. llvm::UpgradeMDStringConstant(String);
  1821. Metadata *MD = MDString::get(Context, String);
  1822. MDValueList.assignValue(MD, NextMDValueNo++);
  1823. break;
  1824. }
  1825. case bitc::METADATA_KIND: {
  1826. if (Record.size() < 2)
  1827. return error("Invalid record");
  1828. unsigned Kind = Record[0];
  1829. SmallString<8> Name(Record.begin()+1, Record.end());
  1830. unsigned NewKind = TheModule->getMDKindID(Name.str());
  1831. if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
  1832. return error("Conflicting METADATA_KIND records");
  1833. break;
  1834. }
  1835. }
  1836. }
  1837. #undef GET_OR_DISTINCT
  1838. }
  1839. /// Decode a signed value stored with the sign bit in the LSB for dense VBR
  1840. /// encoding.
  1841. uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
  1842. if ((V & 1) == 0)
  1843. return V >> 1;
  1844. if (V != 1)
  1845. return -(V >> 1);
  1846. // There is no such thing as -0 with integers. "-0" really means MININT.
  1847. return 1ULL << 63;
  1848. }
  1849. /// Resolve all of the initializers for global values and aliases that we can.
  1850. std::error_code BitcodeReader::resolveGlobalAndAliasInits() {
  1851. std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
  1852. std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
  1853. std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
  1854. std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
  1855. std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
  1856. GlobalInitWorklist.swap(GlobalInits);
  1857. AliasInitWorklist.swap(AliasInits);
  1858. FunctionPrefixWorklist.swap(FunctionPrefixes);
  1859. FunctionPrologueWorklist.swap(FunctionPrologues);
  1860. FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
  1861. while (!GlobalInitWorklist.empty()) {
  1862. unsigned ValID = GlobalInitWorklist.back().second;
  1863. if (ValID >= ValueList.size()) {
  1864. // Not ready to resolve this yet, it requires something later in the file.
  1865. GlobalInits.push_back(GlobalInitWorklist.back());
  1866. } else {
  1867. if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
  1868. GlobalInitWorklist.back().first->setInitializer(C);
  1869. else
  1870. return error("Expected a constant");
  1871. }
  1872. GlobalInitWorklist.pop_back();
  1873. }
  1874. while (!AliasInitWorklist.empty()) {
  1875. unsigned ValID = AliasInitWorklist.back().second;
  1876. if (ValID >= ValueList.size()) {
  1877. AliasInits.push_back(AliasInitWorklist.back());
  1878. } else {
  1879. Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
  1880. if (!C)
  1881. return error("Expected a constant");
  1882. GlobalAlias *Alias = AliasInitWorklist.back().first;
  1883. if (C->getType() != Alias->getType())
  1884. return error("Alias and aliasee types don't match");
  1885. Alias->setAliasee(C);
  1886. }
  1887. AliasInitWorklist.pop_back();
  1888. }
  1889. while (!FunctionPrefixWorklist.empty()) {
  1890. unsigned ValID = FunctionPrefixWorklist.back().second;
  1891. if (ValID >= ValueList.size()) {
  1892. FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
  1893. } else {
  1894. if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
  1895. FunctionPrefixWorklist.back().first->setPrefixData(C);
  1896. else
  1897. return error("Expected a constant");
  1898. }
  1899. FunctionPrefixWorklist.pop_back();
  1900. }
  1901. while (!FunctionPrologueWorklist.empty()) {
  1902. unsigned ValID = FunctionPrologueWorklist.back().second;
  1903. if (ValID >= ValueList.size()) {
  1904. FunctionPrologues.push_back(FunctionPrologueWorklist.back());
  1905. } else {
  1906. if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
  1907. FunctionPrologueWorklist.back().first->setPrologueData(C);
  1908. else
  1909. return error("Expected a constant");
  1910. }
  1911. FunctionPrologueWorklist.pop_back();
  1912. }
  1913. while (!FunctionPersonalityFnWorklist.empty()) {
  1914. unsigned ValID = FunctionPersonalityFnWorklist.back().second;
  1915. if (ValID >= ValueList.size()) {
  1916. FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
  1917. } else {
  1918. if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
  1919. FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
  1920. else
  1921. return error("Expected a constant");
  1922. }
  1923. FunctionPersonalityFnWorklist.pop_back();
  1924. }
  1925. return std::error_code();
  1926. }
  1927. static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
  1928. SmallVector<uint64_t, 8> Words(Vals.size());
  1929. std::transform(Vals.begin(), Vals.end(), Words.begin(),
  1930. BitcodeReader::decodeSignRotatedValue);
  1931. return APInt(TypeBits, Words);
  1932. }
  1933. std::error_code BitcodeReader::parseConstants() {
  1934. if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
  1935. return error("Invalid record");
  1936. SmallVector<uint64_t, 64> Record;
  1937. // Read all the records for this value table.
  1938. Type *CurTy = Type::getInt32Ty(Context);
  1939. unsigned NextCstNo = ValueList.size();
  1940. while (1) {
  1941. // HLSL Change Starts - count skipped blocks
  1942. unsigned skipCount = 0;
  1943. BitstreamEntry Entry = Stream.advanceSkippingSubblocks(0, &skipCount);
  1944. if (skipCount) ReportWarning(DiagnosticHandler, "Unrecognized subblock");
  1945. // HLSL Change End
  1946. switch (Entry.Kind) {
  1947. case BitstreamEntry::SubBlock: // Handled for us already.
  1948. case BitstreamEntry::Error:
  1949. return error("Malformed block");
  1950. case BitstreamEntry::EndBlock:
  1951. if (NextCstNo != ValueList.size())
  1952. return error("Invalid ronstant reference");
  1953. // Once all the constants have been read, go through and resolve forward
  1954. // references.
  1955. ValueList.resolveConstantForwardRefs();
  1956. return std::error_code();
  1957. case BitstreamEntry::Record:
  1958. // The interesting case.
  1959. break;
  1960. }
  1961. // Read a record.
  1962. Record.clear();
  1963. Value *V = nullptr;
  1964. unsigned BitCode = Stream.readRecord(Entry.ID, Record);
  1965. switch (BitCode) {
  1966. default: // Default behavior: unknown constant
  1967. case bitc::CST_CODE_UNDEF: // UNDEF
  1968. V = UndefValue::get(CurTy);
  1969. break;
  1970. case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
  1971. if (Record.empty())
  1972. return error("Invalid record");
  1973. if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
  1974. return error("Invalid record");
  1975. CurTy = TypeList[Record[0]];
  1976. continue; // Skip the ValueList manipulation.
  1977. case bitc::CST_CODE_NULL: // NULL
  1978. V = Constant::getNullValue(CurTy);
  1979. break;
  1980. case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
  1981. if (!CurTy->isIntegerTy() || Record.empty())
  1982. return error("Invalid record");
  1983. V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
  1984. break;
  1985. case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
  1986. if (!CurTy->isIntegerTy() || Record.empty())
  1987. return error("Invalid record");
  1988. APInt VInt =
  1989. readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
  1990. V = ConstantInt::get(Context, VInt);
  1991. break;
  1992. }
  1993. case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
  1994. if (Record.empty())
  1995. return error("Invalid record");
  1996. if (CurTy->isHalfTy())
  1997. V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
  1998. APInt(16, (uint16_t)Record[0])));
  1999. else if (CurTy->isFloatTy())
  2000. V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
  2001. APInt(32, (uint32_t)Record[0])));
  2002. else if (CurTy->isDoubleTy())
  2003. V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
  2004. APInt(64, Record[0])));
  2005. else if (CurTy->isX86_FP80Ty()) {
  2006. // Bits are not stored the same way as a normal i80 APInt, compensate.
  2007. uint64_t Rearrange[2];
  2008. Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
  2009. Rearrange[1] = Record[0] >> 48;
  2010. V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
  2011. APInt(80, Rearrange)));
  2012. } else if (CurTy->isFP128Ty())
  2013. V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
  2014. APInt(128, Record)));
  2015. else if (CurTy->isPPC_FP128Ty())
  2016. V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
  2017. APInt(128, Record)));
  2018. else
  2019. V = UndefValue::get(CurTy);
  2020. break;
  2021. }
  2022. case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
  2023. if (Record.empty())
  2024. return error("Invalid record");
  2025. unsigned Size = Record.size();
  2026. SmallVector<Constant*, 16> Elts;
  2027. if (StructType *STy = dyn_cast<StructType>(CurTy)) {
  2028. for (unsigned i = 0; i != Size; ++i)
  2029. Elts.push_back(ValueList.getConstantFwdRef(Record[i],
  2030. STy->getElementType(i)));
  2031. V = ConstantStruct::get(STy, Elts);
  2032. } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
  2033. Type *EltTy = ATy->getElementType();
  2034. for (unsigned i = 0; i != Size; ++i)
  2035. Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
  2036. V = ConstantArray::get(ATy, Elts);
  2037. } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
  2038. Type *EltTy = VTy->getElementType();
  2039. for (unsigned i = 0; i != Size; ++i)
  2040. Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
  2041. V = ConstantVector::get(Elts);
  2042. } else {
  2043. V = UndefValue::get(CurTy);
  2044. }
  2045. break;
  2046. }
  2047. case bitc::CST_CODE_STRING: // STRING: [values]
  2048. case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
  2049. if (Record.empty())
  2050. return error("Invalid record");
  2051. SmallString<16> Elts(Record.begin(), Record.end());
  2052. V = ConstantDataArray::getString(Context, Elts,
  2053. BitCode == bitc::CST_CODE_CSTRING);
  2054. break;
  2055. }
  2056. case bitc::CST_CODE_DATA: {// DATA: [n x value]
  2057. if (Record.empty())
  2058. return error("Invalid record");
  2059. Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
  2060. unsigned Size = Record.size();
  2061. if (EltTy->isIntegerTy(8)) {
  2062. SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
  2063. if (isa<VectorType>(CurTy))
  2064. V = ConstantDataVector::get(Context, Elts);
  2065. else
  2066. V = ConstantDataArray::get(Context, Elts);
  2067. } else if (EltTy->isIntegerTy(16)) {
  2068. SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
  2069. if (isa<VectorType>(CurTy))
  2070. V = ConstantDataVector::get(Context, Elts);
  2071. else
  2072. V = ConstantDataArray::get(Context, Elts);
  2073. } else if (EltTy->isIntegerTy(32)) {
  2074. SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
  2075. if (isa<VectorType>(CurTy))
  2076. V = ConstantDataVector::get(Context, Elts);
  2077. else
  2078. V = ConstantDataArray::get(Context, Elts);
  2079. } else if (EltTy->isIntegerTy(64)) {
  2080. SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
  2081. if (isa<VectorType>(CurTy))
  2082. V = ConstantDataVector::get(Context, Elts);
  2083. else
  2084. V = ConstantDataArray::get(Context, Elts);
  2085. } else if (EltTy->isFloatTy()) {
  2086. SmallVector<float, 16> Elts(Size);
  2087. std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
  2088. if (isa<VectorType>(CurTy))
  2089. V = ConstantDataVector::get(Context, Elts);
  2090. else
  2091. V = ConstantDataArray::get(Context, Elts);
  2092. } else if (EltTy->isDoubleTy()) {
  2093. SmallVector<double, 16> Elts(Size);
  2094. std::transform(Record.begin(), Record.end(), Elts.begin(),
  2095. BitsToDouble);
  2096. if (isa<VectorType>(CurTy))
  2097. V = ConstantDataVector::get(Context, Elts);
  2098. else
  2099. V = ConstantDataArray::get(Context, Elts);
  2100. } else {
  2101. return error("Invalid type for value");
  2102. }
  2103. break;
  2104. }
  2105. case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
  2106. if (Record.size() < 3)
  2107. return error("Invalid record");
  2108. int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
  2109. if (Opc < 0) {
  2110. V = UndefValue::get(CurTy); // Unknown binop.
  2111. } else {
  2112. Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
  2113. Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
  2114. unsigned Flags = 0;
  2115. if (Record.size() >= 4) {
  2116. if (Opc == Instruction::Add ||
  2117. Opc == Instruction::Sub ||
  2118. Opc == Instruction::Mul ||
  2119. Opc == Instruction::Shl) {
  2120. if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
  2121. Flags |= OverflowingBinaryOperator::NoSignedWrap;
  2122. if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
  2123. Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
  2124. } else if (Opc == Instruction::SDiv ||
  2125. Opc == Instruction::UDiv ||
  2126. Opc == Instruction::LShr ||
  2127. Opc == Instruction::AShr) {
  2128. if (Record[3] & (1 << bitc::PEO_EXACT))
  2129. Flags |= SDivOperator::IsExact;
  2130. }
  2131. }
  2132. V = ConstantExpr::get(Opc, LHS, RHS, Flags);
  2133. }
  2134. break;
  2135. }
  2136. case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
  2137. if (Record.size() < 3)
  2138. return error("Invalid record");
  2139. int Opc = getDecodedCastOpcode(Record[0]);
  2140. if (Opc < 0) {
  2141. V = UndefValue::get(CurTy); // Unknown cast.
  2142. } else {
  2143. Type *OpTy = getTypeByID(Record[1]);
  2144. if (!OpTy)
  2145. return error("Invalid record");
  2146. Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
  2147. V = UpgradeBitCastExpr(Opc, Op, CurTy);
  2148. if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
  2149. }
  2150. break;
  2151. }
  2152. case bitc::CST_CODE_CE_INBOUNDS_GEP:
  2153. case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
  2154. unsigned OpNum = 0;
  2155. Type *PointeeType = nullptr;
  2156. if (Record.size() % 2)
  2157. PointeeType = getTypeByID(Record[OpNum++]);
  2158. SmallVector<Constant*, 16> Elts;
  2159. while (OpNum != Record.size()) {
  2160. Type *ElTy = getTypeByID(Record[OpNum++]);
  2161. if (!ElTy)
  2162. return error("Invalid record");
  2163. Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
  2164. }
  2165. if (PointeeType &&
  2166. PointeeType !=
  2167. cast<SequentialType>(Elts[0]->getType()->getScalarType())
  2168. ->getElementType())
  2169. return error("Explicit gep operator type does not match pointee type "
  2170. "of pointer operand");
  2171. ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
  2172. V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
  2173. BitCode ==
  2174. bitc::CST_CODE_CE_INBOUNDS_GEP);
  2175. break;
  2176. }
  2177. case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
  2178. if (Record.size() < 3)
  2179. return error("Invalid record");
  2180. Type *SelectorTy = Type::getInt1Ty(Context);
  2181. // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
  2182. // vector. Otherwise, it must be a single bit.
  2183. if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
  2184. SelectorTy = VectorType::get(Type::getInt1Ty(Context),
  2185. VTy->getNumElements());
  2186. V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
  2187. SelectorTy),
  2188. ValueList.getConstantFwdRef(Record[1],CurTy),
  2189. ValueList.getConstantFwdRef(Record[2],CurTy));
  2190. break;
  2191. }
  2192. case bitc::CST_CODE_CE_EXTRACTELT
  2193. : { // CE_EXTRACTELT: [opty, opval, opty, opval]
  2194. if (Record.size() < 3)
  2195. return error("Invalid record");
  2196. VectorType *OpTy =
  2197. dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
  2198. if (!OpTy)
  2199. return error("Invalid record");
  2200. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  2201. Constant *Op1 = nullptr;
  2202. if (Record.size() == 4) {
  2203. Type *IdxTy = getTypeByID(Record[2]);
  2204. if (!IdxTy)
  2205. return error("Invalid record");
  2206. Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
  2207. } else // TODO: Remove with llvm 4.0
  2208. Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
  2209. if (!Op1)
  2210. return error("Invalid record");
  2211. V = ConstantExpr::getExtractElement(Op0, Op1);
  2212. break;
  2213. }
  2214. case bitc::CST_CODE_CE_INSERTELT
  2215. : { // CE_INSERTELT: [opval, opval, opty, opval]
  2216. VectorType *OpTy = dyn_cast<VectorType>(CurTy);
  2217. if (Record.size() < 3 || !OpTy)
  2218. return error("Invalid record");
  2219. Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
  2220. Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
  2221. OpTy->getElementType());
  2222. Constant *Op2 = nullptr;
  2223. if (Record.size() == 4) {
  2224. Type *IdxTy = getTypeByID(Record[2]);
  2225. if (!IdxTy)
  2226. return error("Invalid record");
  2227. Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
  2228. } else // TODO: Remove with llvm 4.0
  2229. Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
  2230. if (!Op2)
  2231. return error("Invalid record");
  2232. V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
  2233. break;
  2234. }
  2235. case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
  2236. VectorType *OpTy = dyn_cast<VectorType>(CurTy);
  2237. if (Record.size() < 3 || !OpTy)
  2238. return error("Invalid record");
  2239. Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
  2240. Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
  2241. Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
  2242. OpTy->getNumElements());
  2243. Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
  2244. V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
  2245. break;
  2246. }
  2247. case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
  2248. VectorType *RTy = dyn_cast<VectorType>(CurTy);
  2249. VectorType *OpTy =
  2250. dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
  2251. if (Record.size() < 4 || !RTy || !OpTy)
  2252. return error("Invalid record");
  2253. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  2254. Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
  2255. Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
  2256. RTy->getNumElements());
  2257. Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
  2258. V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
  2259. break;
  2260. }
  2261. case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
  2262. if (Record.size() < 4)
  2263. return error("Invalid record");
  2264. Type *OpTy = getTypeByID(Record[0]);
  2265. if (!OpTy)
  2266. return error("Invalid record");
  2267. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  2268. Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
  2269. if (OpTy->isFPOrFPVectorTy())
  2270. V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
  2271. else
  2272. V = ConstantExpr::getICmp(Record[3], Op0, Op1);
  2273. break;
  2274. }
  2275. // This maintains backward compatibility, pre-asm dialect keywords.
  2276. // FIXME: Remove with the 4.0 release.
  2277. case bitc::CST_CODE_INLINEASM_OLD: {
  2278. if (Record.size() < 2)
  2279. return error("Invalid record");
  2280. std::string AsmStr, ConstrStr;
  2281. bool HasSideEffects = Record[0] & 1;
  2282. bool IsAlignStack = Record[0] >> 1;
  2283. unsigned AsmStrSize = Record[1];
  2284. if (2+AsmStrSize >= Record.size())
  2285. return error("Invalid record");
  2286. unsigned ConstStrSize = Record[2+AsmStrSize];
  2287. if (3+AsmStrSize+ConstStrSize > Record.size())
  2288. return error("Invalid record");
  2289. for (unsigned i = 0; i != AsmStrSize; ++i)
  2290. AsmStr += (char)Record[2+i];
  2291. for (unsigned i = 0; i != ConstStrSize; ++i)
  2292. ConstrStr += (char)Record[3+AsmStrSize+i];
  2293. PointerType *PTy = cast<PointerType>(CurTy);
  2294. V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
  2295. AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
  2296. break;
  2297. }
  2298. // This version adds support for the asm dialect keywords (e.g.,
  2299. // inteldialect).
  2300. case bitc::CST_CODE_INLINEASM: {
  2301. if (Record.size() < 2)
  2302. return error("Invalid record");
  2303. std::string AsmStr, ConstrStr;
  2304. bool HasSideEffects = Record[0] & 1;
  2305. bool IsAlignStack = (Record[0] >> 1) & 1;
  2306. unsigned AsmDialect = Record[0] >> 2;
  2307. unsigned AsmStrSize = Record[1];
  2308. if (2+AsmStrSize >= Record.size())
  2309. return error("Invalid record");
  2310. unsigned ConstStrSize = Record[2+AsmStrSize];
  2311. if (3+AsmStrSize+ConstStrSize > Record.size())
  2312. return error("Invalid record");
  2313. for (unsigned i = 0; i != AsmStrSize; ++i)
  2314. AsmStr += (char)Record[2+i];
  2315. for (unsigned i = 0; i != ConstStrSize; ++i)
  2316. ConstrStr += (char)Record[3+AsmStrSize+i];
  2317. PointerType *PTy = cast<PointerType>(CurTy);
  2318. V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
  2319. AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
  2320. InlineAsm::AsmDialect(AsmDialect));
  2321. break;
  2322. }
  2323. case bitc::CST_CODE_BLOCKADDRESS:{
  2324. if (Record.size() < 3)
  2325. return error("Invalid record");
  2326. Type *FnTy = getTypeByID(Record[0]);
  2327. if (!FnTy)
  2328. return error("Invalid record");
  2329. Function *Fn =
  2330. dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
  2331. if (!Fn)
  2332. return error("Invalid record");
  2333. // Don't let Fn get dematerialized.
  2334. BlockAddressesTaken.insert(Fn);
  2335. // If the function is already parsed we can insert the block address right
  2336. // away.
  2337. BasicBlock *BB;
  2338. unsigned BBID = Record[2];
  2339. if (!BBID)
  2340. // Invalid reference to entry block.
  2341. return error("Invalid ID");
  2342. if (!Fn->empty()) {
  2343. Function::iterator BBI = Fn->begin(), BBE = Fn->end();
  2344. for (size_t I = 0, E = BBID; I != E; ++I) {
  2345. if (BBI == BBE)
  2346. return error("Invalid ID");
  2347. ++BBI;
  2348. }
  2349. BB = BBI;
  2350. } else {
  2351. // Otherwise insert a placeholder and remember it so it can be inserted
  2352. // when the function is parsed.
  2353. auto &FwdBBs = BasicBlockFwdRefs[Fn];
  2354. if (FwdBBs.empty())
  2355. BasicBlockFwdRefQueue.push_back(Fn);
  2356. if (FwdBBs.size() < BBID + 1)
  2357. FwdBBs.resize(BBID + 1);
  2358. if (!FwdBBs[BBID])
  2359. FwdBBs[BBID] = BasicBlock::Create(Context);
  2360. BB = FwdBBs[BBID];
  2361. }
  2362. V = BlockAddress::get(Fn, BB);
  2363. break;
  2364. }
  2365. }
  2366. ValueList.assignValue(V, NextCstNo);
  2367. ++NextCstNo;
  2368. }
  2369. }
  2370. std::error_code BitcodeReader::parseUseLists() {
  2371. if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
  2372. return error("Invalid record");
  2373. // Read all the records.
  2374. SmallVector<uint64_t, 64> Record;
  2375. while (1) {
  2376. // HLSL Change Starts - count skipped blocks
  2377. unsigned skipCount = 0;
  2378. BitstreamEntry Entry = Stream.advanceSkippingSubblocks(0, &skipCount);
  2379. if (skipCount) ReportWarning(DiagnosticHandler, "Unrecognized subblock");
  2380. // HLSL Change End
  2381. switch (Entry.Kind) {
  2382. case BitstreamEntry::SubBlock: // Handled for us already.
  2383. case BitstreamEntry::Error:
  2384. return error("Malformed block");
  2385. case BitstreamEntry::EndBlock:
  2386. return std::error_code();
  2387. case BitstreamEntry::Record:
  2388. // The interesting case.
  2389. break;
  2390. }
  2391. // Read a use list record.
  2392. Record.clear();
  2393. bool IsBB = false;
  2394. switch (Stream.readRecord(Entry.ID, Record)) {
  2395. default: // Default behavior: unknown type.
  2396. break;
  2397. case bitc::USELIST_CODE_BB:
  2398. IsBB = true;
  2399. // fallthrough
  2400. case bitc::USELIST_CODE_DEFAULT: {
  2401. unsigned RecordLength = Record.size();
  2402. if (RecordLength < 3)
  2403. // Records should have at least an ID and two indexes.
  2404. return error("Invalid record");
  2405. unsigned ID = Record.back();
  2406. Record.pop_back();
  2407. Value *V;
  2408. if (IsBB) {
  2409. assert(ID < FunctionBBs.size() && "Basic block not found");
  2410. V = FunctionBBs[ID];
  2411. } else
  2412. V = ValueList[ID];
  2413. unsigned NumUses = 0;
  2414. SmallDenseMap<const Use *, unsigned, 16> Order;
  2415. for (const Use &U : V->uses()) {
  2416. if (++NumUses > Record.size())
  2417. break;
  2418. Order[&U] = Record[NumUses - 1];
  2419. }
  2420. if (Order.size() != Record.size() || NumUses > Record.size())
  2421. // Mismatches can happen if the functions are being materialized lazily
  2422. // (out-of-order), or a value has been upgraded.
  2423. break;
  2424. V->sortUseList([&](const Use &L, const Use &R) {
  2425. return Order.lookup(&L) < Order.lookup(&R);
  2426. });
  2427. break;
  2428. }
  2429. }
  2430. }
  2431. }
  2432. /// When we see the block for metadata, remember where it is and then skip it.
  2433. /// This lets us lazily deserialize the metadata.
  2434. std::error_code BitcodeReader::rememberAndSkipMetadata() {
  2435. // Save the current stream state.
  2436. uint64_t CurBit = Stream.GetCurrentBitNo();
  2437. DeferredMetadataInfo.push_back(CurBit);
  2438. // Skip over the block for now.
  2439. if (Stream.SkipBlock())
  2440. return error("Invalid record");
  2441. return std::error_code();
  2442. }
  2443. std::error_code BitcodeReader::materializeMetadata() {
  2444. for (uint64_t BitPos : DeferredMetadataInfo) {
  2445. // Move the bit stream to the saved position.
  2446. Stream.JumpToBit(BitPos);
  2447. if (std::error_code EC = parseMetadata())
  2448. return EC;
  2449. }
  2450. DeferredMetadataInfo.clear();
  2451. return std::error_code();
  2452. }
  2453. void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
  2454. /// When we see the block for a function body, remember where it is and then
  2455. /// skip it. This lets us lazily deserialize the functions.
  2456. std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
  2457. // Get the function we are talking about.
  2458. if (FunctionsWithBodies.empty())
  2459. return error("Insufficient function protos");
  2460. Function *Fn = FunctionsWithBodies.back();
  2461. FunctionsWithBodies.pop_back();
  2462. // Save the current stream state.
  2463. uint64_t CurBit = Stream.GetCurrentBitNo();
  2464. DeferredFunctionInfo[Fn] = CurBit;
  2465. // Skip over the function block for now.
  2466. if (Stream.SkipBlock())
  2467. return error("Invalid record");
  2468. return std::error_code();
  2469. }
  2470. std::error_code BitcodeReader::globalCleanup() {
  2471. // Patch the initializers for globals and aliases up.
  2472. resolveGlobalAndAliasInits();
  2473. if (!GlobalInits.empty() || !AliasInits.empty())
  2474. return error("Malformed global initializer set");
  2475. // Look for intrinsic functions which need to be upgraded at some point
  2476. for (Function &F : *TheModule) {
  2477. Function *NewFn;
  2478. if (UpgradeIntrinsicFunction(&F, NewFn))
  2479. UpgradedIntrinsics[&F] = NewFn;
  2480. }
  2481. // Look for global variables which need to be renamed.
  2482. for (GlobalVariable &GV : TheModule->globals())
  2483. UpgradeGlobalVariable(&GV);
  2484. // Force deallocation of memory for these vectors to favor the client that
  2485. // want lazy deserialization.
  2486. std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
  2487. std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
  2488. return std::error_code();
  2489. }
  2490. std::error_code BitcodeReader::parseModule(bool Resume,
  2491. bool ShouldLazyLoadMetadata) {
  2492. if (Resume)
  2493. Stream.JumpToBit(NextUnreadBit);
  2494. else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
  2495. return error("Invalid record");
  2496. SmallVector<uint64_t, 64> Record;
  2497. std::vector<std::string> SectionTable;
  2498. std::vector<std::string> GCTable;
  2499. // Read all the records for this module.
  2500. while (1) {
  2501. BitstreamEntry Entry = Stream.advance();
  2502. switch (Entry.Kind) {
  2503. case BitstreamEntry::Error:
  2504. return error("Malformed block");
  2505. case BitstreamEntry::EndBlock:
  2506. return globalCleanup();
  2507. case BitstreamEntry::SubBlock:
  2508. switch (Entry.ID) {
  2509. default: // Skip unknown content.
  2510. if (Stream.SkipBlock())
  2511. return error("Invalid record");
  2512. ReportWarning(DiagnosticHandler, "Unrecognized block found"); // HLSL Change - check for skipped blocks
  2513. break;
  2514. case bitc::BLOCKINFO_BLOCK_ID:
  2515. // HLSL Changes Start -- check for skipped blocks
  2516. unsigned count;
  2517. count = 0;
  2518. if (Stream.ReadBlockInfoBlock(&count))
  2519. return error("Malformed block");
  2520. if (count > 0)
  2521. ReportWarning(DiagnosticHandler, "Unrecognized block found");
  2522. // HLSL Changes End
  2523. break;
  2524. case bitc::PARAMATTR_BLOCK_ID:
  2525. if (std::error_code EC = parseAttributeBlock())
  2526. return EC;
  2527. break;
  2528. case bitc::PARAMATTR_GROUP_BLOCK_ID:
  2529. if (std::error_code EC = parseAttributeGroupBlock())
  2530. return EC;
  2531. break;
  2532. case bitc::TYPE_BLOCK_ID_NEW:
  2533. if (std::error_code EC = parseTypeTable())
  2534. return EC;
  2535. break;
  2536. case bitc::VALUE_SYMTAB_BLOCK_ID:
  2537. if (std::error_code EC = parseValueSymbolTable())
  2538. return EC;
  2539. SeenValueSymbolTable = true;
  2540. break;
  2541. case bitc::CONSTANTS_BLOCK_ID:
  2542. if (std::error_code EC = parseConstants())
  2543. return EC;
  2544. if (std::error_code EC = resolveGlobalAndAliasInits())
  2545. return EC;
  2546. break;
  2547. case bitc::METADATA_BLOCK_ID:
  2548. if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
  2549. if (std::error_code EC = rememberAndSkipMetadata())
  2550. return EC;
  2551. break;
  2552. }
  2553. assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
  2554. if (std::error_code EC = parseMetadata())
  2555. return EC;
  2556. break;
  2557. case bitc::FUNCTION_BLOCK_ID:
  2558. // If this is the first function body we've seen, reverse the
  2559. // FunctionsWithBodies list.
  2560. if (!SeenFirstFunctionBody) {
  2561. std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
  2562. if (std::error_code EC = globalCleanup())
  2563. return EC;
  2564. SeenFirstFunctionBody = true;
  2565. }
  2566. if (std::error_code EC = rememberAndSkipFunctionBody())
  2567. return EC;
  2568. // Suspend parsing when we reach the function bodies. Subsequent
  2569. // materialization calls will resume it when necessary. If the bitcode
  2570. // file is old, the symbol table will be at the end instead and will not
  2571. // have been seen yet. In this case, just finish the parse now.
  2572. if (SeenValueSymbolTable) {
  2573. NextUnreadBit = Stream.GetCurrentBitNo();
  2574. return std::error_code();
  2575. }
  2576. break;
  2577. case bitc::USELIST_BLOCK_ID:
  2578. if (std::error_code EC = parseUseLists())
  2579. return EC;
  2580. break;
  2581. }
  2582. continue;
  2583. case BitstreamEntry::Record:
  2584. // The interesting case.
  2585. break;
  2586. }
  2587. // Read a record.
  2588. switch (Stream.readRecord(Entry.ID, Record)) {
  2589. default: break; // Default behavior, ignore unknown content.
  2590. case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
  2591. if (Record.size() < 1)
  2592. return error("Invalid record");
  2593. // Only version #0 and #1 are supported so far.
  2594. unsigned module_version = Record[0];
  2595. switch (module_version) {
  2596. default:
  2597. return error("Invalid value");
  2598. case 0:
  2599. UseRelativeIDs = false;
  2600. break;
  2601. case 1:
  2602. UseRelativeIDs = true;
  2603. break;
  2604. }
  2605. break;
  2606. }
  2607. case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
  2608. std::string S;
  2609. if (convertToString(Record, 0, S))
  2610. return error("Invalid record");
  2611. TheModule->setTargetTriple(S);
  2612. break;
  2613. }
  2614. case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
  2615. std::string S;
  2616. if (convertToString(Record, 0, S))
  2617. return error("Invalid record");
  2618. TheModule->setDataLayout(S);
  2619. break;
  2620. }
  2621. case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
  2622. std::string S;
  2623. if (convertToString(Record, 0, S))
  2624. return error("Invalid record");
  2625. TheModule->setModuleInlineAsm(S);
  2626. break;
  2627. }
  2628. case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
  2629. // FIXME: Remove in 4.0.
  2630. std::string S;
  2631. if (convertToString(Record, 0, S))
  2632. return error("Invalid record");
  2633. // Ignore value.
  2634. break;
  2635. }
  2636. case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
  2637. std::string S;
  2638. if (convertToString(Record, 0, S))
  2639. return error("Invalid record");
  2640. SectionTable.push_back(S);
  2641. break;
  2642. }
  2643. case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
  2644. std::string S;
  2645. if (convertToString(Record, 0, S))
  2646. return error("Invalid record");
  2647. GCTable.push_back(S);
  2648. break;
  2649. }
  2650. case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
  2651. if (Record.size() < 2)
  2652. return error("Invalid record");
  2653. Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
  2654. unsigned ComdatNameSize = Record[1];
  2655. std::string ComdatName;
  2656. ComdatName.reserve(ComdatNameSize);
  2657. for (unsigned i = 0; i != ComdatNameSize; ++i)
  2658. ComdatName += (char)Record[2 + i];
  2659. Comdat *C = TheModule->getOrInsertComdat(ComdatName);
  2660. C->setSelectionKind(SK);
  2661. ComdatList.push_back(C);
  2662. break;
  2663. }
  2664. // GLOBALVAR: [pointer type, isconst, initid,
  2665. // linkage, alignment, section, visibility, threadlocal,
  2666. // unnamed_addr, externally_initialized, dllstorageclass,
  2667. // comdat]
  2668. case bitc::MODULE_CODE_GLOBALVAR: {
  2669. if (Record.size() < 6)
  2670. return error("Invalid record");
  2671. Type *Ty = getTypeByID(Record[0]);
  2672. if (!Ty)
  2673. return error("Invalid record");
  2674. bool isConstant = Record[1] & 1;
  2675. bool explicitType = Record[1] & 2;
  2676. unsigned AddressSpace;
  2677. if (explicitType) {
  2678. AddressSpace = Record[1] >> 2;
  2679. } else {
  2680. if (!Ty->isPointerTy())
  2681. return error("Invalid type for value");
  2682. AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
  2683. Ty = cast<PointerType>(Ty)->getElementType();
  2684. }
  2685. uint64_t RawLinkage = Record[3];
  2686. GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
  2687. unsigned Alignment;
  2688. if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
  2689. return EC;
  2690. std::string Section;
  2691. if (Record[5]) {
  2692. if (Record[5]-1 >= SectionTable.size())
  2693. return error("Invalid ID");
  2694. Section = SectionTable[Record[5]-1];
  2695. }
  2696. GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
  2697. // Local linkage must have default visibility.
  2698. if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
  2699. // FIXME: Change to an error if non-default in 4.0.
  2700. Visibility = getDecodedVisibility(Record[6]);
  2701. GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
  2702. if (Record.size() > 7)
  2703. TLM = getDecodedThreadLocalMode(Record[7]);
  2704. bool UnnamedAddr = false;
  2705. if (Record.size() > 8)
  2706. UnnamedAddr = Record[8];
  2707. bool ExternallyInitialized = false;
  2708. if (Record.size() > 9)
  2709. ExternallyInitialized = Record[9];
  2710. GlobalVariable *NewGV =
  2711. new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
  2712. TLM, AddressSpace, ExternallyInitialized);
  2713. NewGV->setAlignment(Alignment);
  2714. if (!Section.empty())
  2715. NewGV->setSection(Section);
  2716. NewGV->setVisibility(Visibility);
  2717. NewGV->setUnnamedAddr(UnnamedAddr);
  2718. if (Record.size() > 10)
  2719. NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
  2720. else
  2721. upgradeDLLImportExportLinkage(NewGV, RawLinkage);
  2722. ValueList.push_back(NewGV);
  2723. // Remember which value to use for the global initializer.
  2724. if (unsigned InitID = Record[2])
  2725. GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
  2726. if (Record.size() > 11) {
  2727. if (unsigned ComdatID = Record[11]) {
  2728. if (ComdatID > ComdatList.size())
  2729. return error("Invalid global variable comdat ID");
  2730. NewGV->setComdat(ComdatList[ComdatID - 1]);
  2731. }
  2732. } else if (hasImplicitComdat(RawLinkage)) {
  2733. NewGV->setComdat(reinterpret_cast<Comdat *>(1));
  2734. }
  2735. break;
  2736. }
  2737. // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
  2738. // alignment, section, visibility, gc, unnamed_addr,
  2739. // prologuedata, dllstorageclass, comdat, prefixdata]
  2740. case bitc::MODULE_CODE_FUNCTION: {
  2741. if (Record.size() < 8)
  2742. return error("Invalid record");
  2743. Type *Ty = getTypeByID(Record[0]);
  2744. if (!Ty)
  2745. return error("Invalid record");
  2746. if (auto *PTy = dyn_cast<PointerType>(Ty))
  2747. Ty = PTy->getElementType();
  2748. auto *FTy = dyn_cast<FunctionType>(Ty);
  2749. if (!FTy)
  2750. return error("Invalid type for value");
  2751. Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
  2752. "", TheModule);
  2753. Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
  2754. bool isProto = Record[2];
  2755. uint64_t RawLinkage = Record[3];
  2756. Func->setLinkage(getDecodedLinkage(RawLinkage));
  2757. Func->setAttributes(getAttributes(Record[4]));
  2758. unsigned Alignment;
  2759. if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
  2760. return EC;
  2761. Func->setAlignment(Alignment);
  2762. if (Record[6]) {
  2763. if (Record[6]-1 >= SectionTable.size())
  2764. return error("Invalid ID");
  2765. Func->setSection(SectionTable[Record[6]-1]);
  2766. }
  2767. // Local linkage must have default visibility.
  2768. if (!Func->hasLocalLinkage())
  2769. // FIXME: Change to an error if non-default in 4.0.
  2770. Func->setVisibility(getDecodedVisibility(Record[7]));
  2771. if (Record.size() > 8 && Record[8]) {
  2772. if (Record[8]-1 >= GCTable.size())
  2773. return error("Invalid ID");
  2774. Func->setGC(GCTable[Record[8]-1].c_str());
  2775. }
  2776. bool UnnamedAddr = false;
  2777. if (Record.size() > 9)
  2778. UnnamedAddr = Record[9];
  2779. Func->setUnnamedAddr(UnnamedAddr);
  2780. if (Record.size() > 10 && Record[10] != 0)
  2781. FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
  2782. if (Record.size() > 11)
  2783. Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
  2784. else
  2785. upgradeDLLImportExportLinkage(Func, RawLinkage);
  2786. if (Record.size() > 12) {
  2787. if (unsigned ComdatID = Record[12]) {
  2788. if (ComdatID > ComdatList.size())
  2789. return error("Invalid function comdat ID");
  2790. Func->setComdat(ComdatList[ComdatID - 1]);
  2791. }
  2792. } else if (hasImplicitComdat(RawLinkage)) {
  2793. Func->setComdat(reinterpret_cast<Comdat *>(1));
  2794. }
  2795. if (Record.size() > 13 && Record[13] != 0)
  2796. FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
  2797. if (Record.size() > 14 && Record[14] != 0)
  2798. FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
  2799. ValueList.push_back(Func);
  2800. // If this is a function with a body, remember the prototype we are
  2801. // creating now, so that we can match up the body with them later.
  2802. if (!isProto) {
  2803. Func->setIsMaterializable(true);
  2804. FunctionsWithBodies.push_back(Func);
  2805. DeferredFunctionInfo[Func] = 0;
  2806. }
  2807. break;
  2808. }
  2809. // ALIAS: [alias type, aliasee val#, linkage]
  2810. // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
  2811. case bitc::MODULE_CODE_ALIAS: {
  2812. if (Record.size() < 3)
  2813. return error("Invalid record");
  2814. Type *Ty = getTypeByID(Record[0]);
  2815. if (!Ty)
  2816. return error("Invalid record");
  2817. auto *PTy = dyn_cast<PointerType>(Ty);
  2818. if (!PTy)
  2819. return error("Invalid type for value");
  2820. auto *NewGA =
  2821. GlobalAlias::create(PTy, getDecodedLinkage(Record[2]), "", TheModule);
  2822. // Old bitcode files didn't have visibility field.
  2823. // Local linkage must have default visibility.
  2824. if (Record.size() > 3 && !NewGA->hasLocalLinkage())
  2825. // FIXME: Change to an error if non-default in 4.0.
  2826. NewGA->setVisibility(getDecodedVisibility(Record[3]));
  2827. if (Record.size() > 4)
  2828. NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[4]));
  2829. else
  2830. upgradeDLLImportExportLinkage(NewGA, Record[2]);
  2831. if (Record.size() > 5)
  2832. NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[5]));
  2833. if (Record.size() > 6)
  2834. NewGA->setUnnamedAddr(Record[6]);
  2835. ValueList.push_back(NewGA);
  2836. AliasInits.push_back(std::make_pair(NewGA, Record[1]));
  2837. break;
  2838. }
  2839. /// MODULE_CODE_PURGEVALS: [numvals]
  2840. case bitc::MODULE_CODE_PURGEVALS:
  2841. // Trim down the value list to the specified size.
  2842. if (Record.size() < 1 || Record[0] > ValueList.size())
  2843. return error("Invalid record");
  2844. ValueList.shrinkTo(Record[0]);
  2845. break;
  2846. }
  2847. Record.clear();
  2848. }
  2849. }
  2850. std::error_code
  2851. BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
  2852. Module *M, bool ShouldLazyLoadMetadata) {
  2853. TheModule = M;
  2854. if (std::error_code EC = initStream(std::move(Streamer)))
  2855. return EC;
  2856. // Sniff for the signature.
  2857. if (Stream.Read(8) != 'B' ||
  2858. Stream.Read(8) != 'C' ||
  2859. Stream.Read(4) != 0x0 ||
  2860. Stream.Read(4) != 0xC ||
  2861. Stream.Read(4) != 0xE ||
  2862. Stream.Read(4) != 0xD)
  2863. return error("Invalid bitcode signature");
  2864. // We expect a number of well-defined blocks, though we don't necessarily
  2865. // need to understand them all.
  2866. while (1) {
  2867. if (Stream.AtEndOfStream()) {
  2868. return error("Malformed IR file");
  2869. }
  2870. BitstreamEntry Entry =
  2871. Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
  2872. if (Entry.Kind != BitstreamEntry::SubBlock)
  2873. return error("Malformed block");
  2874. // HLSL Change - process the complete stream.
  2875. if (Entry.ID == bitc::MODULE_BLOCK_ID) {
  2876. return parseModule(false, ShouldLazyLoadMetadata);
  2877. }
  2878. else {
  2879. ReportWarning(DiagnosticHandler, "Unrecognized block found");
  2880. if (Stream.SkipBlock())
  2881. return error("Invalid record");
  2882. }
  2883. // HLSL Change Ends - process the complete stream.
  2884. }
  2885. }
  2886. ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
  2887. if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
  2888. return error("Invalid record");
  2889. SmallVector<uint64_t, 64> Record;
  2890. std::string Triple;
  2891. // Read all the records for this module.
  2892. while (1) {
  2893. // HLSL Change Starts - count skipped blocks
  2894. unsigned skipCount = 0;
  2895. BitstreamEntry Entry = Stream.advanceSkippingSubblocks(0, &skipCount);
  2896. if (skipCount) ReportWarning(DiagnosticHandler, "Unrecognized subblock");
  2897. // HLSL Change End
  2898. switch (Entry.Kind) {
  2899. case BitstreamEntry::SubBlock: // Handled for us already.
  2900. case BitstreamEntry::Error:
  2901. return error("Malformed block");
  2902. case BitstreamEntry::EndBlock:
  2903. return Triple;
  2904. case BitstreamEntry::Record:
  2905. // The interesting case.
  2906. break;
  2907. }
  2908. // Read a record.
  2909. switch (Stream.readRecord(Entry.ID, Record)) {
  2910. default: break; // Default behavior, ignore unknown content.
  2911. case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
  2912. std::string S;
  2913. if (convertToString(Record, 0, S))
  2914. return error("Invalid record");
  2915. Triple = S;
  2916. break;
  2917. }
  2918. }
  2919. Record.clear();
  2920. }
  2921. llvm_unreachable("Exit infinite loop");
  2922. }
  2923. ErrorOr<std::string> BitcodeReader::parseTriple() {
  2924. if (std::error_code EC = initStream(nullptr))
  2925. return EC;
  2926. // Sniff for the signature.
  2927. if (Stream.Read(8) != 'B' ||
  2928. Stream.Read(8) != 'C' ||
  2929. Stream.Read(4) != 0x0 ||
  2930. Stream.Read(4) != 0xC ||
  2931. Stream.Read(4) != 0xE ||
  2932. Stream.Read(4) != 0xD)
  2933. return error("Invalid bitcode signature");
  2934. // We expect a number of well-defined blocks, though we don't necessarily
  2935. // need to understand them all.
  2936. while (1) {
  2937. BitstreamEntry Entry = Stream.advance();
  2938. switch (Entry.Kind) {
  2939. case BitstreamEntry::Error:
  2940. return error("Malformed block");
  2941. case BitstreamEntry::EndBlock:
  2942. return std::error_code();
  2943. case BitstreamEntry::SubBlock:
  2944. if (Entry.ID == bitc::MODULE_BLOCK_ID)
  2945. return parseModuleTriple();
  2946. // Ignore other sub-blocks.
  2947. if (Stream.SkipBlock())
  2948. return error("Malformed block");
  2949. ReportWarning(DiagnosticHandler, "Unrecognized block found");
  2950. continue;
  2951. case BitstreamEntry::Record:
  2952. Stream.skipRecord(Entry.ID);
  2953. continue;
  2954. }
  2955. }
  2956. }
  2957. /// Parse metadata attachments.
  2958. std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
  2959. if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
  2960. return error("Invalid record");
  2961. SmallVector<uint64_t, 64> Record;
  2962. while (1) {
  2963. // HLSL Change Starts - count skipped blocks
  2964. unsigned skipCount = 0;
  2965. BitstreamEntry Entry = Stream.advanceSkippingSubblocks(0, &skipCount);
  2966. if (skipCount) ReportWarning(DiagnosticHandler, "Unrecognized subblock");
  2967. // HLSL Change End
  2968. switch (Entry.Kind) {
  2969. case BitstreamEntry::SubBlock: // Handled for us already.
  2970. case BitstreamEntry::Error:
  2971. return error("Malformed block");
  2972. case BitstreamEntry::EndBlock:
  2973. return std::error_code();
  2974. case BitstreamEntry::Record:
  2975. // The interesting case.
  2976. break;
  2977. }
  2978. // Read a metadata attachment record.
  2979. Record.clear();
  2980. switch (Stream.readRecord(Entry.ID, Record)) {
  2981. default: // Default behavior: ignore.
  2982. break;
  2983. case bitc::METADATA_ATTACHMENT: {
  2984. unsigned RecordLength = Record.size();
  2985. if (Record.empty())
  2986. return error("Invalid record");
  2987. if (RecordLength % 2 == 0) {
  2988. // A function attachment.
  2989. for (unsigned I = 0; I != RecordLength; I += 2) {
  2990. auto K = MDKindMap.find(Record[I]);
  2991. if (K == MDKindMap.end())
  2992. return error("Invalid ID");
  2993. Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
  2994. F.setMetadata(K->second, cast<MDNode>(MD));
  2995. }
  2996. continue;
  2997. }
  2998. // An instruction attachment.
  2999. Instruction *Inst = InstructionList[Record[0]];
  3000. for (unsigned i = 1; i != RecordLength; i = i+2) {
  3001. unsigned Kind = Record[i];
  3002. DenseMap<unsigned, unsigned>::iterator I =
  3003. MDKindMap.find(Kind);
  3004. if (I == MDKindMap.end())
  3005. return error("Invalid ID");
  3006. Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
  3007. if (isa<LocalAsMetadata>(Node))
  3008. // Drop the attachment. This used to be legal, but there's no
  3009. // upgrade path.
  3010. break;
  3011. Inst->setMetadata(I->second, cast<MDNode>(Node));
  3012. if (I->second == LLVMContext::MD_tbaa)
  3013. InstsWithTBAATag.push_back(Inst);
  3014. }
  3015. break;
  3016. }
  3017. }
  3018. }
  3019. }
  3020. static std::error_code typeCheckLoadStoreInst(DiagnosticHandlerFunction DH,
  3021. Type *ValType, Type *PtrType) {
  3022. if (!isa<PointerType>(PtrType))
  3023. return error(DH, "Load/Store operand is not a pointer type");
  3024. Type *ElemType = cast<PointerType>(PtrType)->getElementType();
  3025. if (ValType && ValType != ElemType)
  3026. return error(DH, "Explicit load/store type does not match pointee type of "
  3027. "pointer operand");
  3028. if (!PointerType::isLoadableOrStorableType(ElemType))
  3029. return error(DH, "Cannot load/store from pointer");
  3030. return std::error_code();
  3031. }
  3032. /// Lazily parse the specified function body block.
  3033. std::error_code BitcodeReader::parseFunctionBody(Function *F) {
  3034. if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
  3035. return error("Invalid record");
  3036. InstructionList.clear();
  3037. unsigned ModuleValueListSize = ValueList.size();
  3038. unsigned ModuleMDValueListSize = MDValueList.size();
  3039. // Add all the function arguments to the value table.
  3040. for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
  3041. ValueList.push_back(I);
  3042. unsigned NextValueNo = ValueList.size();
  3043. BasicBlock *CurBB = nullptr;
  3044. unsigned CurBBNo = 0;
  3045. DebugLoc LastLoc;
  3046. auto getLastInstruction = [&]() -> Instruction * {
  3047. if (CurBB && !CurBB->empty())
  3048. return &CurBB->back();
  3049. else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
  3050. !FunctionBBs[CurBBNo - 1]->empty())
  3051. return &FunctionBBs[CurBBNo - 1]->back();
  3052. return nullptr;
  3053. };
  3054. // Read all the records.
  3055. SmallVector<uint64_t, 64> Record;
  3056. while (1) {
  3057. BitstreamEntry Entry = Stream.advance();
  3058. switch (Entry.Kind) {
  3059. case BitstreamEntry::Error:
  3060. return error("Malformed block");
  3061. case BitstreamEntry::EndBlock:
  3062. goto OutOfRecordLoop;
  3063. case BitstreamEntry::SubBlock:
  3064. switch (Entry.ID) {
  3065. default: // Skip unknown content.
  3066. if (Stream.SkipBlock())
  3067. return error("Invalid record");
  3068. ReportWarning(DiagnosticHandler, "Unrecognized block found");
  3069. break;
  3070. case bitc::CONSTANTS_BLOCK_ID:
  3071. if (std::error_code EC = parseConstants())
  3072. return EC;
  3073. NextValueNo = ValueList.size();
  3074. break;
  3075. case bitc::VALUE_SYMTAB_BLOCK_ID:
  3076. if (std::error_code EC = parseValueSymbolTable())
  3077. return EC;
  3078. break;
  3079. case bitc::METADATA_ATTACHMENT_ID:
  3080. if (std::error_code EC = parseMetadataAttachment(*F))
  3081. return EC;
  3082. break;
  3083. case bitc::METADATA_BLOCK_ID:
  3084. if (std::error_code EC = parseMetadata())
  3085. return EC;
  3086. break;
  3087. case bitc::USELIST_BLOCK_ID:
  3088. if (std::error_code EC = parseUseLists())
  3089. return EC;
  3090. break;
  3091. }
  3092. continue;
  3093. case BitstreamEntry::Record:
  3094. // The interesting case.
  3095. break;
  3096. }
  3097. // Read a record.
  3098. Record.clear();
  3099. Instruction *I = nullptr;
  3100. unsigned BitCode = Stream.readRecord(Entry.ID, Record);
  3101. switch (BitCode) {
  3102. default: // Default behavior: reject
  3103. return error("Invalid value");
  3104. case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
  3105. if (Record.size() < 1 || Record[0] == 0)
  3106. return error("Invalid record");
  3107. // Create all the basic blocks for the function.
  3108. FunctionBBs.resize(Record[0]);
  3109. // See if anything took the address of blocks in this function.
  3110. auto BBFRI = BasicBlockFwdRefs.find(F);
  3111. if (BBFRI == BasicBlockFwdRefs.end()) {
  3112. for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
  3113. FunctionBBs[i] = BasicBlock::Create(Context, "", F);
  3114. } else {
  3115. auto &BBRefs = BBFRI->second;
  3116. // Check for invalid basic block references.
  3117. if (BBRefs.size() > FunctionBBs.size())
  3118. return error("Invalid ID");
  3119. assert(!BBRefs.empty() && "Unexpected empty array");
  3120. assert(!BBRefs.front() && "Invalid reference to entry block");
  3121. for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
  3122. ++I)
  3123. if (I < RE && BBRefs[I]) {
  3124. BBRefs[I]->insertInto(F);
  3125. FunctionBBs[I] = BBRefs[I];
  3126. } else {
  3127. FunctionBBs[I] = BasicBlock::Create(Context, "", F);
  3128. }
  3129. // Erase from the table.
  3130. BasicBlockFwdRefs.erase(BBFRI);
  3131. }
  3132. CurBB = FunctionBBs[0];
  3133. continue;
  3134. }
  3135. case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
  3136. // This record indicates that the last instruction is at the same
  3137. // location as the previous instruction with a location.
  3138. I = getLastInstruction();
  3139. if (!I)
  3140. return error("Invalid record");
  3141. I->setDebugLoc(LastLoc);
  3142. I = nullptr;
  3143. continue;
  3144. case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
  3145. I = getLastInstruction();
  3146. if (!I || Record.size() < 4)
  3147. return error("Invalid record");
  3148. unsigned Line = Record[0], Col = Record[1];
  3149. unsigned ScopeID = Record[2], IAID = Record[3];
  3150. MDNode *Scope = nullptr, *IA = nullptr;
  3151. if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
  3152. if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
  3153. LastLoc = DebugLoc::get(Line, Col, Scope, IA);
  3154. I->setDebugLoc(LastLoc);
  3155. I = nullptr;
  3156. continue;
  3157. }
  3158. case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
  3159. unsigned OpNum = 0;
  3160. Value *LHS, *RHS;
  3161. if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
  3162. popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
  3163. OpNum+1 > Record.size())
  3164. return error("Invalid record");
  3165. int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
  3166. if (Opc == -1)
  3167. return error("Invalid record");
  3168. I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
  3169. InstructionList.push_back(I);
  3170. if (OpNum < Record.size()) {
  3171. if (Opc == Instruction::Add ||
  3172. Opc == Instruction::Sub ||
  3173. Opc == Instruction::Mul ||
  3174. Opc == Instruction::Shl) {
  3175. if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
  3176. cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
  3177. if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
  3178. cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
  3179. } else if (Opc == Instruction::SDiv ||
  3180. Opc == Instruction::UDiv ||
  3181. Opc == Instruction::LShr ||
  3182. Opc == Instruction::AShr) {
  3183. if (Record[OpNum] & (1 << bitc::PEO_EXACT))
  3184. cast<BinaryOperator>(I)->setIsExact(true);
  3185. } else if (isa<FPMathOperator>(I)) {
  3186. FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
  3187. if (FMF.any())
  3188. I->setFastMathFlags(FMF);
  3189. }
  3190. }
  3191. break;
  3192. }
  3193. case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
  3194. unsigned OpNum = 0;
  3195. Value *Op;
  3196. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  3197. OpNum+2 != Record.size())
  3198. return error("Invalid record");
  3199. Type *ResTy = getTypeByID(Record[OpNum]);
  3200. int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
  3201. if (Opc == -1 || !ResTy)
  3202. return error("Invalid record");
  3203. Instruction *Temp = nullptr;
  3204. if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
  3205. if (Temp) {
  3206. InstructionList.push_back(Temp);
  3207. CurBB->getInstList().push_back(Temp);
  3208. }
  3209. } else {
  3210. I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
  3211. }
  3212. InstructionList.push_back(I);
  3213. break;
  3214. }
  3215. case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
  3216. case bitc::FUNC_CODE_INST_GEP_OLD:
  3217. case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
  3218. unsigned OpNum = 0;
  3219. Type *Ty;
  3220. bool InBounds;
  3221. if (BitCode == bitc::FUNC_CODE_INST_GEP) {
  3222. InBounds = Record[OpNum++];
  3223. Ty = getTypeByID(Record[OpNum++]);
  3224. } else {
  3225. InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
  3226. Ty = nullptr;
  3227. }
  3228. Value *BasePtr;
  3229. if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
  3230. return error("Invalid record");
  3231. if (!Ty)
  3232. Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
  3233. ->getElementType();
  3234. else if (Ty !=
  3235. cast<SequentialType>(BasePtr->getType()->getScalarType())
  3236. ->getElementType())
  3237. return error(
  3238. "Explicit gep type does not match pointee type of pointer operand");
  3239. SmallVector<Value*, 16> GEPIdx;
  3240. while (OpNum != Record.size()) {
  3241. Value *Op;
  3242. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  3243. return error("Invalid record");
  3244. GEPIdx.push_back(Op);
  3245. }
  3246. I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
  3247. InstructionList.push_back(I);
  3248. if (InBounds)
  3249. cast<GetElementPtrInst>(I)->setIsInBounds(true);
  3250. break;
  3251. }
  3252. case bitc::FUNC_CODE_INST_EXTRACTVAL: {
  3253. // EXTRACTVAL: [opty, opval, n x indices]
  3254. unsigned OpNum = 0;
  3255. Value *Agg;
  3256. if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
  3257. return error("Invalid record");
  3258. unsigned RecSize = Record.size();
  3259. if (OpNum == RecSize)
  3260. return error("EXTRACTVAL: Invalid instruction with 0 indices");
  3261. SmallVector<unsigned, 4> EXTRACTVALIdx;
  3262. Type *CurTy = Agg->getType();
  3263. for (; OpNum != RecSize; ++OpNum) {
  3264. bool IsArray = CurTy->isArrayTy();
  3265. bool IsStruct = CurTy->isStructTy();
  3266. uint64_t Index = Record[OpNum];
  3267. if (!IsStruct && !IsArray)
  3268. return error("EXTRACTVAL: Invalid type");
  3269. if ((unsigned)Index != Index)
  3270. return error("Invalid value");
  3271. if (IsStruct && Index >= CurTy->subtypes().size())
  3272. return error("EXTRACTVAL: Invalid struct index");
  3273. if (IsArray && Index >= CurTy->getArrayNumElements())
  3274. return error("EXTRACTVAL: Invalid array index");
  3275. EXTRACTVALIdx.push_back((unsigned)Index);
  3276. if (IsStruct)
  3277. CurTy = CurTy->subtypes()[Index];
  3278. else
  3279. CurTy = CurTy->subtypes()[0];
  3280. }
  3281. I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
  3282. InstructionList.push_back(I);
  3283. break;
  3284. }
  3285. case bitc::FUNC_CODE_INST_INSERTVAL: {
  3286. // INSERTVAL: [opty, opval, opty, opval, n x indices]
  3287. unsigned OpNum = 0;
  3288. Value *Agg;
  3289. if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
  3290. return error("Invalid record");
  3291. Value *Val;
  3292. if (getValueTypePair(Record, OpNum, NextValueNo, Val))
  3293. return error("Invalid record");
  3294. unsigned RecSize = Record.size();
  3295. if (OpNum == RecSize)
  3296. return error("INSERTVAL: Invalid instruction with 0 indices");
  3297. SmallVector<unsigned, 4> INSERTVALIdx;
  3298. Type *CurTy = Agg->getType();
  3299. for (; OpNum != RecSize; ++OpNum) {
  3300. bool IsArray = CurTy->isArrayTy();
  3301. bool IsStruct = CurTy->isStructTy();
  3302. uint64_t Index = Record[OpNum];
  3303. if (!IsStruct && !IsArray)
  3304. return error("INSERTVAL: Invalid type");
  3305. if ((unsigned)Index != Index)
  3306. return error("Invalid value");
  3307. if (IsStruct && Index >= CurTy->subtypes().size())
  3308. return error("INSERTVAL: Invalid struct index");
  3309. if (IsArray && Index >= CurTy->getArrayNumElements())
  3310. return error("INSERTVAL: Invalid array index");
  3311. INSERTVALIdx.push_back((unsigned)Index);
  3312. if (IsStruct)
  3313. CurTy = CurTy->subtypes()[Index];
  3314. else
  3315. CurTy = CurTy->subtypes()[0];
  3316. }
  3317. if (CurTy != Val->getType())
  3318. return error("Inserted value type doesn't match aggregate type");
  3319. I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
  3320. InstructionList.push_back(I);
  3321. break;
  3322. }
  3323. case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
  3324. // obsolete form of select
  3325. // handles select i1 ... in old bitcode
  3326. unsigned OpNum = 0;
  3327. Value *TrueVal, *FalseVal, *Cond;
  3328. if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
  3329. popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
  3330. popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
  3331. return error("Invalid record");
  3332. I = SelectInst::Create(Cond, TrueVal, FalseVal);
  3333. InstructionList.push_back(I);
  3334. break;
  3335. }
  3336. case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
  3337. // new form of select
  3338. // handles select i1 or select [N x i1]
  3339. unsigned OpNum = 0;
  3340. Value *TrueVal, *FalseVal, *Cond;
  3341. if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
  3342. popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
  3343. getValueTypePair(Record, OpNum, NextValueNo, Cond))
  3344. return error("Invalid record");
  3345. // select condition can be either i1 or [N x i1]
  3346. if (VectorType* vector_type =
  3347. dyn_cast<VectorType>(Cond->getType())) {
  3348. // expect <n x i1>
  3349. if (vector_type->getElementType() != Type::getInt1Ty(Context))
  3350. return error("Invalid type for value");
  3351. } else {
  3352. // expect i1
  3353. if (Cond->getType() != Type::getInt1Ty(Context))
  3354. return error("Invalid type for value");
  3355. }
  3356. I = SelectInst::Create(Cond, TrueVal, FalseVal);
  3357. InstructionList.push_back(I);
  3358. break;
  3359. }
  3360. case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
  3361. unsigned OpNum = 0;
  3362. Value *Vec, *Idx;
  3363. if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
  3364. getValueTypePair(Record, OpNum, NextValueNo, Idx))
  3365. return error("Invalid record");
  3366. if (!Vec->getType()->isVectorTy())
  3367. return error("Invalid type for value");
  3368. I = ExtractElementInst::Create(Vec, Idx);
  3369. InstructionList.push_back(I);
  3370. break;
  3371. }
  3372. case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
  3373. unsigned OpNum = 0;
  3374. Value *Vec, *Elt, *Idx;
  3375. if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
  3376. return error("Invalid record");
  3377. if (!Vec->getType()->isVectorTy())
  3378. return error("Invalid type for value");
  3379. if (popValue(Record, OpNum, NextValueNo,
  3380. cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
  3381. getValueTypePair(Record, OpNum, NextValueNo, Idx))
  3382. return error("Invalid record");
  3383. I = InsertElementInst::Create(Vec, Elt, Idx);
  3384. InstructionList.push_back(I);
  3385. break;
  3386. }
  3387. case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
  3388. unsigned OpNum = 0;
  3389. Value *Vec1, *Vec2, *Mask;
  3390. if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
  3391. popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
  3392. return error("Invalid record");
  3393. if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
  3394. return error("Invalid record");
  3395. if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
  3396. return error("Invalid type for value");
  3397. I = new ShuffleVectorInst(Vec1, Vec2, Mask);
  3398. InstructionList.push_back(I);
  3399. break;
  3400. }
  3401. case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
  3402. // Old form of ICmp/FCmp returning bool
  3403. // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
  3404. // both legal on vectors but had different behaviour.
  3405. case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
  3406. // FCmp/ICmp returning bool or vector of bool
  3407. unsigned OpNum = 0;
  3408. Value *LHS, *RHS;
  3409. if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
  3410. popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
  3411. return error("Invalid record");
  3412. unsigned PredVal = Record[OpNum];
  3413. bool IsFP = LHS->getType()->isFPOrFPVectorTy();
  3414. FastMathFlags FMF;
  3415. if (IsFP && Record.size() > OpNum+1)
  3416. FMF = getDecodedFastMathFlags(Record[++OpNum]);
  3417. if (OpNum+1 != Record.size())
  3418. return error("Invalid record");
  3419. if (LHS->getType()->isFPOrFPVectorTy())
  3420. I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
  3421. else
  3422. I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
  3423. if (FMF.any())
  3424. I->setFastMathFlags(FMF);
  3425. InstructionList.push_back(I);
  3426. break;
  3427. }
  3428. case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
  3429. {
  3430. unsigned Size = Record.size();
  3431. if (Size == 0) {
  3432. I = ReturnInst::Create(Context);
  3433. InstructionList.push_back(I);
  3434. break;
  3435. }
  3436. unsigned OpNum = 0;
  3437. Value *Op = nullptr;
  3438. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  3439. return error("Invalid record");
  3440. if (OpNum != Record.size())
  3441. return error("Invalid record");
  3442. I = ReturnInst::Create(Context, Op);
  3443. InstructionList.push_back(I);
  3444. break;
  3445. }
  3446. case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
  3447. if (Record.size() != 1 && Record.size() != 3)
  3448. return error("Invalid record");
  3449. BasicBlock *TrueDest = getBasicBlock(Record[0]);
  3450. if (!TrueDest)
  3451. return error("Invalid record");
  3452. if (Record.size() == 1) {
  3453. I = BranchInst::Create(TrueDest);
  3454. InstructionList.push_back(I);
  3455. }
  3456. else {
  3457. BasicBlock *FalseDest = getBasicBlock(Record[1]);
  3458. Value *Cond = getValue(Record, 2, NextValueNo,
  3459. Type::getInt1Ty(Context));
  3460. if (!FalseDest || !Cond)
  3461. return error("Invalid record");
  3462. I = BranchInst::Create(TrueDest, FalseDest, Cond);
  3463. InstructionList.push_back(I);
  3464. }
  3465. break;
  3466. }
  3467. case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
  3468. // Check magic
  3469. if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
  3470. // "New" SwitchInst format with case ranges. The changes to write this
  3471. // format were reverted but we still recognize bitcode that uses it.
  3472. // Hopefully someday we will have support for case ranges and can use
  3473. // this format again.
  3474. Type *OpTy = getTypeByID(Record[1]);
  3475. unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
  3476. Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
  3477. BasicBlock *Default = getBasicBlock(Record[3]);
  3478. if (!OpTy || !Cond || !Default)
  3479. return error("Invalid record");
  3480. unsigned NumCases = Record[4];
  3481. SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
  3482. InstructionList.push_back(SI);
  3483. unsigned CurIdx = 5;
  3484. for (unsigned i = 0; i != NumCases; ++i) {
  3485. SmallVector<ConstantInt*, 1> CaseVals;
  3486. unsigned NumItems = Record[CurIdx++];
  3487. for (unsigned ci = 0; ci != NumItems; ++ci) {
  3488. bool isSingleNumber = Record[CurIdx++];
  3489. APInt Low;
  3490. unsigned ActiveWords = 1;
  3491. if (ValueBitWidth > 64)
  3492. ActiveWords = Record[CurIdx++];
  3493. Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
  3494. ValueBitWidth);
  3495. CurIdx += ActiveWords;
  3496. if (!isSingleNumber) {
  3497. ActiveWords = 1;
  3498. if (ValueBitWidth > 64)
  3499. ActiveWords = Record[CurIdx++];
  3500. APInt High = readWideAPInt(
  3501. makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
  3502. CurIdx += ActiveWords;
  3503. // FIXME: It is not clear whether values in the range should be
  3504. // compared as signed or unsigned values. The partially
  3505. // implemented changes that used this format in the past used
  3506. // unsigned comparisons.
  3507. for ( ; Low.ule(High); ++Low)
  3508. CaseVals.push_back(ConstantInt::get(Context, Low));
  3509. } else
  3510. CaseVals.push_back(ConstantInt::get(Context, Low));
  3511. }
  3512. BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
  3513. for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
  3514. cve = CaseVals.end(); cvi != cve; ++cvi)
  3515. SI->addCase(*cvi, DestBB);
  3516. }
  3517. I = SI;
  3518. break;
  3519. }
  3520. // Old SwitchInst format without case ranges.
  3521. if (Record.size() < 3 || (Record.size() & 1) == 0)
  3522. return error("Invalid record");
  3523. Type *OpTy = getTypeByID(Record[0]);
  3524. Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
  3525. BasicBlock *Default = getBasicBlock(Record[2]);
  3526. if (!OpTy || !Cond || !Default)
  3527. return error("Invalid record");
  3528. unsigned NumCases = (Record.size()-3)/2;
  3529. SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
  3530. InstructionList.push_back(SI);
  3531. for (unsigned i = 0, e = NumCases; i != e; ++i) {
  3532. ConstantInt *CaseVal =
  3533. dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
  3534. BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
  3535. if (!CaseVal || !DestBB) {
  3536. delete SI;
  3537. return error("Invalid record");
  3538. }
  3539. SI->addCase(CaseVal, DestBB);
  3540. }
  3541. I = SI;
  3542. break;
  3543. }
  3544. case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
  3545. if (Record.size() < 2)
  3546. return error("Invalid record");
  3547. Type *OpTy = getTypeByID(Record[0]);
  3548. Value *Address = getValue(Record, 1, NextValueNo, OpTy);
  3549. if (!OpTy || !Address)
  3550. return error("Invalid record");
  3551. unsigned NumDests = Record.size()-2;
  3552. IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
  3553. InstructionList.push_back(IBI);
  3554. for (unsigned i = 0, e = NumDests; i != e; ++i) {
  3555. if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
  3556. IBI->addDestination(DestBB);
  3557. } else {
  3558. delete IBI;
  3559. return error("Invalid record");
  3560. }
  3561. }
  3562. I = IBI;
  3563. break;
  3564. }
  3565. case bitc::FUNC_CODE_INST_INVOKE: {
  3566. // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
  3567. if (Record.size() < 4)
  3568. return error("Invalid record");
  3569. unsigned OpNum = 0;
  3570. AttributeSet PAL = getAttributes(Record[OpNum++]);
  3571. unsigned CCInfo = Record[OpNum++];
  3572. BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
  3573. BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
  3574. FunctionType *FTy = nullptr;
  3575. if (CCInfo >> 13 & 1 &&
  3576. !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
  3577. return error("Explicit invoke type is not a function type");
  3578. Value *Callee;
  3579. if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
  3580. return error("Invalid record");
  3581. PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
  3582. if (!CalleeTy)
  3583. return error("Callee is not a pointer");
  3584. if (!FTy) {
  3585. FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
  3586. if (!FTy)
  3587. return error("Callee is not of pointer to function type");
  3588. } else if (CalleeTy->getElementType() != FTy)
  3589. return error("Explicit invoke type does not match pointee type of "
  3590. "callee operand");
  3591. if (Record.size() < FTy->getNumParams() + OpNum)
  3592. return error("Insufficient operands to call");
  3593. SmallVector<Value*, 16> Ops;
  3594. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
  3595. Ops.push_back(getValue(Record, OpNum, NextValueNo,
  3596. FTy->getParamType(i)));
  3597. if (!Ops.back())
  3598. return error("Invalid record");
  3599. }
  3600. if (!FTy->isVarArg()) {
  3601. if (Record.size() != OpNum)
  3602. return error("Invalid record");
  3603. } else {
  3604. // Read type/value pairs for varargs params.
  3605. while (OpNum != Record.size()) {
  3606. Value *Op;
  3607. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  3608. return error("Invalid record");
  3609. Ops.push_back(Op);
  3610. }
  3611. }
  3612. I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
  3613. InstructionList.push_back(I);
  3614. cast<InvokeInst>(I)
  3615. ->setCallingConv(static_cast<CallingConv::ID>(~(1U << 13) & CCInfo));
  3616. cast<InvokeInst>(I)->setAttributes(PAL);
  3617. break;
  3618. }
  3619. case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
  3620. unsigned Idx = 0;
  3621. Value *Val = nullptr;
  3622. if (getValueTypePair(Record, Idx, NextValueNo, Val))
  3623. return error("Invalid record");
  3624. I = ResumeInst::Create(Val);
  3625. InstructionList.push_back(I);
  3626. break;
  3627. }
  3628. case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
  3629. I = new UnreachableInst(Context);
  3630. InstructionList.push_back(I);
  3631. break;
  3632. case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
  3633. if (Record.size() < 1 || ((Record.size()-1)&1))
  3634. return error("Invalid record");
  3635. Type *Ty = getTypeByID(Record[0]);
  3636. if (!Ty)
  3637. return error("Invalid record");
  3638. PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
  3639. InstructionList.push_back(PN);
  3640. for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
  3641. Value *V;
  3642. // With the new function encoding, it is possible that operands have
  3643. // negative IDs (for forward references). Use a signed VBR
  3644. // representation to keep the encoding small.
  3645. if (UseRelativeIDs)
  3646. V = getValueSigned(Record, 1+i, NextValueNo, Ty);
  3647. else
  3648. V = getValue(Record, 1+i, NextValueNo, Ty);
  3649. BasicBlock *BB = getBasicBlock(Record[2+i]);
  3650. if (!V || !BB)
  3651. return error("Invalid record");
  3652. PN->addIncoming(V, BB);
  3653. }
  3654. I = PN;
  3655. break;
  3656. }
  3657. case bitc::FUNC_CODE_INST_LANDINGPAD:
  3658. case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
  3659. // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
  3660. unsigned Idx = 0;
  3661. if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
  3662. if (Record.size() < 3)
  3663. return error("Invalid record");
  3664. } else {
  3665. assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
  3666. if (Record.size() < 4)
  3667. return error("Invalid record");
  3668. }
  3669. Type *Ty = getTypeByID(Record[Idx++]);
  3670. if (!Ty)
  3671. return error("Invalid record");
  3672. if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
  3673. Value *PersFn = nullptr;
  3674. if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
  3675. return error("Invalid record");
  3676. if (!F->hasPersonalityFn())
  3677. F->setPersonalityFn(cast<Constant>(PersFn));
  3678. else if (F->getPersonalityFn() != cast<Constant>(PersFn))
  3679. return error("Personality function mismatch");
  3680. }
  3681. bool IsCleanup = !!Record[Idx++];
  3682. unsigned NumClauses = Record[Idx++];
  3683. LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
  3684. LP->setCleanup(IsCleanup);
  3685. for (unsigned J = 0; J != NumClauses; ++J) {
  3686. LandingPadInst::ClauseType CT =
  3687. LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
  3688. Value *Val;
  3689. if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
  3690. delete LP;
  3691. return error("Invalid record");
  3692. }
  3693. assert((CT != LandingPadInst::Catch ||
  3694. !isa<ArrayType>(Val->getType())) &&
  3695. "Catch clause has a invalid type!");
  3696. assert((CT != LandingPadInst::Filter ||
  3697. isa<ArrayType>(Val->getType())) &&
  3698. "Filter clause has invalid type!");
  3699. LP->addClause(cast<Constant>(Val));
  3700. }
  3701. I = LP;
  3702. InstructionList.push_back(I);
  3703. break;
  3704. }
  3705. case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
  3706. if (Record.size() != 4)
  3707. return error("Invalid record");
  3708. uint64_t AlignRecord = Record[3];
  3709. const uint64_t InAllocaMask = uint64_t(1) << 5;
  3710. const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
  3711. const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
  3712. bool InAlloca = AlignRecord & InAllocaMask;
  3713. Type *Ty = getTypeByID(Record[0]);
  3714. if ((AlignRecord & ExplicitTypeMask) == 0) {
  3715. auto *PTy = dyn_cast_or_null<PointerType>(Ty);
  3716. if (!PTy)
  3717. return error("Old-style alloca with a non-pointer type");
  3718. Ty = PTy->getElementType();
  3719. }
  3720. Type *OpTy = getTypeByID(Record[1]);
  3721. Value *Size = getFnValueByID(Record[2], OpTy);
  3722. unsigned Align;
  3723. if (std::error_code EC =
  3724. parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
  3725. return EC;
  3726. }
  3727. if (!Ty || !Size)
  3728. return error("Invalid record");
  3729. AllocaInst *AI = new AllocaInst(Ty, Size, Align);
  3730. AI->setUsedWithInAlloca(InAlloca);
  3731. I = AI;
  3732. InstructionList.push_back(I);
  3733. break;
  3734. }
  3735. case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
  3736. unsigned OpNum = 0;
  3737. Value *Op;
  3738. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  3739. (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
  3740. return error("Invalid record");
  3741. Type *Ty = nullptr;
  3742. if (OpNum + 3 == Record.size())
  3743. Ty = getTypeByID(Record[OpNum++]);
  3744. if (std::error_code EC =
  3745. typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
  3746. return EC;
  3747. if (!Ty)
  3748. Ty = cast<PointerType>(Op->getType())->getElementType();
  3749. unsigned Align;
  3750. if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
  3751. return EC;
  3752. I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
  3753. InstructionList.push_back(I);
  3754. break;
  3755. }
  3756. case bitc::FUNC_CODE_INST_LOADATOMIC: {
  3757. // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
  3758. unsigned OpNum = 0;
  3759. Value *Op;
  3760. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  3761. (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
  3762. return error("Invalid record");
  3763. Type *Ty = nullptr;
  3764. if (OpNum + 5 == Record.size())
  3765. Ty = getTypeByID(Record[OpNum++]);
  3766. if (std::error_code EC =
  3767. typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
  3768. return EC;
  3769. if (!Ty)
  3770. Ty = cast<PointerType>(Op->getType())->getElementType();
  3771. AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
  3772. if (Ordering == NotAtomic || Ordering == Release ||
  3773. Ordering == AcquireRelease)
  3774. return error("Invalid record");
  3775. if (Ordering != NotAtomic && Record[OpNum] == 0)
  3776. return error("Invalid record");
  3777. SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
  3778. unsigned Align;
  3779. if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
  3780. return EC;
  3781. I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
  3782. InstructionList.push_back(I);
  3783. break;
  3784. }
  3785. case bitc::FUNC_CODE_INST_STORE:
  3786. case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
  3787. unsigned OpNum = 0;
  3788. Value *Val, *Ptr;
  3789. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
  3790. (BitCode == bitc::FUNC_CODE_INST_STORE
  3791. ? getValueTypePair(Record, OpNum, NextValueNo, Val)
  3792. : popValue(Record, OpNum, NextValueNo,
  3793. cast<PointerType>(Ptr->getType())->getElementType(),
  3794. Val)) ||
  3795. OpNum + 2 != Record.size())
  3796. return error("Invalid record");
  3797. if (std::error_code EC = typeCheckLoadStoreInst(
  3798. DiagnosticHandler, Val->getType(), Ptr->getType()))
  3799. return EC;
  3800. unsigned Align;
  3801. if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
  3802. return EC;
  3803. I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
  3804. InstructionList.push_back(I);
  3805. break;
  3806. }
  3807. case bitc::FUNC_CODE_INST_STOREATOMIC:
  3808. case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
  3809. // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
  3810. unsigned OpNum = 0;
  3811. Value *Val, *Ptr;
  3812. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
  3813. (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
  3814. ? getValueTypePair(Record, OpNum, NextValueNo, Val)
  3815. : popValue(Record, OpNum, NextValueNo,
  3816. cast<PointerType>(Ptr->getType())->getElementType(),
  3817. Val)) ||
  3818. OpNum + 4 != Record.size())
  3819. return error("Invalid record");
  3820. if (std::error_code EC = typeCheckLoadStoreInst(
  3821. DiagnosticHandler, Val->getType(), Ptr->getType()))
  3822. return EC;
  3823. AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
  3824. if (Ordering == NotAtomic || Ordering == Acquire ||
  3825. Ordering == AcquireRelease)
  3826. return error("Invalid record");
  3827. SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
  3828. if (Ordering != NotAtomic && Record[OpNum] == 0)
  3829. return error("Invalid record");
  3830. unsigned Align;
  3831. if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
  3832. return EC;
  3833. I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
  3834. InstructionList.push_back(I);
  3835. break;
  3836. }
  3837. case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
  3838. case bitc::FUNC_CODE_INST_CMPXCHG: {
  3839. // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
  3840. // failureordering?, isweak?]
  3841. unsigned OpNum = 0;
  3842. Value *Ptr, *Cmp, *New;
  3843. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
  3844. (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
  3845. ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
  3846. : popValue(Record, OpNum, NextValueNo,
  3847. cast<PointerType>(Ptr->getType())->getElementType(),
  3848. Cmp)) ||
  3849. popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
  3850. Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
  3851. return error("Invalid record");
  3852. AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
  3853. if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
  3854. return error("Invalid record");
  3855. SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
  3856. if (std::error_code EC = typeCheckLoadStoreInst(
  3857. DiagnosticHandler, Cmp->getType(), Ptr->getType()))
  3858. return EC;
  3859. AtomicOrdering FailureOrdering;
  3860. if (Record.size() < 7)
  3861. FailureOrdering =
  3862. AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
  3863. else
  3864. FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
  3865. I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
  3866. SynchScope);
  3867. cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
  3868. if (Record.size() < 8) {
  3869. // Before weak cmpxchgs existed, the instruction simply returned the
  3870. // value loaded from memory, so bitcode files from that era will be
  3871. // expecting the first component of a modern cmpxchg.
  3872. CurBB->getInstList().push_back(I);
  3873. I = ExtractValueInst::Create(I, 0);
  3874. } else {
  3875. cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
  3876. }
  3877. InstructionList.push_back(I);
  3878. break;
  3879. }
  3880. case bitc::FUNC_CODE_INST_ATOMICRMW: {
  3881. // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
  3882. unsigned OpNum = 0;
  3883. Value *Ptr, *Val;
  3884. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
  3885. popValue(Record, OpNum, NextValueNo,
  3886. cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
  3887. OpNum+4 != Record.size())
  3888. return error("Invalid record");
  3889. AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
  3890. if (Operation < AtomicRMWInst::FIRST_BINOP ||
  3891. Operation > AtomicRMWInst::LAST_BINOP)
  3892. return error("Invalid record");
  3893. AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
  3894. if (Ordering == NotAtomic || Ordering == Unordered)
  3895. return error("Invalid record");
  3896. SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
  3897. I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
  3898. cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
  3899. InstructionList.push_back(I);
  3900. break;
  3901. }
  3902. case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
  3903. if (2 != Record.size())
  3904. return error("Invalid record");
  3905. AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
  3906. if (Ordering == NotAtomic || Ordering == Unordered ||
  3907. Ordering == Monotonic)
  3908. return error("Invalid record");
  3909. SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
  3910. I = new FenceInst(Context, Ordering, SynchScope);
  3911. InstructionList.push_back(I);
  3912. break;
  3913. }
  3914. case bitc::FUNC_CODE_INST_CALL: {
  3915. // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
  3916. if (Record.size() < 3)
  3917. return error("Invalid record");
  3918. unsigned OpNum = 0;
  3919. AttributeSet PAL = getAttributes(Record[OpNum++]);
  3920. unsigned CCInfo = Record[OpNum++];
  3921. FunctionType *FTy = nullptr;
  3922. if (CCInfo >> 15 & 1 &&
  3923. !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
  3924. return error("Explicit call type is not a function type");
  3925. Value *Callee;
  3926. if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
  3927. return error("Invalid record");
  3928. PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
  3929. if (!OpTy)
  3930. return error("Callee is not a pointer type");
  3931. if (!FTy) {
  3932. FTy = dyn_cast<FunctionType>(OpTy->getElementType());
  3933. if (!FTy)
  3934. return error("Callee is not of pointer to function type");
  3935. } else if (OpTy->getElementType() != FTy)
  3936. return error("Explicit call type does not match pointee type of "
  3937. "callee operand");
  3938. if (Record.size() < FTy->getNumParams() + OpNum)
  3939. return error("Insufficient operands to call");
  3940. SmallVector<Value*, 16> Args;
  3941. // Read the fixed params.
  3942. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
  3943. if (FTy->getParamType(i)->isLabelTy())
  3944. Args.push_back(getBasicBlock(Record[OpNum]));
  3945. else
  3946. Args.push_back(getValue(Record, OpNum, NextValueNo,
  3947. FTy->getParamType(i)));
  3948. if (!Args.back())
  3949. return error("Invalid record");
  3950. }
  3951. // Read type/value pairs for varargs params.
  3952. if (!FTy->isVarArg()) {
  3953. if (OpNum != Record.size())
  3954. return error("Invalid record");
  3955. } else {
  3956. while (OpNum != Record.size()) {
  3957. Value *Op;
  3958. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  3959. return error("Invalid record");
  3960. Args.push_back(Op);
  3961. }
  3962. }
  3963. I = CallInst::Create(FTy, Callee, Args);
  3964. InstructionList.push_back(I);
  3965. cast<CallInst>(I)->setCallingConv(
  3966. static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
  3967. CallInst::TailCallKind TCK = CallInst::TCK_None;
  3968. if (CCInfo & 1)
  3969. TCK = CallInst::TCK_Tail;
  3970. if (CCInfo & (1 << 14))
  3971. TCK = CallInst::TCK_MustTail;
  3972. cast<CallInst>(I)->setTailCallKind(TCK);
  3973. cast<CallInst>(I)->setAttributes(PAL);
  3974. break;
  3975. }
  3976. case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
  3977. if (Record.size() < 3)
  3978. return error("Invalid record");
  3979. Type *OpTy = getTypeByID(Record[0]);
  3980. Value *Op = getValue(Record, 1, NextValueNo, OpTy);
  3981. Type *ResTy = getTypeByID(Record[2]);
  3982. if (!OpTy || !Op || !ResTy)
  3983. return error("Invalid record");
  3984. I = new VAArgInst(Op, ResTy);
  3985. InstructionList.push_back(I);
  3986. break;
  3987. }
  3988. }
  3989. // Add instruction to end of current BB. If there is no current BB, reject
  3990. // this file.
  3991. if (!CurBB) {
  3992. delete I;
  3993. return error("Invalid instruction with no BB");
  3994. }
  3995. CurBB->getInstList().push_back(I);
  3996. // If this was a terminator instruction, move to the next block.
  3997. if (isa<TerminatorInst>(I)) {
  3998. ++CurBBNo;
  3999. CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
  4000. }
  4001. // Non-void values get registered in the value table for future use.
  4002. if (I && !I->getType()->isVoidTy())
  4003. ValueList.assignValue(I, NextValueNo++);
  4004. }
  4005. OutOfRecordLoop:
  4006. // Check the function list for unresolved values.
  4007. if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
  4008. if (!A->getParent()) {
  4009. // We found at least one unresolved value. Nuke them all to avoid leaks.
  4010. for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
  4011. if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
  4012. A->replaceAllUsesWith(UndefValue::get(A->getType()));
  4013. delete A;
  4014. }
  4015. }
  4016. return error("Never resolved value found in function");
  4017. }
  4018. }
  4019. // FIXME: Check for unresolved forward-declared metadata references
  4020. // and clean up leaks.
  4021. // Trim the value list down to the size it was before we parsed this function.
  4022. ValueList.shrinkTo(ModuleValueListSize);
  4023. MDValueList.shrinkTo(ModuleMDValueListSize);
  4024. std::vector<BasicBlock*>().swap(FunctionBBs);
  4025. return std::error_code();
  4026. }
  4027. /// Find the function body in the bitcode stream
  4028. std::error_code BitcodeReader::findFunctionInStream(
  4029. Function *F,
  4030. DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
  4031. while (DeferredFunctionInfoIterator->second == 0) {
  4032. if (Stream.AtEndOfStream())
  4033. return error("Could not find function in stream");
  4034. // ParseModule will parse the next body in the stream and set its
  4035. // position in the DeferredFunctionInfo map.
  4036. if (std::error_code EC = parseModule(true))
  4037. return EC;
  4038. }
  4039. return std::error_code();
  4040. }
  4041. //===----------------------------------------------------------------------===//
  4042. // GVMaterializer implementation
  4043. //===----------------------------------------------------------------------===//
  4044. void BitcodeReader::releaseBuffer() { Buffer.release(); }
  4045. std::error_code BitcodeReader::materialize(GlobalValue *GV) {
  4046. if (std::error_code EC = materializeMetadata())
  4047. return EC;
  4048. Function *F = dyn_cast<Function>(GV);
  4049. // If it's not a function or is already material, ignore the request.
  4050. if (!F || !F->isMaterializable())
  4051. return std::error_code();
  4052. DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
  4053. assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
  4054. // If its position is recorded as 0, its body is somewhere in the stream
  4055. // but we haven't seen it yet.
  4056. if (DFII->second == 0)
  4057. if (std::error_code EC = findFunctionInStream(F, DFII))
  4058. return EC;
  4059. // Move the bit stream to the saved position of the deferred function body.
  4060. Stream.JumpToBit(DFII->second);
  4061. if (std::error_code EC = parseFunctionBody(F))
  4062. return EC;
  4063. F->setIsMaterializable(false);
  4064. if (StripDebugInfo)
  4065. stripDebugInfo(*F);
  4066. // Upgrade any old intrinsic calls in the function.
  4067. for (auto &I : UpgradedIntrinsics) {
  4068. for (auto UI = I.first->user_begin(), UE = I.first->user_end(); UI != UE;) {
  4069. User *U = *UI;
  4070. ++UI;
  4071. if (CallInst *CI = dyn_cast<CallInst>(U))
  4072. UpgradeIntrinsicCall(CI, I.second);
  4073. }
  4074. }
  4075. // Bring in any functions that this function forward-referenced via
  4076. // blockaddresses.
  4077. return materializeForwardReferencedFunctions();
  4078. }
  4079. bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
  4080. const Function *F = dyn_cast<Function>(GV);
  4081. if (!F || F->isDeclaration())
  4082. return false;
  4083. // Dematerializing F would leave dangling references that wouldn't be
  4084. // reconnected on re-materialization.
  4085. if (BlockAddressesTaken.count(F))
  4086. return false;
  4087. return DeferredFunctionInfo.count(const_cast<Function*>(F));
  4088. }
  4089. void BitcodeReader::dematerialize(GlobalValue *GV) {
  4090. Function *F = dyn_cast<Function>(GV);
  4091. // If this function isn't dematerializable, this is a noop.
  4092. if (!F || !isDematerializable(F))
  4093. return;
  4094. assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
  4095. // Just forget the function body, we can remat it later.
  4096. F->dropAllReferences();
  4097. F->setIsMaterializable(true);
  4098. }
  4099. std::error_code BitcodeReader::materializeModule(Module *M) {
  4100. assert(M == TheModule &&
  4101. "Can only Materialize the Module this BitcodeReader is attached to.");
  4102. if (std::error_code EC = materializeMetadata())
  4103. return EC;
  4104. // Promise to materialize all forward references.
  4105. WillMaterializeAllForwardRefs = true;
  4106. // Iterate over the module, deserializing any functions that are still on
  4107. // disk.
  4108. for (Module::iterator F = TheModule->begin(), E = TheModule->end();
  4109. F != E; ++F) {
  4110. if (std::error_code EC = materialize(F))
  4111. return EC;
  4112. }
  4113. // At this point, if there are any function bodies, the current bit is
  4114. // pointing to the END_BLOCK record after them. Now make sure the rest
  4115. // of the bits in the module have been read.
  4116. if (NextUnreadBit)
  4117. parseModule(true);
  4118. // Check that all block address forward references got resolved (as we
  4119. // promised above).
  4120. if (!BasicBlockFwdRefs.empty())
  4121. return error("Never resolved function from blockaddress");
  4122. // Upgrade any intrinsic calls that slipped through (should not happen!) and
  4123. // delete the old functions to clean up. We can't do this unless the entire
  4124. // module is materialized because there could always be another function body
  4125. // with calls to the old function.
  4126. for (auto &I : UpgradedIntrinsics) {
  4127. for (auto *U : I.first->users()) {
  4128. if (CallInst *CI = dyn_cast<CallInst>(U))
  4129. UpgradeIntrinsicCall(CI, I.second);
  4130. }
  4131. if (!I.first->use_empty())
  4132. I.first->replaceAllUsesWith(I.second);
  4133. I.first->eraseFromParent();
  4134. }
  4135. UpgradedIntrinsics.clear();
  4136. for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
  4137. UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
  4138. UpgradeDebugInfo(*M);
  4139. // HLSL Change Starts
  4140. if (!Tracker.isDense((uint64_t)(Buffer->getBufferSize()) * 8)) {
  4141. ReportWarning(DiagnosticHandler, "Unused bits in buffer.");
  4142. }
  4143. // HLSL Change Ends
  4144. return std::error_code();
  4145. }
  4146. std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
  4147. return IdentifiedStructTypes;
  4148. }
  4149. std::error_code
  4150. BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
  4151. if (Streamer)
  4152. return initLazyStream(std::move(Streamer));
  4153. return initStreamFromBuffer();
  4154. }
  4155. std::error_code BitcodeReader::initStreamFromBuffer() {
  4156. const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
  4157. const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
  4158. if (Buffer->getBufferSize() & 3)
  4159. return error("Invalid bitcode size"); // HLSL Change - bitcode size is the problem, not the signature per se
  4160. // If we have a wrapper header, parse it and ignore the non-bc file contents.
  4161. // The magic number is 0x0B17C0DE stored in little endian.
  4162. if (isBitcodeWrapper(BufPtr, BufEnd))
  4163. if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
  4164. return error("Invalid bitcode wrapper header");
  4165. StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
  4166. StreamFile->Tracker = &Tracker; // HLSL Change
  4167. Stream.init(&*StreamFile);
  4168. return std::error_code();
  4169. }
  4170. std::error_code
  4171. BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
  4172. // Check and strip off the bitcode wrapper; BitstreamReader expects never to
  4173. // see it.
  4174. auto OwnedBytes =
  4175. llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
  4176. StreamingMemoryObject &Bytes = *OwnedBytes;
  4177. StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
  4178. Stream.init(&*StreamFile);
  4179. unsigned char buf[16];
  4180. if (Bytes.readBytes(buf, 16, 0) != 16)
  4181. return error("Invalid bitcode signature");
  4182. if (!isBitcode(buf, buf + 16))
  4183. return error("Invalid bitcode signature");
  4184. if (isBitcodeWrapper(buf, buf + 4)) {
  4185. const unsigned char *bitcodeStart = buf;
  4186. const unsigned char *bitcodeEnd = buf + 16;
  4187. SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
  4188. Bytes.dropLeadingBytes(bitcodeStart - buf);
  4189. Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
  4190. }
  4191. return std::error_code();
  4192. }
  4193. namespace {
  4194. class BitcodeErrorCategoryType : public std::error_category {
  4195. const char *name() const LLVM_NOEXCEPT override {
  4196. return "llvm.bitcode";
  4197. }
  4198. std::string message(int IE) const override {
  4199. BitcodeError E = static_cast<BitcodeError>(IE);
  4200. switch (E) {
  4201. case BitcodeError::InvalidBitcodeSignature:
  4202. return "Invalid bitcode signature";
  4203. case BitcodeError::CorruptedBitcode:
  4204. return "Corrupted bitcode";
  4205. }
  4206. llvm_unreachable("Unknown error type!");
  4207. }
  4208. };
  4209. }
  4210. static BitcodeErrorCategoryType g_ErrorCategory; // HLSL Change - not a ManagedStatic
  4211. const std::error_category &llvm::BitcodeErrorCategory() {
  4212. return g_ErrorCategory; // HLSL Change - simple global
  4213. }
  4214. //===----------------------------------------------------------------------===//
  4215. // External interface
  4216. //===----------------------------------------------------------------------===//
  4217. static ErrorOr<std::unique_ptr<Module>>
  4218. getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
  4219. BitcodeReader *R, LLVMContext &Context,
  4220. bool MaterializeAll, bool ShouldLazyLoadMetadata) {
  4221. std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
  4222. M->setMaterializer(R);
  4223. auto cleanupOnError = [&](std::error_code EC) {
  4224. R->releaseBuffer(); // Never take ownership on error.
  4225. return EC;
  4226. };
  4227. // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
  4228. if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
  4229. ShouldLazyLoadMetadata))
  4230. return cleanupOnError(EC);
  4231. if (MaterializeAll) {
  4232. // Read in the entire module, and destroy the BitcodeReader.
  4233. if (std::error_code EC = M->materializeAllPermanently())
  4234. return cleanupOnError(EC);
  4235. } else {
  4236. // Resolve forward references from blockaddresses.
  4237. if (std::error_code EC = R->materializeForwardReferencedFunctions())
  4238. return cleanupOnError(EC);
  4239. }
  4240. return std::move(M);
  4241. }
  4242. /// \brief Get a lazy one-at-time loading module from bitcode.
  4243. ///
  4244. /// This isn't always used in a lazy context. In particular, it's also used by
  4245. /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
  4246. /// in forward-referenced functions from block address references.
  4247. ///
  4248. /// \param[in] MaterializeAll Set to \c true if we should materialize
  4249. /// everything.
  4250. static ErrorOr<std::unique_ptr<Module>>
  4251. getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
  4252. LLVMContext &Context, bool MaterializeAll,
  4253. DiagnosticHandlerFunction DiagnosticHandler,
  4254. bool ShouldLazyLoadMetadata = false) {
  4255. BitcodeReader *R =
  4256. new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
  4257. ErrorOr<std::unique_ptr<Module>> Ret =
  4258. getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
  4259. MaterializeAll, ShouldLazyLoadMetadata);
  4260. if (!Ret)
  4261. return Ret;
  4262. Buffer.release(); // The BitcodeReader owns it now.
  4263. return Ret;
  4264. }
  4265. ErrorOr<std::unique_ptr<Module>> llvm::getLazyBitcodeModule(
  4266. std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
  4267. DiagnosticHandlerFunction DiagnosticHandler, bool ShouldLazyLoadMetadata) {
  4268. return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
  4269. DiagnosticHandler, ShouldLazyLoadMetadata);
  4270. }
  4271. ErrorOr<std::unique_ptr<Module>> llvm::getStreamedBitcodeModule(
  4272. StringRef Name, std::unique_ptr<DataStreamer> Streamer,
  4273. LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler) {
  4274. std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
  4275. BitcodeReader *R = new BitcodeReader(Context, DiagnosticHandler);
  4276. return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
  4277. false);
  4278. }
  4279. // HLSL Change Starts
  4280. struct report_fatal_error_data {
  4281. report_fatal_error_data(DiagnosticHandlerFunction DH)
  4282. : DiagnosticHandler(DH) {}
  4283. DiagnosticHandlerFunction DiagnosticHandler;
  4284. };
  4285. void report_fatal_error_handler(void *user_datam, const std::string &reason,
  4286. bool gen_crash_diag) {
  4287. report_fatal_error_data *data = (report_fatal_error_data *)user_datam;
  4288. BitcodeDiagnosticInfo BDI(std::error_code(EINVAL, std::system_category()),
  4289. DiagnosticSeverity::DS_Error, reason);
  4290. data->DiagnosticHandler(BDI);
  4291. throw std::exception("Invalid bitcode");
  4292. }
  4293. // HLSL Change Ends
  4294. ErrorOr<std::unique_ptr<Module>>
  4295. llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
  4296. DiagnosticHandlerFunction DiagnosticHandler) {
  4297. // HLSL Change Starts - introduce a ScopedFatalErrorHandler to handle
  4298. // report_fatal_error from readers.
  4299. report_fatal_error_data data(DiagnosticHandler);
  4300. ScopedFatalErrorHandler SFE(report_fatal_error_handler, &data);
  4301. // HLSL Change Ends
  4302. std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
  4303. return getLazyBitcodeModuleImpl(std::move(Buf), Context, true,
  4304. DiagnosticHandler);
  4305. // TODO: Restore the use-lists to the in-memory state when the bitcode was
  4306. // written. We must defer until the Module has been fully materialized.
  4307. }
  4308. std::string
  4309. llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
  4310. DiagnosticHandlerFunction DiagnosticHandler) {
  4311. std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
  4312. auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
  4313. DiagnosticHandler);
  4314. ErrorOr<std::string> Triple = R->parseTriple();
  4315. if (Triple.getError())
  4316. return "";
  4317. return Triple.get();
  4318. }