BitcodeWriter.cpp 176 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635
  1. //===- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Bitcode writer implementation.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Bitcode/BitcodeWriter.h"
  13. #include "ValueEnumerator.h"
  14. #include "llvm/ADT/APFloat.h"
  15. #include "llvm/ADT/APInt.h"
  16. #include "llvm/ADT/ArrayRef.h"
  17. #include "llvm/ADT/DenseMap.h"
  18. #include "llvm/ADT/None.h"
  19. #include "llvm/ADT/Optional.h"
  20. #include "llvm/ADT/STLExtras.h"
  21. #include "llvm/ADT/SmallString.h"
  22. #include "llvm/ADT/SmallVector.h"
  23. #include "llvm/ADT/StringMap.h"
  24. #include "llvm/ADT/StringRef.h"
  25. #include "llvm/ADT/Triple.h"
  26. #include "llvm/Bitstream/BitCodes.h"
  27. #include "llvm/Bitstream/BitstreamWriter.h"
  28. #include "llvm/Bitcode/LLVMBitCodes.h"
  29. #include "llvm/Config/llvm-config.h"
  30. #include "llvm/IR/Attributes.h"
  31. #include "llvm/IR/BasicBlock.h"
  32. #include "llvm/IR/CallSite.h"
  33. #include "llvm/IR/Comdat.h"
  34. #include "llvm/IR/Constant.h"
  35. #include "llvm/IR/Constants.h"
  36. #include "llvm/IR/DebugInfoMetadata.h"
  37. #include "llvm/IR/DebugLoc.h"
  38. #include "llvm/IR/DerivedTypes.h"
  39. #include "llvm/IR/Function.h"
  40. #include "llvm/IR/GlobalAlias.h"
  41. #include "llvm/IR/GlobalIFunc.h"
  42. #include "llvm/IR/GlobalObject.h"
  43. #include "llvm/IR/GlobalValue.h"
  44. #include "llvm/IR/GlobalVariable.h"
  45. #include "llvm/IR/InlineAsm.h"
  46. #include "llvm/IR/InstrTypes.h"
  47. #include "llvm/IR/Instruction.h"
  48. #include "llvm/IR/Instructions.h"
  49. #include "llvm/IR/LLVMContext.h"
  50. #include "llvm/IR/Metadata.h"
  51. #include "llvm/IR/Module.h"
  52. #include "llvm/IR/ModuleSummaryIndex.h"
  53. #include "llvm/IR/Operator.h"
  54. #include "llvm/IR/Type.h"
  55. #include "llvm/IR/UseListOrder.h"
  56. #include "llvm/IR/Value.h"
  57. #include "llvm/IR/ValueSymbolTable.h"
  58. #include "llvm/MC/StringTableBuilder.h"
  59. #include "llvm/Object/IRSymtab.h"
  60. #include "llvm/Support/AtomicOrdering.h"
  61. #include "llvm/Support/Casting.h"
  62. #include "llvm/Support/CommandLine.h"
  63. #include "llvm/Support/Endian.h"
  64. #include "llvm/Support/Error.h"
  65. #include "llvm/Support/ErrorHandling.h"
  66. #include "llvm/Support/MathExtras.h"
  67. #include "llvm/Support/SHA1.h"
  68. #include "llvm/Support/TargetRegistry.h"
  69. #include "llvm/Support/raw_ostream.h"
  70. #include <algorithm>
  71. #include <cassert>
  72. #include <cstddef>
  73. #include <cstdint>
  74. #include <iterator>
  75. #include <map>
  76. #include <memory>
  77. #include <string>
  78. #include <utility>
  79. #include <vector>
  80. using namespace llvm;
  81. static cl::opt<unsigned>
  82. IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),
  83. cl::desc("Number of metadatas above which we emit an index "
  84. "to enable lazy-loading"));
  85. cl::opt<bool> WriteRelBFToSummary(
  86. "write-relbf-to-summary", cl::Hidden, cl::init(false),
  87. cl::desc("Write relative block frequency to function summary "));
  88. extern FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold;
  89. namespace {
  90. /// These are manifest constants used by the bitcode writer. They do not need to
  91. /// be kept in sync with the reader, but need to be consistent within this file.
  92. enum {
  93. // VALUE_SYMTAB_BLOCK abbrev id's.
  94. VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
  95. VST_ENTRY_7_ABBREV,
  96. VST_ENTRY_6_ABBREV,
  97. VST_BBENTRY_6_ABBREV,
  98. // CONSTANTS_BLOCK abbrev id's.
  99. CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
  100. CONSTANTS_INTEGER_ABBREV,
  101. CONSTANTS_CE_CAST_Abbrev,
  102. CONSTANTS_NULL_Abbrev,
  103. // FUNCTION_BLOCK abbrev id's.
  104. FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
  105. FUNCTION_INST_UNOP_ABBREV,
  106. FUNCTION_INST_UNOP_FLAGS_ABBREV,
  107. FUNCTION_INST_BINOP_ABBREV,
  108. FUNCTION_INST_BINOP_FLAGS_ABBREV,
  109. FUNCTION_INST_CAST_ABBREV,
  110. FUNCTION_INST_RET_VOID_ABBREV,
  111. FUNCTION_INST_RET_VAL_ABBREV,
  112. FUNCTION_INST_UNREACHABLE_ABBREV,
  113. FUNCTION_INST_GEP_ABBREV,
  114. };
  115. /// Abstract class to manage the bitcode writing, subclassed for each bitcode
  116. /// file type.
  117. class BitcodeWriterBase {
  118. protected:
  119. /// The stream created and owned by the client.
  120. BitstreamWriter &Stream;
  121. StringTableBuilder &StrtabBuilder;
  122. public:
  123. /// Constructs a BitcodeWriterBase object that writes to the provided
  124. /// \p Stream.
  125. BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
  126. : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
  127. protected:
  128. void writeBitcodeHeader();
  129. void writeModuleVersion();
  130. };
  131. void BitcodeWriterBase::writeModuleVersion() {
  132. // VERSION: [version#]
  133. Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});
  134. }
  135. /// Base class to manage the module bitcode writing, currently subclassed for
  136. /// ModuleBitcodeWriter and ThinLinkBitcodeWriter.
  137. class ModuleBitcodeWriterBase : public BitcodeWriterBase {
  138. protected:
  139. /// The Module to write to bitcode.
  140. const Module &M;
  141. /// Enumerates ids for all values in the module.
  142. ValueEnumerator VE;
  143. /// Optional per-module index to write for ThinLTO.
  144. const ModuleSummaryIndex *Index;
  145. /// Map that holds the correspondence between GUIDs in the summary index,
  146. /// that came from indirect call profiles, and a value id generated by this
  147. /// class to use in the VST and summary block records.
  148. std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
  149. /// Tracks the last value id recorded in the GUIDToValueMap.
  150. unsigned GlobalValueId;
  151. /// Saves the offset of the VSTOffset record that must eventually be
  152. /// backpatched with the offset of the actual VST.
  153. uint64_t VSTOffsetPlaceholder = 0;
  154. public:
  155. /// Constructs a ModuleBitcodeWriterBase object for the given Module,
  156. /// writing to the provided \p Buffer.
  157. ModuleBitcodeWriterBase(const Module &M, StringTableBuilder &StrtabBuilder,
  158. BitstreamWriter &Stream,
  159. bool ShouldPreserveUseListOrder,
  160. const ModuleSummaryIndex *Index)
  161. : BitcodeWriterBase(Stream, StrtabBuilder), M(M),
  162. VE(M, ShouldPreserveUseListOrder), Index(Index) {
  163. // Assign ValueIds to any callee values in the index that came from
  164. // indirect call profiles and were recorded as a GUID not a Value*
  165. // (which would have been assigned an ID by the ValueEnumerator).
  166. // The starting ValueId is just after the number of values in the
  167. // ValueEnumerator, so that they can be emitted in the VST.
  168. GlobalValueId = VE.getValues().size();
  169. if (!Index)
  170. return;
  171. for (const auto &GUIDSummaryLists : *Index)
  172. // Examine all summaries for this GUID.
  173. for (auto &Summary : GUIDSummaryLists.second.SummaryList)
  174. if (auto FS = dyn_cast<FunctionSummary>(Summary.get()))
  175. // For each call in the function summary, see if the call
  176. // is to a GUID (which means it is for an indirect call,
  177. // otherwise we would have a Value for it). If so, synthesize
  178. // a value id.
  179. for (auto &CallEdge : FS->calls())
  180. if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
  181. assignValueId(CallEdge.first.getGUID());
  182. }
  183. protected:
  184. void writePerModuleGlobalValueSummary();
  185. private:
  186. void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
  187. GlobalValueSummary *Summary,
  188. unsigned ValueID,
  189. unsigned FSCallsAbbrev,
  190. unsigned FSCallsProfileAbbrev,
  191. const Function &F);
  192. void writeModuleLevelReferences(const GlobalVariable &V,
  193. SmallVector<uint64_t, 64> &NameVals,
  194. unsigned FSModRefsAbbrev,
  195. unsigned FSModVTableRefsAbbrev);
  196. void assignValueId(GlobalValue::GUID ValGUID) {
  197. GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
  198. }
  199. unsigned getValueId(GlobalValue::GUID ValGUID) {
  200. const auto &VMI = GUIDToValueIdMap.find(ValGUID);
  201. // Expect that any GUID value had a value Id assigned by an
  202. // earlier call to assignValueId.
  203. assert(VMI != GUIDToValueIdMap.end() &&
  204. "GUID does not have assigned value Id");
  205. return VMI->second;
  206. }
  207. // Helper to get the valueId for the type of value recorded in VI.
  208. unsigned getValueId(ValueInfo VI) {
  209. if (!VI.haveGVs() || !VI.getValue())
  210. return getValueId(VI.getGUID());
  211. return VE.getValueID(VI.getValue());
  212. }
  213. std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
  214. };
  215. /// Class to manage the bitcode writing for a module.
  216. class ModuleBitcodeWriter : public ModuleBitcodeWriterBase {
  217. /// Pointer to the buffer allocated by caller for bitcode writing.
  218. const SmallVectorImpl<char> &Buffer;
  219. /// True if a module hash record should be written.
  220. bool GenerateHash;
  221. /// If non-null, when GenerateHash is true, the resulting hash is written
  222. /// into ModHash.
  223. ModuleHash *ModHash;
  224. SHA1 Hasher;
  225. /// The start bit of the identification block.
  226. uint64_t BitcodeStartBit;
  227. public:
  228. /// Constructs a ModuleBitcodeWriter object for the given Module,
  229. /// writing to the provided \p Buffer.
  230. ModuleBitcodeWriter(const Module &M, SmallVectorImpl<char> &Buffer,
  231. StringTableBuilder &StrtabBuilder,
  232. BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
  233. const ModuleSummaryIndex *Index, bool GenerateHash,
  234. ModuleHash *ModHash = nullptr)
  235. : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
  236. ShouldPreserveUseListOrder, Index),
  237. Buffer(Buffer), GenerateHash(GenerateHash), ModHash(ModHash),
  238. BitcodeStartBit(Stream.GetCurrentBitNo()) {}
  239. /// Emit the current module to the bitstream.
  240. void write();
  241. private:
  242. uint64_t bitcodeStartBit() { return BitcodeStartBit; }
  243. size_t addToStrtab(StringRef Str);
  244. void writeAttributeGroupTable();
  245. void writeAttributeTable();
  246. void writeTypeTable();
  247. void writeComdats();
  248. void writeValueSymbolTableForwardDecl();
  249. void writeModuleInfo();
  250. void writeValueAsMetadata(const ValueAsMetadata *MD,
  251. SmallVectorImpl<uint64_t> &Record);
  252. void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,
  253. unsigned Abbrev);
  254. unsigned createDILocationAbbrev();
  255. void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,
  256. unsigned &Abbrev);
  257. unsigned createGenericDINodeAbbrev();
  258. void writeGenericDINode(const GenericDINode *N,
  259. SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
  260. void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,
  261. unsigned Abbrev);
  262. void writeDIEnumerator(const DIEnumerator *N,
  263. SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
  264. void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,
  265. unsigned Abbrev);
  266. void writeDIDerivedType(const DIDerivedType *N,
  267. SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
  268. void writeDICompositeType(const DICompositeType *N,
  269. SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
  270. void writeDISubroutineType(const DISubroutineType *N,
  271. SmallVectorImpl<uint64_t> &Record,
  272. unsigned Abbrev);
  273. void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,
  274. unsigned Abbrev);
  275. void writeDICompileUnit(const DICompileUnit *N,
  276. SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
  277. void writeDISubprogram(const DISubprogram *N,
  278. SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
  279. void writeDILexicalBlock(const DILexicalBlock *N,
  280. SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
  281. void writeDILexicalBlockFile(const DILexicalBlockFile *N,
  282. SmallVectorImpl<uint64_t> &Record,
  283. unsigned Abbrev);
  284. void writeDICommonBlock(const DICommonBlock *N,
  285. SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
  286. void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,
  287. unsigned Abbrev);
  288. void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,
  289. unsigned Abbrev);
  290. void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,
  291. unsigned Abbrev);
  292. void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,
  293. unsigned Abbrev);
  294. void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
  295. SmallVectorImpl<uint64_t> &Record,
  296. unsigned Abbrev);
  297. void writeDITemplateValueParameter(const DITemplateValueParameter *N,
  298. SmallVectorImpl<uint64_t> &Record,
  299. unsigned Abbrev);
  300. void writeDIGlobalVariable(const DIGlobalVariable *N,
  301. SmallVectorImpl<uint64_t> &Record,
  302. unsigned Abbrev);
  303. void writeDILocalVariable(const DILocalVariable *N,
  304. SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
  305. void writeDILabel(const DILabel *N,
  306. SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
  307. void writeDIExpression(const DIExpression *N,
  308. SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
  309. void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,
  310. SmallVectorImpl<uint64_t> &Record,
  311. unsigned Abbrev);
  312. void writeDIObjCProperty(const DIObjCProperty *N,
  313. SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
  314. void writeDIImportedEntity(const DIImportedEntity *N,
  315. SmallVectorImpl<uint64_t> &Record,
  316. unsigned Abbrev);
  317. unsigned createNamedMetadataAbbrev();
  318. void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
  319. unsigned createMetadataStringsAbbrev();
  320. void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
  321. SmallVectorImpl<uint64_t> &Record);
  322. void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
  323. SmallVectorImpl<uint64_t> &Record,
  324. std::vector<unsigned> *MDAbbrevs = nullptr,
  325. std::vector<uint64_t> *IndexPos = nullptr);
  326. void writeModuleMetadata();
  327. void writeFunctionMetadata(const Function &F);
  328. void writeFunctionMetadataAttachment(const Function &F);
  329. void writeGlobalVariableMetadataAttachment(const GlobalVariable &GV);
  330. void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
  331. const GlobalObject &GO);
  332. void writeModuleMetadataKinds();
  333. void writeOperandBundleTags();
  334. void writeSyncScopeNames();
  335. void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
  336. void writeModuleConstants();
  337. bool pushValueAndType(const Value *V, unsigned InstID,
  338. SmallVectorImpl<unsigned> &Vals);
  339. void writeOperandBundles(ImmutableCallSite CS, unsigned InstID);
  340. void pushValue(const Value *V, unsigned InstID,
  341. SmallVectorImpl<unsigned> &Vals);
  342. void pushValueSigned(const Value *V, unsigned InstID,
  343. SmallVectorImpl<uint64_t> &Vals);
  344. void writeInstruction(const Instruction &I, unsigned InstID,
  345. SmallVectorImpl<unsigned> &Vals);
  346. void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
  347. void writeGlobalValueSymbolTable(
  348. DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
  349. void writeUseList(UseListOrder &&Order);
  350. void writeUseListBlock(const Function *F);
  351. void
  352. writeFunction(const Function &F,
  353. DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
  354. void writeBlockInfo();
  355. void writeModuleHash(size_t BlockStartPos);
  356. unsigned getEncodedSyncScopeID(SyncScope::ID SSID) {
  357. return unsigned(SSID);
  358. }
  359. };
  360. /// Class to manage the bitcode writing for a combined index.
  361. class IndexBitcodeWriter : public BitcodeWriterBase {
  362. /// The combined index to write to bitcode.
  363. const ModuleSummaryIndex &Index;
  364. /// When writing a subset of the index for distributed backends, client
  365. /// provides a map of modules to the corresponding GUIDs/summaries to write.
  366. const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
  367. /// Map that holds the correspondence between the GUID used in the combined
  368. /// index and a value id generated by this class to use in references.
  369. std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
  370. /// Tracks the last value id recorded in the GUIDToValueMap.
  371. unsigned GlobalValueId = 0;
  372. public:
  373. /// Constructs a IndexBitcodeWriter object for the given combined index,
  374. /// writing to the provided \p Buffer. When writing a subset of the index
  375. /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
  376. IndexBitcodeWriter(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
  377. const ModuleSummaryIndex &Index,
  378. const std::map<std::string, GVSummaryMapTy>
  379. *ModuleToSummariesForIndex = nullptr)
  380. : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index),
  381. ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
  382. // Assign unique value ids to all summaries to be written, for use
  383. // in writing out the call graph edges. Save the mapping from GUID
  384. // to the new global value id to use when writing those edges, which
  385. // are currently saved in the index in terms of GUID.
  386. forEachSummary([&](GVInfo I, bool) {
  387. GUIDToValueIdMap[I.first] = ++GlobalValueId;
  388. });
  389. }
  390. /// The below iterator returns the GUID and associated summary.
  391. using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
  392. /// Calls the callback for each value GUID and summary to be written to
  393. /// bitcode. This hides the details of whether they are being pulled from the
  394. /// entire index or just those in a provided ModuleToSummariesForIndex map.
  395. template<typename Functor>
  396. void forEachSummary(Functor Callback) {
  397. if (ModuleToSummariesForIndex) {
  398. for (auto &M : *ModuleToSummariesForIndex)
  399. for (auto &Summary : M.second) {
  400. Callback(Summary, false);
  401. // Ensure aliasee is handled, e.g. for assigning a valueId,
  402. // even if we are not importing the aliasee directly (the
  403. // imported alias will contain a copy of aliasee).
  404. if (auto *AS = dyn_cast<AliasSummary>(Summary.getSecond()))
  405. Callback({AS->getAliaseeGUID(), &AS->getAliasee()}, true);
  406. }
  407. } else {
  408. for (auto &Summaries : Index)
  409. for (auto &Summary : Summaries.second.SummaryList)
  410. Callback({Summaries.first, Summary.get()}, false);
  411. }
  412. }
  413. /// Calls the callback for each entry in the modulePaths StringMap that
  414. /// should be written to the module path string table. This hides the details
  415. /// of whether they are being pulled from the entire index or just those in a
  416. /// provided ModuleToSummariesForIndex map.
  417. template <typename Functor> void forEachModule(Functor Callback) {
  418. if (ModuleToSummariesForIndex) {
  419. for (const auto &M : *ModuleToSummariesForIndex) {
  420. const auto &MPI = Index.modulePaths().find(M.first);
  421. if (MPI == Index.modulePaths().end()) {
  422. // This should only happen if the bitcode file was empty, in which
  423. // case we shouldn't be importing (the ModuleToSummariesForIndex
  424. // would only include the module we are writing and index for).
  425. assert(ModuleToSummariesForIndex->size() == 1);
  426. continue;
  427. }
  428. Callback(*MPI);
  429. }
  430. } else {
  431. for (const auto &MPSE : Index.modulePaths())
  432. Callback(MPSE);
  433. }
  434. }
  435. /// Main entry point for writing a combined index to bitcode.
  436. void write();
  437. private:
  438. void writeModStrings();
  439. void writeCombinedGlobalValueSummary();
  440. Optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {
  441. auto VMI = GUIDToValueIdMap.find(ValGUID);
  442. if (VMI == GUIDToValueIdMap.end())
  443. return None;
  444. return VMI->second;
  445. }
  446. std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
  447. };
  448. } // end anonymous namespace
  449. static unsigned getEncodedCastOpcode(unsigned Opcode) {
  450. switch (Opcode) {
  451. default: llvm_unreachable("Unknown cast instruction!");
  452. case Instruction::Trunc : return bitc::CAST_TRUNC;
  453. case Instruction::ZExt : return bitc::CAST_ZEXT;
  454. case Instruction::SExt : return bitc::CAST_SEXT;
  455. case Instruction::FPToUI : return bitc::CAST_FPTOUI;
  456. case Instruction::FPToSI : return bitc::CAST_FPTOSI;
  457. case Instruction::UIToFP : return bitc::CAST_UITOFP;
  458. case Instruction::SIToFP : return bitc::CAST_SITOFP;
  459. case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
  460. case Instruction::FPExt : return bitc::CAST_FPEXT;
  461. case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
  462. case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
  463. case Instruction::BitCast : return bitc::CAST_BITCAST;
  464. case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
  465. }
  466. }
  467. static unsigned getEncodedUnaryOpcode(unsigned Opcode) {
  468. switch (Opcode) {
  469. default: llvm_unreachable("Unknown binary instruction!");
  470. case Instruction::FNeg: return bitc::UNOP_NEG;
  471. }
  472. }
  473. static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
  474. switch (Opcode) {
  475. default: llvm_unreachable("Unknown binary instruction!");
  476. case Instruction::Add:
  477. case Instruction::FAdd: return bitc::BINOP_ADD;
  478. case Instruction::Sub:
  479. case Instruction::FSub: return bitc::BINOP_SUB;
  480. case Instruction::Mul:
  481. case Instruction::FMul: return bitc::BINOP_MUL;
  482. case Instruction::UDiv: return bitc::BINOP_UDIV;
  483. case Instruction::FDiv:
  484. case Instruction::SDiv: return bitc::BINOP_SDIV;
  485. case Instruction::URem: return bitc::BINOP_UREM;
  486. case Instruction::FRem:
  487. case Instruction::SRem: return bitc::BINOP_SREM;
  488. case Instruction::Shl: return bitc::BINOP_SHL;
  489. case Instruction::LShr: return bitc::BINOP_LSHR;
  490. case Instruction::AShr: return bitc::BINOP_ASHR;
  491. case Instruction::And: return bitc::BINOP_AND;
  492. case Instruction::Or: return bitc::BINOP_OR;
  493. case Instruction::Xor: return bitc::BINOP_XOR;
  494. }
  495. }
  496. static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
  497. switch (Op) {
  498. default: llvm_unreachable("Unknown RMW operation!");
  499. case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
  500. case AtomicRMWInst::Add: return bitc::RMW_ADD;
  501. case AtomicRMWInst::Sub: return bitc::RMW_SUB;
  502. case AtomicRMWInst::And: return bitc::RMW_AND;
  503. case AtomicRMWInst::Nand: return bitc::RMW_NAND;
  504. case AtomicRMWInst::Or: return bitc::RMW_OR;
  505. case AtomicRMWInst::Xor: return bitc::RMW_XOR;
  506. case AtomicRMWInst::Max: return bitc::RMW_MAX;
  507. case AtomicRMWInst::Min: return bitc::RMW_MIN;
  508. case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
  509. case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
  510. case AtomicRMWInst::FAdd: return bitc::RMW_FADD;
  511. case AtomicRMWInst::FSub: return bitc::RMW_FSUB;
  512. }
  513. }
  514. static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
  515. switch (Ordering) {
  516. case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
  517. case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
  518. case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
  519. case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
  520. case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
  521. case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
  522. case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
  523. }
  524. llvm_unreachable("Invalid ordering");
  525. }
  526. static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
  527. StringRef Str, unsigned AbbrevToUse) {
  528. SmallVector<unsigned, 64> Vals;
  529. // Code: [strchar x N]
  530. for (unsigned i = 0, e = Str.size(); i != e; ++i) {
  531. if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
  532. AbbrevToUse = 0;
  533. Vals.push_back(Str[i]);
  534. }
  535. // Emit the finished record.
  536. Stream.EmitRecord(Code, Vals, AbbrevToUse);
  537. }
  538. static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
  539. switch (Kind) {
  540. case Attribute::Alignment:
  541. return bitc::ATTR_KIND_ALIGNMENT;
  542. case Attribute::AllocSize:
  543. return bitc::ATTR_KIND_ALLOC_SIZE;
  544. case Attribute::AlwaysInline:
  545. return bitc::ATTR_KIND_ALWAYS_INLINE;
  546. case Attribute::ArgMemOnly:
  547. return bitc::ATTR_KIND_ARGMEMONLY;
  548. case Attribute::Builtin:
  549. return bitc::ATTR_KIND_BUILTIN;
  550. case Attribute::ByVal:
  551. return bitc::ATTR_KIND_BY_VAL;
  552. case Attribute::Convergent:
  553. return bitc::ATTR_KIND_CONVERGENT;
  554. case Attribute::InAlloca:
  555. return bitc::ATTR_KIND_IN_ALLOCA;
  556. case Attribute::Cold:
  557. return bitc::ATTR_KIND_COLD;
  558. case Attribute::InaccessibleMemOnly:
  559. return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY;
  560. case Attribute::InaccessibleMemOrArgMemOnly:
  561. return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY;
  562. case Attribute::InlineHint:
  563. return bitc::ATTR_KIND_INLINE_HINT;
  564. case Attribute::InReg:
  565. return bitc::ATTR_KIND_IN_REG;
  566. case Attribute::JumpTable:
  567. return bitc::ATTR_KIND_JUMP_TABLE;
  568. case Attribute::MinSize:
  569. return bitc::ATTR_KIND_MIN_SIZE;
  570. case Attribute::Naked:
  571. return bitc::ATTR_KIND_NAKED;
  572. case Attribute::Nest:
  573. return bitc::ATTR_KIND_NEST;
  574. case Attribute::NoAlias:
  575. return bitc::ATTR_KIND_NO_ALIAS;
  576. case Attribute::NoBuiltin:
  577. return bitc::ATTR_KIND_NO_BUILTIN;
  578. case Attribute::NoCapture:
  579. return bitc::ATTR_KIND_NO_CAPTURE;
  580. case Attribute::NoDuplicate:
  581. return bitc::ATTR_KIND_NO_DUPLICATE;
  582. case Attribute::NoImplicitFloat:
  583. return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
  584. case Attribute::NoInline:
  585. return bitc::ATTR_KIND_NO_INLINE;
  586. case Attribute::NoRecurse:
  587. return bitc::ATTR_KIND_NO_RECURSE;
  588. case Attribute::NonLazyBind:
  589. return bitc::ATTR_KIND_NON_LAZY_BIND;
  590. case Attribute::NonNull:
  591. return bitc::ATTR_KIND_NON_NULL;
  592. case Attribute::Dereferenceable:
  593. return bitc::ATTR_KIND_DEREFERENCEABLE;
  594. case Attribute::DereferenceableOrNull:
  595. return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
  596. case Attribute::NoRedZone:
  597. return bitc::ATTR_KIND_NO_RED_ZONE;
  598. case Attribute::NoReturn:
  599. return bitc::ATTR_KIND_NO_RETURN;
  600. case Attribute::NoCfCheck:
  601. return bitc::ATTR_KIND_NOCF_CHECK;
  602. case Attribute::NoUnwind:
  603. return bitc::ATTR_KIND_NO_UNWIND;
  604. case Attribute::OptForFuzzing:
  605. return bitc::ATTR_KIND_OPT_FOR_FUZZING;
  606. case Attribute::OptimizeForSize:
  607. return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
  608. case Attribute::OptimizeNone:
  609. return bitc::ATTR_KIND_OPTIMIZE_NONE;
  610. case Attribute::ReadNone:
  611. return bitc::ATTR_KIND_READ_NONE;
  612. case Attribute::ReadOnly:
  613. return bitc::ATTR_KIND_READ_ONLY;
  614. case Attribute::Returned:
  615. return bitc::ATTR_KIND_RETURNED;
  616. case Attribute::ReturnsTwice:
  617. return bitc::ATTR_KIND_RETURNS_TWICE;
  618. case Attribute::SExt:
  619. return bitc::ATTR_KIND_S_EXT;
  620. case Attribute::Speculatable:
  621. return bitc::ATTR_KIND_SPECULATABLE;
  622. case Attribute::StackAlignment:
  623. return bitc::ATTR_KIND_STACK_ALIGNMENT;
  624. case Attribute::StackProtect:
  625. return bitc::ATTR_KIND_STACK_PROTECT;
  626. case Attribute::StackProtectReq:
  627. return bitc::ATTR_KIND_STACK_PROTECT_REQ;
  628. case Attribute::StackProtectStrong:
  629. return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
  630. case Attribute::SafeStack:
  631. return bitc::ATTR_KIND_SAFESTACK;
  632. case Attribute::ShadowCallStack:
  633. return bitc::ATTR_KIND_SHADOWCALLSTACK;
  634. case Attribute::StrictFP:
  635. return bitc::ATTR_KIND_STRICT_FP;
  636. case Attribute::StructRet:
  637. return bitc::ATTR_KIND_STRUCT_RET;
  638. case Attribute::SanitizeAddress:
  639. return bitc::ATTR_KIND_SANITIZE_ADDRESS;
  640. case Attribute::SanitizeHWAddress:
  641. return bitc::ATTR_KIND_SANITIZE_HWADDRESS;
  642. case Attribute::SanitizeThread:
  643. return bitc::ATTR_KIND_SANITIZE_THREAD;
  644. case Attribute::SanitizeMemory:
  645. return bitc::ATTR_KIND_SANITIZE_MEMORY;
  646. case Attribute::SpeculativeLoadHardening:
  647. return bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING;
  648. case Attribute::SwiftError:
  649. return bitc::ATTR_KIND_SWIFT_ERROR;
  650. case Attribute::SwiftSelf:
  651. return bitc::ATTR_KIND_SWIFT_SELF;
  652. case Attribute::UWTable:
  653. return bitc::ATTR_KIND_UW_TABLE;
  654. case Attribute::WillReturn:
  655. return bitc::ATTR_KIND_WILLRETURN;
  656. case Attribute::WriteOnly:
  657. return bitc::ATTR_KIND_WRITEONLY;
  658. case Attribute::ZExt:
  659. return bitc::ATTR_KIND_Z_EXT;
  660. case Attribute::ImmArg:
  661. return bitc::ATTR_KIND_IMMARG;
  662. case Attribute::EndAttrKinds:
  663. llvm_unreachable("Can not encode end-attribute kinds marker.");
  664. case Attribute::None:
  665. llvm_unreachable("Can not encode none-attribute.");
  666. }
  667. llvm_unreachable("Trying to encode unknown attribute");
  668. }
  669. void ModuleBitcodeWriter::writeAttributeGroupTable() {
  670. const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
  671. VE.getAttributeGroups();
  672. if (AttrGrps.empty()) return;
  673. Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
  674. SmallVector<uint64_t, 64> Record;
  675. for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
  676. unsigned AttrListIndex = Pair.first;
  677. AttributeSet AS = Pair.second;
  678. Record.push_back(VE.getAttributeGroupID(Pair));
  679. Record.push_back(AttrListIndex);
  680. for (Attribute Attr : AS) {
  681. if (Attr.isEnumAttribute()) {
  682. Record.push_back(0);
  683. Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
  684. } else if (Attr.isIntAttribute()) {
  685. Record.push_back(1);
  686. Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
  687. Record.push_back(Attr.getValueAsInt());
  688. } else if (Attr.isStringAttribute()) {
  689. StringRef Kind = Attr.getKindAsString();
  690. StringRef Val = Attr.getValueAsString();
  691. Record.push_back(Val.empty() ? 3 : 4);
  692. Record.append(Kind.begin(), Kind.end());
  693. Record.push_back(0);
  694. if (!Val.empty()) {
  695. Record.append(Val.begin(), Val.end());
  696. Record.push_back(0);
  697. }
  698. } else {
  699. assert(Attr.isTypeAttribute());
  700. Type *Ty = Attr.getValueAsType();
  701. Record.push_back(Ty ? 6 : 5);
  702. Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
  703. if (Ty)
  704. Record.push_back(VE.getTypeID(Attr.getValueAsType()));
  705. }
  706. }
  707. Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
  708. Record.clear();
  709. }
  710. Stream.ExitBlock();
  711. }
  712. void ModuleBitcodeWriter::writeAttributeTable() {
  713. const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
  714. if (Attrs.empty()) return;
  715. Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
  716. SmallVector<uint64_t, 64> Record;
  717. for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
  718. AttributeList AL = Attrs[i];
  719. for (unsigned i = AL.index_begin(), e = AL.index_end(); i != e; ++i) {
  720. AttributeSet AS = AL.getAttributes(i);
  721. if (AS.hasAttributes())
  722. Record.push_back(VE.getAttributeGroupID({i, AS}));
  723. }
  724. Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
  725. Record.clear();
  726. }
  727. Stream.ExitBlock();
  728. }
  729. /// WriteTypeTable - Write out the type table for a module.
  730. void ModuleBitcodeWriter::writeTypeTable() {
  731. const ValueEnumerator::TypeList &TypeList = VE.getTypes();
  732. Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
  733. SmallVector<uint64_t, 64> TypeVals;
  734. uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
  735. // Abbrev for TYPE_CODE_POINTER.
  736. auto Abbv = std::make_shared<BitCodeAbbrev>();
  737. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
  738. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
  739. Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
  740. unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  741. // Abbrev for TYPE_CODE_FUNCTION.
  742. Abbv = std::make_shared<BitCodeAbbrev>();
  743. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
  744. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
  745. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  746. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
  747. unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  748. // Abbrev for TYPE_CODE_STRUCT_ANON.
  749. Abbv = std::make_shared<BitCodeAbbrev>();
  750. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
  751. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
  752. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  753. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
  754. unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  755. // Abbrev for TYPE_CODE_STRUCT_NAME.
  756. Abbv = std::make_shared<BitCodeAbbrev>();
  757. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
  758. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  759. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  760. unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  761. // Abbrev for TYPE_CODE_STRUCT_NAMED.
  762. Abbv = std::make_shared<BitCodeAbbrev>();
  763. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
  764. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
  765. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  766. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
  767. unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  768. // Abbrev for TYPE_CODE_ARRAY.
  769. Abbv = std::make_shared<BitCodeAbbrev>();
  770. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
  771. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
  772. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
  773. unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  774. // Emit an entry count so the reader can reserve space.
  775. TypeVals.push_back(TypeList.size());
  776. Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
  777. TypeVals.clear();
  778. // Loop over all of the types, emitting each in turn.
  779. for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
  780. Type *T = TypeList[i];
  781. int AbbrevToUse = 0;
  782. unsigned Code = 0;
  783. switch (T->getTypeID()) {
  784. case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
  785. case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
  786. case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
  787. case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
  788. case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
  789. case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
  790. case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
  791. case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
  792. case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
  793. case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
  794. case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;
  795. case Type::IntegerTyID:
  796. // INTEGER: [width]
  797. Code = bitc::TYPE_CODE_INTEGER;
  798. TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
  799. break;
  800. case Type::PointerTyID: {
  801. PointerType *PTy = cast<PointerType>(T);
  802. // POINTER: [pointee type, address space]
  803. Code = bitc::TYPE_CODE_POINTER;
  804. TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
  805. unsigned AddressSpace = PTy->getAddressSpace();
  806. TypeVals.push_back(AddressSpace);
  807. if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
  808. break;
  809. }
  810. case Type::FunctionTyID: {
  811. FunctionType *FT = cast<FunctionType>(T);
  812. // FUNCTION: [isvararg, retty, paramty x N]
  813. Code = bitc::TYPE_CODE_FUNCTION;
  814. TypeVals.push_back(FT->isVarArg());
  815. TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
  816. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
  817. TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
  818. AbbrevToUse = FunctionAbbrev;
  819. break;
  820. }
  821. case Type::StructTyID: {
  822. StructType *ST = cast<StructType>(T);
  823. // STRUCT: [ispacked, eltty x N]
  824. TypeVals.push_back(ST->isPacked());
  825. // Output all of the element types.
  826. for (StructType::element_iterator I = ST->element_begin(),
  827. E = ST->element_end(); I != E; ++I)
  828. TypeVals.push_back(VE.getTypeID(*I));
  829. if (ST->isLiteral()) {
  830. Code = bitc::TYPE_CODE_STRUCT_ANON;
  831. AbbrevToUse = StructAnonAbbrev;
  832. } else {
  833. if (ST->isOpaque()) {
  834. Code = bitc::TYPE_CODE_OPAQUE;
  835. } else {
  836. Code = bitc::TYPE_CODE_STRUCT_NAMED;
  837. AbbrevToUse = StructNamedAbbrev;
  838. }
  839. // Emit the name if it is present.
  840. if (!ST->getName().empty())
  841. writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
  842. StructNameAbbrev);
  843. }
  844. break;
  845. }
  846. case Type::ArrayTyID: {
  847. ArrayType *AT = cast<ArrayType>(T);
  848. // ARRAY: [numelts, eltty]
  849. Code = bitc::TYPE_CODE_ARRAY;
  850. TypeVals.push_back(AT->getNumElements());
  851. TypeVals.push_back(VE.getTypeID(AT->getElementType()));
  852. AbbrevToUse = ArrayAbbrev;
  853. break;
  854. }
  855. case Type::VectorTyID: {
  856. VectorType *VT = cast<VectorType>(T);
  857. // VECTOR [numelts, eltty]
  858. Code = bitc::TYPE_CODE_VECTOR;
  859. TypeVals.push_back(VT->getNumElements());
  860. TypeVals.push_back(VE.getTypeID(VT->getElementType()));
  861. break;
  862. }
  863. }
  864. // Emit the finished record.
  865. Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
  866. TypeVals.clear();
  867. }
  868. Stream.ExitBlock();
  869. }
  870. static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
  871. switch (Linkage) {
  872. case GlobalValue::ExternalLinkage:
  873. return 0;
  874. case GlobalValue::WeakAnyLinkage:
  875. return 16;
  876. case GlobalValue::AppendingLinkage:
  877. return 2;
  878. case GlobalValue::InternalLinkage:
  879. return 3;
  880. case GlobalValue::LinkOnceAnyLinkage:
  881. return 18;
  882. case GlobalValue::ExternalWeakLinkage:
  883. return 7;
  884. case GlobalValue::CommonLinkage:
  885. return 8;
  886. case GlobalValue::PrivateLinkage:
  887. return 9;
  888. case GlobalValue::WeakODRLinkage:
  889. return 17;
  890. case GlobalValue::LinkOnceODRLinkage:
  891. return 19;
  892. case GlobalValue::AvailableExternallyLinkage:
  893. return 12;
  894. }
  895. llvm_unreachable("Invalid linkage");
  896. }
  897. static unsigned getEncodedLinkage(const GlobalValue &GV) {
  898. return getEncodedLinkage(GV.getLinkage());
  899. }
  900. static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags) {
  901. uint64_t RawFlags = 0;
  902. RawFlags |= Flags.ReadNone;
  903. RawFlags |= (Flags.ReadOnly << 1);
  904. RawFlags |= (Flags.NoRecurse << 2);
  905. RawFlags |= (Flags.ReturnDoesNotAlias << 3);
  906. RawFlags |= (Flags.NoInline << 4);
  907. return RawFlags;
  908. }
  909. // Decode the flags for GlobalValue in the summary
  910. static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags) {
  911. uint64_t RawFlags = 0;
  912. RawFlags |= Flags.NotEligibleToImport; // bool
  913. RawFlags |= (Flags.Live << 1);
  914. RawFlags |= (Flags.DSOLocal << 2);
  915. RawFlags |= (Flags.CanAutoHide << 3);
  916. // Linkage don't need to be remapped at that time for the summary. Any future
  917. // change to the getEncodedLinkage() function will need to be taken into
  918. // account here as well.
  919. RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
  920. return RawFlags;
  921. }
  922. static uint64_t getEncodedGVarFlags(GlobalVarSummary::GVarFlags Flags) {
  923. uint64_t RawFlags = Flags.ReadOnly;
  924. return RawFlags;
  925. }
  926. static unsigned getEncodedVisibility(const GlobalValue &GV) {
  927. switch (GV.getVisibility()) {
  928. case GlobalValue::DefaultVisibility: return 0;
  929. case GlobalValue::HiddenVisibility: return 1;
  930. case GlobalValue::ProtectedVisibility: return 2;
  931. }
  932. llvm_unreachable("Invalid visibility");
  933. }
  934. static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
  935. switch (GV.getDLLStorageClass()) {
  936. case GlobalValue::DefaultStorageClass: return 0;
  937. case GlobalValue::DLLImportStorageClass: return 1;
  938. case GlobalValue::DLLExportStorageClass: return 2;
  939. }
  940. llvm_unreachable("Invalid DLL storage class");
  941. }
  942. static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
  943. switch (GV.getThreadLocalMode()) {
  944. case GlobalVariable::NotThreadLocal: return 0;
  945. case GlobalVariable::GeneralDynamicTLSModel: return 1;
  946. case GlobalVariable::LocalDynamicTLSModel: return 2;
  947. case GlobalVariable::InitialExecTLSModel: return 3;
  948. case GlobalVariable::LocalExecTLSModel: return 4;
  949. }
  950. llvm_unreachable("Invalid TLS model");
  951. }
  952. static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
  953. switch (C.getSelectionKind()) {
  954. case Comdat::Any:
  955. return bitc::COMDAT_SELECTION_KIND_ANY;
  956. case Comdat::ExactMatch:
  957. return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
  958. case Comdat::Largest:
  959. return bitc::COMDAT_SELECTION_KIND_LARGEST;
  960. case Comdat::NoDuplicates:
  961. return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
  962. case Comdat::SameSize:
  963. return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
  964. }
  965. llvm_unreachable("Invalid selection kind");
  966. }
  967. static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
  968. switch (GV.getUnnamedAddr()) {
  969. case GlobalValue::UnnamedAddr::None: return 0;
  970. case GlobalValue::UnnamedAddr::Local: return 2;
  971. case GlobalValue::UnnamedAddr::Global: return 1;
  972. }
  973. llvm_unreachable("Invalid unnamed_addr");
  974. }
  975. size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
  976. if (GenerateHash)
  977. Hasher.update(Str);
  978. return StrtabBuilder.add(Str);
  979. }
  980. void ModuleBitcodeWriter::writeComdats() {
  981. SmallVector<unsigned, 64> Vals;
  982. for (const Comdat *C : VE.getComdats()) {
  983. // COMDAT: [strtab offset, strtab size, selection_kind]
  984. Vals.push_back(addToStrtab(C->getName()));
  985. Vals.push_back(C->getName().size());
  986. Vals.push_back(getEncodedComdatSelectionKind(*C));
  987. Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
  988. Vals.clear();
  989. }
  990. }
  991. /// Write a record that will eventually hold the word offset of the
  992. /// module-level VST. For now the offset is 0, which will be backpatched
  993. /// after the real VST is written. Saves the bit offset to backpatch.
  994. void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
  995. // Write a placeholder value in for the offset of the real VST,
  996. // which is written after the function blocks so that it can include
  997. // the offset of each function. The placeholder offset will be
  998. // updated when the real VST is written.
  999. auto Abbv = std::make_shared<BitCodeAbbrev>();
  1000. Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
  1001. // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
  1002. // hold the real VST offset. Must use fixed instead of VBR as we don't
  1003. // know how many VBR chunks to reserve ahead of time.
  1004. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  1005. unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  1006. // Emit the placeholder
  1007. uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
  1008. Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
  1009. // Compute and save the bit offset to the placeholder, which will be
  1010. // patched when the real VST is written. We can simply subtract the 32-bit
  1011. // fixed size from the current bit number to get the location to backpatch.
  1012. VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
  1013. }
  1014. enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
  1015. /// Determine the encoding to use for the given string name and length.
  1016. static StringEncoding getStringEncoding(StringRef Str) {
  1017. bool isChar6 = true;
  1018. for (char C : Str) {
  1019. if (isChar6)
  1020. isChar6 = BitCodeAbbrevOp::isChar6(C);
  1021. if ((unsigned char)C & 128)
  1022. // don't bother scanning the rest.
  1023. return SE_Fixed8;
  1024. }
  1025. if (isChar6)
  1026. return SE_Char6;
  1027. return SE_Fixed7;
  1028. }
  1029. /// Emit top-level description of module, including target triple, inline asm,
  1030. /// descriptors for global variables, and function prototype info.
  1031. /// Returns the bit offset to backpatch with the location of the real VST.
  1032. void ModuleBitcodeWriter::writeModuleInfo() {
  1033. // Emit various pieces of data attached to a module.
  1034. if (!M.getTargetTriple().empty())
  1035. writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
  1036. 0 /*TODO*/);
  1037. const std::string &DL = M.getDataLayoutStr();
  1038. if (!DL.empty())
  1039. writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
  1040. if (!M.getModuleInlineAsm().empty())
  1041. writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
  1042. 0 /*TODO*/);
  1043. // Emit information about sections and GC, computing how many there are. Also
  1044. // compute the maximum alignment value.
  1045. std::map<std::string, unsigned> SectionMap;
  1046. std::map<std::string, unsigned> GCMap;
  1047. unsigned MaxAlignment = 0;
  1048. unsigned MaxGlobalType = 0;
  1049. for (const GlobalValue &GV : M.globals()) {
  1050. MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
  1051. MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
  1052. if (GV.hasSection()) {
  1053. // Give section names unique ID's.
  1054. unsigned &Entry = SectionMap[GV.getSection()];
  1055. if (!Entry) {
  1056. writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
  1057. 0 /*TODO*/);
  1058. Entry = SectionMap.size();
  1059. }
  1060. }
  1061. }
  1062. for (const Function &F : M) {
  1063. MaxAlignment = std::max(MaxAlignment, F.getAlignment());
  1064. if (F.hasSection()) {
  1065. // Give section names unique ID's.
  1066. unsigned &Entry = SectionMap[F.getSection()];
  1067. if (!Entry) {
  1068. writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
  1069. 0 /*TODO*/);
  1070. Entry = SectionMap.size();
  1071. }
  1072. }
  1073. if (F.hasGC()) {
  1074. // Same for GC names.
  1075. unsigned &Entry = GCMap[F.getGC()];
  1076. if (!Entry) {
  1077. writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
  1078. 0 /*TODO*/);
  1079. Entry = GCMap.size();
  1080. }
  1081. }
  1082. }
  1083. // Emit abbrev for globals, now that we know # sections and max alignment.
  1084. unsigned SimpleGVarAbbrev = 0;
  1085. if (!M.global_empty()) {
  1086. // Add an abbrev for common globals with no visibility or thread localness.
  1087. auto Abbv = std::make_shared<BitCodeAbbrev>();
  1088. Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
  1089. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  1090. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  1091. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  1092. Log2_32_Ceil(MaxGlobalType+1)));
  1093. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
  1094. //| explicitType << 1
  1095. //| constant
  1096. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
  1097. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
  1098. if (MaxAlignment == 0) // Alignment.
  1099. Abbv->Add(BitCodeAbbrevOp(0));
  1100. else {
  1101. unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
  1102. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  1103. Log2_32_Ceil(MaxEncAlignment+1)));
  1104. }
  1105. if (SectionMap.empty()) // Section.
  1106. Abbv->Add(BitCodeAbbrevOp(0));
  1107. else
  1108. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  1109. Log2_32_Ceil(SectionMap.size()+1)));
  1110. // Don't bother emitting vis + thread local.
  1111. SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  1112. }
  1113. SmallVector<unsigned, 64> Vals;
  1114. // Emit the module's source file name.
  1115. {
  1116. StringEncoding Bits = getStringEncoding(M.getSourceFileName());
  1117. BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
  1118. if (Bits == SE_Char6)
  1119. AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
  1120. else if (Bits == SE_Fixed7)
  1121. AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
  1122. // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
  1123. auto Abbv = std::make_shared<BitCodeAbbrev>();
  1124. Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
  1125. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1126. Abbv->Add(AbbrevOpToUse);
  1127. unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  1128. for (const auto P : M.getSourceFileName())
  1129. Vals.push_back((unsigned char)P);
  1130. // Emit the finished record.
  1131. Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
  1132. Vals.clear();
  1133. }
  1134. // Emit the global variable information.
  1135. for (const GlobalVariable &GV : M.globals()) {
  1136. unsigned AbbrevToUse = 0;
  1137. // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
  1138. // linkage, alignment, section, visibility, threadlocal,
  1139. // unnamed_addr, externally_initialized, dllstorageclass,
  1140. // comdat, attributes, DSO_Local]
  1141. Vals.push_back(addToStrtab(GV.getName()));
  1142. Vals.push_back(GV.getName().size());
  1143. Vals.push_back(VE.getTypeID(GV.getValueType()));
  1144. Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
  1145. Vals.push_back(GV.isDeclaration() ? 0 :
  1146. (VE.getValueID(GV.getInitializer()) + 1));
  1147. Vals.push_back(getEncodedLinkage(GV));
  1148. Vals.push_back(Log2_32(GV.getAlignment())+1);
  1149. Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
  1150. if (GV.isThreadLocal() ||
  1151. GV.getVisibility() != GlobalValue::DefaultVisibility ||
  1152. GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
  1153. GV.isExternallyInitialized() ||
  1154. GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
  1155. GV.hasComdat() ||
  1156. GV.hasAttributes() ||
  1157. GV.isDSOLocal() ||
  1158. GV.hasPartition()) {
  1159. Vals.push_back(getEncodedVisibility(GV));
  1160. Vals.push_back(getEncodedThreadLocalMode(GV));
  1161. Vals.push_back(getEncodedUnnamedAddr(GV));
  1162. Vals.push_back(GV.isExternallyInitialized());
  1163. Vals.push_back(getEncodedDLLStorageClass(GV));
  1164. Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
  1165. auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
  1166. Vals.push_back(VE.getAttributeListID(AL));
  1167. Vals.push_back(GV.isDSOLocal());
  1168. Vals.push_back(addToStrtab(GV.getPartition()));
  1169. Vals.push_back(GV.getPartition().size());
  1170. } else {
  1171. AbbrevToUse = SimpleGVarAbbrev;
  1172. }
  1173. Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
  1174. Vals.clear();
  1175. }
  1176. // Emit the function proto information.
  1177. for (const Function &F : M) {
  1178. // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,
  1179. // linkage, paramattrs, alignment, section, visibility, gc,
  1180. // unnamed_addr, prologuedata, dllstorageclass, comdat,
  1181. // prefixdata, personalityfn, DSO_Local, addrspace]
  1182. Vals.push_back(addToStrtab(F.getName()));
  1183. Vals.push_back(F.getName().size());
  1184. Vals.push_back(VE.getTypeID(F.getFunctionType()));
  1185. Vals.push_back(F.getCallingConv());
  1186. Vals.push_back(F.isDeclaration());
  1187. Vals.push_back(getEncodedLinkage(F));
  1188. Vals.push_back(VE.getAttributeListID(F.getAttributes()));
  1189. Vals.push_back(Log2_32(F.getAlignment())+1);
  1190. Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
  1191. Vals.push_back(getEncodedVisibility(F));
  1192. Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
  1193. Vals.push_back(getEncodedUnnamedAddr(F));
  1194. Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
  1195. : 0);
  1196. Vals.push_back(getEncodedDLLStorageClass(F));
  1197. Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
  1198. Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
  1199. : 0);
  1200. Vals.push_back(
  1201. F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
  1202. Vals.push_back(F.isDSOLocal());
  1203. Vals.push_back(F.getAddressSpace());
  1204. Vals.push_back(addToStrtab(F.getPartition()));
  1205. Vals.push_back(F.getPartition().size());
  1206. unsigned AbbrevToUse = 0;
  1207. Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
  1208. Vals.clear();
  1209. }
  1210. // Emit the alias information.
  1211. for (const GlobalAlias &A : M.aliases()) {
  1212. // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
  1213. // visibility, dllstorageclass, threadlocal, unnamed_addr,
  1214. // DSO_Local]
  1215. Vals.push_back(addToStrtab(A.getName()));
  1216. Vals.push_back(A.getName().size());
  1217. Vals.push_back(VE.getTypeID(A.getValueType()));
  1218. Vals.push_back(A.getType()->getAddressSpace());
  1219. Vals.push_back(VE.getValueID(A.getAliasee()));
  1220. Vals.push_back(getEncodedLinkage(A));
  1221. Vals.push_back(getEncodedVisibility(A));
  1222. Vals.push_back(getEncodedDLLStorageClass(A));
  1223. Vals.push_back(getEncodedThreadLocalMode(A));
  1224. Vals.push_back(getEncodedUnnamedAddr(A));
  1225. Vals.push_back(A.isDSOLocal());
  1226. Vals.push_back(addToStrtab(A.getPartition()));
  1227. Vals.push_back(A.getPartition().size());
  1228. unsigned AbbrevToUse = 0;
  1229. Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
  1230. Vals.clear();
  1231. }
  1232. // Emit the ifunc information.
  1233. for (const GlobalIFunc &I : M.ifuncs()) {
  1234. // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
  1235. // val#, linkage, visibility, DSO_Local]
  1236. Vals.push_back(addToStrtab(I.getName()));
  1237. Vals.push_back(I.getName().size());
  1238. Vals.push_back(VE.getTypeID(I.getValueType()));
  1239. Vals.push_back(I.getType()->getAddressSpace());
  1240. Vals.push_back(VE.getValueID(I.getResolver()));
  1241. Vals.push_back(getEncodedLinkage(I));
  1242. Vals.push_back(getEncodedVisibility(I));
  1243. Vals.push_back(I.isDSOLocal());
  1244. Vals.push_back(addToStrtab(I.getPartition()));
  1245. Vals.push_back(I.getPartition().size());
  1246. Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
  1247. Vals.clear();
  1248. }
  1249. writeValueSymbolTableForwardDecl();
  1250. }
  1251. static uint64_t getOptimizationFlags(const Value *V) {
  1252. uint64_t Flags = 0;
  1253. if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
  1254. if (OBO->hasNoSignedWrap())
  1255. Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
  1256. if (OBO->hasNoUnsignedWrap())
  1257. Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
  1258. } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
  1259. if (PEO->isExact())
  1260. Flags |= 1 << bitc::PEO_EXACT;
  1261. } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
  1262. if (FPMO->hasAllowReassoc())
  1263. Flags |= bitc::AllowReassoc;
  1264. if (FPMO->hasNoNaNs())
  1265. Flags |= bitc::NoNaNs;
  1266. if (FPMO->hasNoInfs())
  1267. Flags |= bitc::NoInfs;
  1268. if (FPMO->hasNoSignedZeros())
  1269. Flags |= bitc::NoSignedZeros;
  1270. if (FPMO->hasAllowReciprocal())
  1271. Flags |= bitc::AllowReciprocal;
  1272. if (FPMO->hasAllowContract())
  1273. Flags |= bitc::AllowContract;
  1274. if (FPMO->hasApproxFunc())
  1275. Flags |= bitc::ApproxFunc;
  1276. }
  1277. return Flags;
  1278. }
  1279. void ModuleBitcodeWriter::writeValueAsMetadata(
  1280. const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
  1281. // Mimic an MDNode with a value as one operand.
  1282. Value *V = MD->getValue();
  1283. Record.push_back(VE.getTypeID(V->getType()));
  1284. Record.push_back(VE.getValueID(V));
  1285. Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
  1286. Record.clear();
  1287. }
  1288. void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
  1289. SmallVectorImpl<uint64_t> &Record,
  1290. unsigned Abbrev) {
  1291. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
  1292. Metadata *MD = N->getOperand(i);
  1293. assert(!(MD && isa<LocalAsMetadata>(MD)) &&
  1294. "Unexpected function-local metadata");
  1295. Record.push_back(VE.getMetadataOrNullID(MD));
  1296. }
  1297. Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
  1298. : bitc::METADATA_NODE,
  1299. Record, Abbrev);
  1300. Record.clear();
  1301. }
  1302. unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
  1303. // Assume the column is usually under 128, and always output the inlined-at
  1304. // location (it's never more expensive than building an array size 1).
  1305. auto Abbv = std::make_shared<BitCodeAbbrev>();
  1306. Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
  1307. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
  1308. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  1309. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  1310. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  1311. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  1312. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
  1313. return Stream.EmitAbbrev(std::move(Abbv));
  1314. }
  1315. void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
  1316. SmallVectorImpl<uint64_t> &Record,
  1317. unsigned &Abbrev) {
  1318. if (!Abbrev)
  1319. Abbrev = createDILocationAbbrev();
  1320. Record.push_back(N->isDistinct());
  1321. Record.push_back(N->getLine());
  1322. Record.push_back(N->getColumn());
  1323. Record.push_back(VE.getMetadataID(N->getScope()));
  1324. Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
  1325. Record.push_back(N->isImplicitCode());
  1326. Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
  1327. Record.clear();
  1328. }
  1329. unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
  1330. // Assume the column is usually under 128, and always output the inlined-at
  1331. // location (it's never more expensive than building an array size 1).
  1332. auto Abbv = std::make_shared<BitCodeAbbrev>();
  1333. Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
  1334. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
  1335. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  1336. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
  1337. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  1338. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1339. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  1340. return Stream.EmitAbbrev(std::move(Abbv));
  1341. }
  1342. void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
  1343. SmallVectorImpl<uint64_t> &Record,
  1344. unsigned &Abbrev) {
  1345. if (!Abbrev)
  1346. Abbrev = createGenericDINodeAbbrev();
  1347. Record.push_back(N->isDistinct());
  1348. Record.push_back(N->getTag());
  1349. Record.push_back(0); // Per-tag version field; unused for now.
  1350. for (auto &I : N->operands())
  1351. Record.push_back(VE.getMetadataOrNullID(I));
  1352. Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
  1353. Record.clear();
  1354. }
  1355. static uint64_t rotateSign(int64_t I) {
  1356. uint64_t U = I;
  1357. return I < 0 ? ~(U << 1) : U << 1;
  1358. }
  1359. void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
  1360. SmallVectorImpl<uint64_t> &Record,
  1361. unsigned Abbrev) {
  1362. const uint64_t Version = 1 << 1;
  1363. Record.push_back((uint64_t)N->isDistinct() | Version);
  1364. Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
  1365. Record.push_back(rotateSign(N->getLowerBound()));
  1366. Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
  1367. Record.clear();
  1368. }
  1369. void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
  1370. SmallVectorImpl<uint64_t> &Record,
  1371. unsigned Abbrev) {
  1372. Record.push_back((N->isUnsigned() << 1) | N->isDistinct());
  1373. Record.push_back(rotateSign(N->getValue()));
  1374. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1375. Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
  1376. Record.clear();
  1377. }
  1378. void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
  1379. SmallVectorImpl<uint64_t> &Record,
  1380. unsigned Abbrev) {
  1381. Record.push_back(N->isDistinct());
  1382. Record.push_back(N->getTag());
  1383. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1384. Record.push_back(N->getSizeInBits());
  1385. Record.push_back(N->getAlignInBits());
  1386. Record.push_back(N->getEncoding());
  1387. Record.push_back(N->getFlags());
  1388. Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
  1389. Record.clear();
  1390. }
  1391. void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
  1392. SmallVectorImpl<uint64_t> &Record,
  1393. unsigned Abbrev) {
  1394. Record.push_back(N->isDistinct());
  1395. Record.push_back(N->getTag());
  1396. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1397. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1398. Record.push_back(N->getLine());
  1399. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  1400. Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
  1401. Record.push_back(N->getSizeInBits());
  1402. Record.push_back(N->getAlignInBits());
  1403. Record.push_back(N->getOffsetInBits());
  1404. Record.push_back(N->getFlags());
  1405. Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
  1406. // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
  1407. // that there is no DWARF address space associated with DIDerivedType.
  1408. if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
  1409. Record.push_back(*DWARFAddressSpace + 1);
  1410. else
  1411. Record.push_back(0);
  1412. Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
  1413. Record.clear();
  1414. }
  1415. void ModuleBitcodeWriter::writeDICompositeType(
  1416. const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
  1417. unsigned Abbrev) {
  1418. const unsigned IsNotUsedInOldTypeRef = 0x2;
  1419. Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
  1420. Record.push_back(N->getTag());
  1421. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1422. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1423. Record.push_back(N->getLine());
  1424. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  1425. Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
  1426. Record.push_back(N->getSizeInBits());
  1427. Record.push_back(N->getAlignInBits());
  1428. Record.push_back(N->getOffsetInBits());
  1429. Record.push_back(N->getFlags());
  1430. Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
  1431. Record.push_back(N->getRuntimeLang());
  1432. Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
  1433. Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
  1434. Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
  1435. Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator()));
  1436. Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
  1437. Record.clear();
  1438. }
  1439. void ModuleBitcodeWriter::writeDISubroutineType(
  1440. const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
  1441. unsigned Abbrev) {
  1442. const unsigned HasNoOldTypeRefs = 0x2;
  1443. Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
  1444. Record.push_back(N->getFlags());
  1445. Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
  1446. Record.push_back(N->getCC());
  1447. Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
  1448. Record.clear();
  1449. }
  1450. void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
  1451. SmallVectorImpl<uint64_t> &Record,
  1452. unsigned Abbrev) {
  1453. Record.push_back(N->isDistinct());
  1454. Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
  1455. Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
  1456. if (N->getRawChecksum()) {
  1457. Record.push_back(N->getRawChecksum()->Kind);
  1458. Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));
  1459. } else {
  1460. // Maintain backwards compatibility with the old internal representation of
  1461. // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
  1462. Record.push_back(0);
  1463. Record.push_back(VE.getMetadataOrNullID(nullptr));
  1464. }
  1465. auto Source = N->getRawSource();
  1466. if (Source)
  1467. Record.push_back(VE.getMetadataOrNullID(*Source));
  1468. Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
  1469. Record.clear();
  1470. }
  1471. void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
  1472. SmallVectorImpl<uint64_t> &Record,
  1473. unsigned Abbrev) {
  1474. assert(N->isDistinct() && "Expected distinct compile units");
  1475. Record.push_back(/* IsDistinct */ true);
  1476. Record.push_back(N->getSourceLanguage());
  1477. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1478. Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
  1479. Record.push_back(N->isOptimized());
  1480. Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
  1481. Record.push_back(N->getRuntimeVersion());
  1482. Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
  1483. Record.push_back(N->getEmissionKind());
  1484. Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
  1485. Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
  1486. Record.push_back(/* subprograms */ 0);
  1487. Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
  1488. Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
  1489. Record.push_back(N->getDWOId());
  1490. Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
  1491. Record.push_back(N->getSplitDebugInlining());
  1492. Record.push_back(N->getDebugInfoForProfiling());
  1493. Record.push_back((unsigned)N->getNameTableKind());
  1494. Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
  1495. Record.clear();
  1496. }
  1497. void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
  1498. SmallVectorImpl<uint64_t> &Record,
  1499. unsigned Abbrev) {
  1500. const uint64_t HasUnitFlag = 1 << 1;
  1501. const uint64_t HasSPFlagsFlag = 1 << 2;
  1502. Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
  1503. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  1504. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1505. Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
  1506. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1507. Record.push_back(N->getLine());
  1508. Record.push_back(VE.getMetadataOrNullID(N->getType()));
  1509. Record.push_back(N->getScopeLine());
  1510. Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
  1511. Record.push_back(N->getSPFlags());
  1512. Record.push_back(N->getVirtualIndex());
  1513. Record.push_back(N->getFlags());
  1514. Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
  1515. Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
  1516. Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
  1517. Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));
  1518. Record.push_back(N->getThisAdjustment());
  1519. Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
  1520. Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
  1521. Record.clear();
  1522. }
  1523. void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
  1524. SmallVectorImpl<uint64_t> &Record,
  1525. unsigned Abbrev) {
  1526. Record.push_back(N->isDistinct());
  1527. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  1528. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1529. Record.push_back(N->getLine());
  1530. Record.push_back(N->getColumn());
  1531. Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
  1532. Record.clear();
  1533. }
  1534. void ModuleBitcodeWriter::writeDILexicalBlockFile(
  1535. const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
  1536. unsigned Abbrev) {
  1537. Record.push_back(N->isDistinct());
  1538. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  1539. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1540. Record.push_back(N->getDiscriminator());
  1541. Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
  1542. Record.clear();
  1543. }
  1544. void ModuleBitcodeWriter::writeDICommonBlock(const DICommonBlock *N,
  1545. SmallVectorImpl<uint64_t> &Record,
  1546. unsigned Abbrev) {
  1547. Record.push_back(N->isDistinct());
  1548. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  1549. Record.push_back(VE.getMetadataOrNullID(N->getDecl()));
  1550. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1551. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1552. Record.push_back(N->getLineNo());
  1553. Stream.EmitRecord(bitc::METADATA_COMMON_BLOCK, Record, Abbrev);
  1554. Record.clear();
  1555. }
  1556. void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
  1557. SmallVectorImpl<uint64_t> &Record,
  1558. unsigned Abbrev) {
  1559. Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
  1560. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  1561. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1562. Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
  1563. Record.clear();
  1564. }
  1565. void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
  1566. SmallVectorImpl<uint64_t> &Record,
  1567. unsigned Abbrev) {
  1568. Record.push_back(N->isDistinct());
  1569. Record.push_back(N->getMacinfoType());
  1570. Record.push_back(N->getLine());
  1571. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1572. Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
  1573. Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
  1574. Record.clear();
  1575. }
  1576. void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
  1577. SmallVectorImpl<uint64_t> &Record,
  1578. unsigned Abbrev) {
  1579. Record.push_back(N->isDistinct());
  1580. Record.push_back(N->getMacinfoType());
  1581. Record.push_back(N->getLine());
  1582. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1583. Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
  1584. Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
  1585. Record.clear();
  1586. }
  1587. void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
  1588. SmallVectorImpl<uint64_t> &Record,
  1589. unsigned Abbrev) {
  1590. Record.push_back(N->isDistinct());
  1591. for (auto &I : N->operands())
  1592. Record.push_back(VE.getMetadataOrNullID(I));
  1593. Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
  1594. Record.clear();
  1595. }
  1596. void ModuleBitcodeWriter::writeDITemplateTypeParameter(
  1597. const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
  1598. unsigned Abbrev) {
  1599. Record.push_back(N->isDistinct());
  1600. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1601. Record.push_back(VE.getMetadataOrNullID(N->getType()));
  1602. Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
  1603. Record.clear();
  1604. }
  1605. void ModuleBitcodeWriter::writeDITemplateValueParameter(
  1606. const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
  1607. unsigned Abbrev) {
  1608. Record.push_back(N->isDistinct());
  1609. Record.push_back(N->getTag());
  1610. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1611. Record.push_back(VE.getMetadataOrNullID(N->getType()));
  1612. Record.push_back(VE.getMetadataOrNullID(N->getValue()));
  1613. Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
  1614. Record.clear();
  1615. }
  1616. void ModuleBitcodeWriter::writeDIGlobalVariable(
  1617. const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
  1618. unsigned Abbrev) {
  1619. const uint64_t Version = 2 << 1;
  1620. Record.push_back((uint64_t)N->isDistinct() | Version);
  1621. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  1622. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1623. Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
  1624. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1625. Record.push_back(N->getLine());
  1626. Record.push_back(VE.getMetadataOrNullID(N->getType()));
  1627. Record.push_back(N->isLocalToUnit());
  1628. Record.push_back(N->isDefinition());
  1629. Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
  1630. Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
  1631. Record.push_back(N->getAlignInBits());
  1632. Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
  1633. Record.clear();
  1634. }
  1635. void ModuleBitcodeWriter::writeDILocalVariable(
  1636. const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
  1637. unsigned Abbrev) {
  1638. // In order to support all possible bitcode formats in BitcodeReader we need
  1639. // to distinguish the following cases:
  1640. // 1) Record has no artificial tag (Record[1]),
  1641. // has no obsolete inlinedAt field (Record[9]).
  1642. // In this case Record size will be 8, HasAlignment flag is false.
  1643. // 2) Record has artificial tag (Record[1]),
  1644. // has no obsolete inlignedAt field (Record[9]).
  1645. // In this case Record size will be 9, HasAlignment flag is false.
  1646. // 3) Record has both artificial tag (Record[1]) and
  1647. // obsolete inlignedAt field (Record[9]).
  1648. // In this case Record size will be 10, HasAlignment flag is false.
  1649. // 4) Record has neither artificial tag, nor inlignedAt field, but
  1650. // HasAlignment flag is true and Record[8] contains alignment value.
  1651. const uint64_t HasAlignmentFlag = 1 << 1;
  1652. Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
  1653. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  1654. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1655. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1656. Record.push_back(N->getLine());
  1657. Record.push_back(VE.getMetadataOrNullID(N->getType()));
  1658. Record.push_back(N->getArg());
  1659. Record.push_back(N->getFlags());
  1660. Record.push_back(N->getAlignInBits());
  1661. Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
  1662. Record.clear();
  1663. }
  1664. void ModuleBitcodeWriter::writeDILabel(
  1665. const DILabel *N, SmallVectorImpl<uint64_t> &Record,
  1666. unsigned Abbrev) {
  1667. Record.push_back((uint64_t)N->isDistinct());
  1668. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  1669. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1670. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1671. Record.push_back(N->getLine());
  1672. Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev);
  1673. Record.clear();
  1674. }
  1675. void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
  1676. SmallVectorImpl<uint64_t> &Record,
  1677. unsigned Abbrev) {
  1678. Record.reserve(N->getElements().size() + 1);
  1679. const uint64_t Version = 3 << 1;
  1680. Record.push_back((uint64_t)N->isDistinct() | Version);
  1681. Record.append(N->elements_begin(), N->elements_end());
  1682. Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
  1683. Record.clear();
  1684. }
  1685. void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
  1686. const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
  1687. unsigned Abbrev) {
  1688. Record.push_back(N->isDistinct());
  1689. Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
  1690. Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
  1691. Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
  1692. Record.clear();
  1693. }
  1694. void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
  1695. SmallVectorImpl<uint64_t> &Record,
  1696. unsigned Abbrev) {
  1697. Record.push_back(N->isDistinct());
  1698. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1699. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1700. Record.push_back(N->getLine());
  1701. Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
  1702. Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
  1703. Record.push_back(N->getAttributes());
  1704. Record.push_back(VE.getMetadataOrNullID(N->getType()));
  1705. Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
  1706. Record.clear();
  1707. }
  1708. void ModuleBitcodeWriter::writeDIImportedEntity(
  1709. const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
  1710. unsigned Abbrev) {
  1711. Record.push_back(N->isDistinct());
  1712. Record.push_back(N->getTag());
  1713. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  1714. Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
  1715. Record.push_back(N->getLine());
  1716. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1717. Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
  1718. Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
  1719. Record.clear();
  1720. }
  1721. unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
  1722. auto Abbv = std::make_shared<BitCodeAbbrev>();
  1723. Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
  1724. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1725. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
  1726. return Stream.EmitAbbrev(std::move(Abbv));
  1727. }
  1728. void ModuleBitcodeWriter::writeNamedMetadata(
  1729. SmallVectorImpl<uint64_t> &Record) {
  1730. if (M.named_metadata_empty())
  1731. return;
  1732. unsigned Abbrev = createNamedMetadataAbbrev();
  1733. for (const NamedMDNode &NMD : M.named_metadata()) {
  1734. // Write name.
  1735. StringRef Str = NMD.getName();
  1736. Record.append(Str.bytes_begin(), Str.bytes_end());
  1737. Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
  1738. Record.clear();
  1739. // Write named metadata operands.
  1740. for (const MDNode *N : NMD.operands())
  1741. Record.push_back(VE.getMetadataID(N));
  1742. Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
  1743. Record.clear();
  1744. }
  1745. }
  1746. unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
  1747. auto Abbv = std::make_shared<BitCodeAbbrev>();
  1748. Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
  1749. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
  1750. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
  1751. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  1752. return Stream.EmitAbbrev(std::move(Abbv));
  1753. }
  1754. /// Write out a record for MDString.
  1755. ///
  1756. /// All the metadata strings in a metadata block are emitted in a single
  1757. /// record. The sizes and strings themselves are shoved into a blob.
  1758. void ModuleBitcodeWriter::writeMetadataStrings(
  1759. ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
  1760. if (Strings.empty())
  1761. return;
  1762. // Start the record with the number of strings.
  1763. Record.push_back(bitc::METADATA_STRINGS);
  1764. Record.push_back(Strings.size());
  1765. // Emit the sizes of the strings in the blob.
  1766. SmallString<256> Blob;
  1767. {
  1768. BitstreamWriter W(Blob);
  1769. for (const Metadata *MD : Strings)
  1770. W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
  1771. W.FlushToWord();
  1772. }
  1773. // Add the offset to the strings to the record.
  1774. Record.push_back(Blob.size());
  1775. // Add the strings to the blob.
  1776. for (const Metadata *MD : Strings)
  1777. Blob.append(cast<MDString>(MD)->getString());
  1778. // Emit the final record.
  1779. Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
  1780. Record.clear();
  1781. }
  1782. // Generates an enum to use as an index in the Abbrev array of Metadata record.
  1783. enum MetadataAbbrev : unsigned {
  1784. #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
  1785. #include "llvm/IR/Metadata.def"
  1786. LastPlusOne
  1787. };
  1788. void ModuleBitcodeWriter::writeMetadataRecords(
  1789. ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
  1790. std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
  1791. if (MDs.empty())
  1792. return;
  1793. // Initialize MDNode abbreviations.
  1794. #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
  1795. #include "llvm/IR/Metadata.def"
  1796. for (const Metadata *MD : MDs) {
  1797. if (IndexPos)
  1798. IndexPos->push_back(Stream.GetCurrentBitNo());
  1799. if (const MDNode *N = dyn_cast<MDNode>(MD)) {
  1800. assert(N->isResolved() && "Expected forward references to be resolved");
  1801. switch (N->getMetadataID()) {
  1802. default:
  1803. llvm_unreachable("Invalid MDNode subclass");
  1804. #define HANDLE_MDNODE_LEAF(CLASS) \
  1805. case Metadata::CLASS##Kind: \
  1806. if (MDAbbrevs) \
  1807. write##CLASS(cast<CLASS>(N), Record, \
  1808. (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
  1809. else \
  1810. write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
  1811. continue;
  1812. #include "llvm/IR/Metadata.def"
  1813. }
  1814. }
  1815. writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
  1816. }
  1817. }
  1818. void ModuleBitcodeWriter::writeModuleMetadata() {
  1819. if (!VE.hasMDs() && M.named_metadata_empty())
  1820. return;
  1821. Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
  1822. SmallVector<uint64_t, 64> Record;
  1823. // Emit all abbrevs upfront, so that the reader can jump in the middle of the
  1824. // block and load any metadata.
  1825. std::vector<unsigned> MDAbbrevs;
  1826. MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
  1827. MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
  1828. MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
  1829. createGenericDINodeAbbrev();
  1830. auto Abbv = std::make_shared<BitCodeAbbrev>();
  1831. Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
  1832. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  1833. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  1834. unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  1835. Abbv = std::make_shared<BitCodeAbbrev>();
  1836. Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
  1837. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1838. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  1839. unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  1840. // Emit MDStrings together upfront.
  1841. writeMetadataStrings(VE.getMDStrings(), Record);
  1842. // We only emit an index for the metadata record if we have more than a given
  1843. // (naive) threshold of metadatas, otherwise it is not worth it.
  1844. if (VE.getNonMDStrings().size() > IndexThreshold) {
  1845. // Write a placeholder value in for the offset of the metadata index,
  1846. // which is written after the records, so that it can include
  1847. // the offset of each entry. The placeholder offset will be
  1848. // updated after all records are emitted.
  1849. uint64_t Vals[] = {0, 0};
  1850. Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
  1851. }
  1852. // Compute and save the bit offset to the current position, which will be
  1853. // patched when we emit the index later. We can simply subtract the 64-bit
  1854. // fixed size from the current bit number to get the location to backpatch.
  1855. uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
  1856. // This index will contain the bitpos for each individual record.
  1857. std::vector<uint64_t> IndexPos;
  1858. IndexPos.reserve(VE.getNonMDStrings().size());
  1859. // Write all the records
  1860. writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
  1861. if (VE.getNonMDStrings().size() > IndexThreshold) {
  1862. // Now that we have emitted all the records we will emit the index. But
  1863. // first
  1864. // backpatch the forward reference so that the reader can skip the records
  1865. // efficiently.
  1866. Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
  1867. Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
  1868. // Delta encode the index.
  1869. uint64_t PreviousValue = IndexOffsetRecordBitPos;
  1870. for (auto &Elt : IndexPos) {
  1871. auto EltDelta = Elt - PreviousValue;
  1872. PreviousValue = Elt;
  1873. Elt = EltDelta;
  1874. }
  1875. // Emit the index record.
  1876. Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
  1877. IndexPos.clear();
  1878. }
  1879. // Write the named metadata now.
  1880. writeNamedMetadata(Record);
  1881. auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
  1882. SmallVector<uint64_t, 4> Record;
  1883. Record.push_back(VE.getValueID(&GO));
  1884. pushGlobalMetadataAttachment(Record, GO);
  1885. Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);
  1886. };
  1887. for (const Function &F : M)
  1888. if (F.isDeclaration() && F.hasMetadata())
  1889. AddDeclAttachedMetadata(F);
  1890. // FIXME: Only store metadata for declarations here, and move data for global
  1891. // variable definitions to a separate block (PR28134).
  1892. for (const GlobalVariable &GV : M.globals())
  1893. if (GV.hasMetadata())
  1894. AddDeclAttachedMetadata(GV);
  1895. Stream.ExitBlock();
  1896. }
  1897. void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
  1898. if (!VE.hasMDs())
  1899. return;
  1900. Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
  1901. SmallVector<uint64_t, 64> Record;
  1902. writeMetadataStrings(VE.getMDStrings(), Record);
  1903. writeMetadataRecords(VE.getNonMDStrings(), Record);
  1904. Stream.ExitBlock();
  1905. }
  1906. void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
  1907. SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
  1908. // [n x [id, mdnode]]
  1909. SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
  1910. GO.getAllMetadata(MDs);
  1911. for (const auto &I : MDs) {
  1912. Record.push_back(I.first);
  1913. Record.push_back(VE.getMetadataID(I.second));
  1914. }
  1915. }
  1916. void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
  1917. Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
  1918. SmallVector<uint64_t, 64> Record;
  1919. if (F.hasMetadata()) {
  1920. pushGlobalMetadataAttachment(Record, F);
  1921. Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
  1922. Record.clear();
  1923. }
  1924. // Write metadata attachments
  1925. // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
  1926. SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
  1927. for (const BasicBlock &BB : F)
  1928. for (const Instruction &I : BB) {
  1929. MDs.clear();
  1930. I.getAllMetadataOtherThanDebugLoc(MDs);
  1931. // If no metadata, ignore instruction.
  1932. if (MDs.empty()) continue;
  1933. Record.push_back(VE.getInstructionID(&I));
  1934. for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
  1935. Record.push_back(MDs[i].first);
  1936. Record.push_back(VE.getMetadataID(MDs[i].second));
  1937. }
  1938. Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
  1939. Record.clear();
  1940. }
  1941. Stream.ExitBlock();
  1942. }
  1943. void ModuleBitcodeWriter::writeModuleMetadataKinds() {
  1944. SmallVector<uint64_t, 64> Record;
  1945. // Write metadata kinds
  1946. // METADATA_KIND - [n x [id, name]]
  1947. SmallVector<StringRef, 8> Names;
  1948. M.getMDKindNames(Names);
  1949. if (Names.empty()) return;
  1950. Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
  1951. for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
  1952. Record.push_back(MDKindID);
  1953. StringRef KName = Names[MDKindID];
  1954. Record.append(KName.begin(), KName.end());
  1955. Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
  1956. Record.clear();
  1957. }
  1958. Stream.ExitBlock();
  1959. }
  1960. void ModuleBitcodeWriter::writeOperandBundleTags() {
  1961. // Write metadata kinds
  1962. //
  1963. // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
  1964. //
  1965. // OPERAND_BUNDLE_TAG - [strchr x N]
  1966. SmallVector<StringRef, 8> Tags;
  1967. M.getOperandBundleTags(Tags);
  1968. if (Tags.empty())
  1969. return;
  1970. Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
  1971. SmallVector<uint64_t, 64> Record;
  1972. for (auto Tag : Tags) {
  1973. Record.append(Tag.begin(), Tag.end());
  1974. Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
  1975. Record.clear();
  1976. }
  1977. Stream.ExitBlock();
  1978. }
  1979. void ModuleBitcodeWriter::writeSyncScopeNames() {
  1980. SmallVector<StringRef, 8> SSNs;
  1981. M.getContext().getSyncScopeNames(SSNs);
  1982. if (SSNs.empty())
  1983. return;
  1984. Stream.EnterSubblock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID, 2);
  1985. SmallVector<uint64_t, 64> Record;
  1986. for (auto SSN : SSNs) {
  1987. Record.append(SSN.begin(), SSN.end());
  1988. Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0);
  1989. Record.clear();
  1990. }
  1991. Stream.ExitBlock();
  1992. }
  1993. static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
  1994. if ((int64_t)V >= 0)
  1995. Vals.push_back(V << 1);
  1996. else
  1997. Vals.push_back((-V << 1) | 1);
  1998. }
  1999. void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
  2000. bool isGlobal) {
  2001. if (FirstVal == LastVal) return;
  2002. Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
  2003. unsigned AggregateAbbrev = 0;
  2004. unsigned String8Abbrev = 0;
  2005. unsigned CString7Abbrev = 0;
  2006. unsigned CString6Abbrev = 0;
  2007. // If this is a constant pool for the module, emit module-specific abbrevs.
  2008. if (isGlobal) {
  2009. // Abbrev for CST_CODE_AGGREGATE.
  2010. auto Abbv = std::make_shared<BitCodeAbbrev>();
  2011. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
  2012. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2013. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
  2014. AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  2015. // Abbrev for CST_CODE_STRING.
  2016. Abbv = std::make_shared<BitCodeAbbrev>();
  2017. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
  2018. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2019. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
  2020. String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
  2021. // Abbrev for CST_CODE_CSTRING.
  2022. Abbv = std::make_shared<BitCodeAbbrev>();
  2023. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
  2024. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2025. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
  2026. CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
  2027. // Abbrev for CST_CODE_CSTRING.
  2028. Abbv = std::make_shared<BitCodeAbbrev>();
  2029. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
  2030. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2031. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  2032. CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
  2033. }
  2034. SmallVector<uint64_t, 64> Record;
  2035. const ValueEnumerator::ValueList &Vals = VE.getValues();
  2036. Type *LastTy = nullptr;
  2037. for (unsigned i = FirstVal; i != LastVal; ++i) {
  2038. const Value *V = Vals[i].first;
  2039. // If we need to switch types, do so now.
  2040. if (V->getType() != LastTy) {
  2041. LastTy = V->getType();
  2042. Record.push_back(VE.getTypeID(LastTy));
  2043. Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
  2044. CONSTANTS_SETTYPE_ABBREV);
  2045. Record.clear();
  2046. }
  2047. if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
  2048. Record.push_back(unsigned(IA->hasSideEffects()) |
  2049. unsigned(IA->isAlignStack()) << 1 |
  2050. unsigned(IA->getDialect()&1) << 2);
  2051. // Add the asm string.
  2052. const std::string &AsmStr = IA->getAsmString();
  2053. Record.push_back(AsmStr.size());
  2054. Record.append(AsmStr.begin(), AsmStr.end());
  2055. // Add the constraint string.
  2056. const std::string &ConstraintStr = IA->getConstraintString();
  2057. Record.push_back(ConstraintStr.size());
  2058. Record.append(ConstraintStr.begin(), ConstraintStr.end());
  2059. Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
  2060. Record.clear();
  2061. continue;
  2062. }
  2063. const Constant *C = cast<Constant>(V);
  2064. unsigned Code = -1U;
  2065. unsigned AbbrevToUse = 0;
  2066. if (C->isNullValue()) {
  2067. Code = bitc::CST_CODE_NULL;
  2068. } else if (isa<UndefValue>(C)) {
  2069. Code = bitc::CST_CODE_UNDEF;
  2070. } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
  2071. if (IV->getBitWidth() <= 64) {
  2072. uint64_t V = IV->getSExtValue();
  2073. emitSignedInt64(Record, V);
  2074. Code = bitc::CST_CODE_INTEGER;
  2075. AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
  2076. } else { // Wide integers, > 64 bits in size.
  2077. // We have an arbitrary precision integer value to write whose
  2078. // bit width is > 64. However, in canonical unsigned integer
  2079. // format it is likely that the high bits are going to be zero.
  2080. // So, we only write the number of active words.
  2081. unsigned NWords = IV->getValue().getActiveWords();
  2082. const uint64_t *RawWords = IV->getValue().getRawData();
  2083. for (unsigned i = 0; i != NWords; ++i) {
  2084. emitSignedInt64(Record, RawWords[i]);
  2085. }
  2086. Code = bitc::CST_CODE_WIDE_INTEGER;
  2087. }
  2088. } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
  2089. Code = bitc::CST_CODE_FLOAT;
  2090. Type *Ty = CFP->getType();
  2091. if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
  2092. Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
  2093. } else if (Ty->isX86_FP80Ty()) {
  2094. // api needed to prevent premature destruction
  2095. // bits are not in the same order as a normal i80 APInt, compensate.
  2096. APInt api = CFP->getValueAPF().bitcastToAPInt();
  2097. const uint64_t *p = api.getRawData();
  2098. Record.push_back((p[1] << 48) | (p[0] >> 16));
  2099. Record.push_back(p[0] & 0xffffLL);
  2100. } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
  2101. APInt api = CFP->getValueAPF().bitcastToAPInt();
  2102. const uint64_t *p = api.getRawData();
  2103. Record.push_back(p[0]);
  2104. Record.push_back(p[1]);
  2105. } else {
  2106. assert(0 && "Unknown FP type!");
  2107. }
  2108. } else if (isa<ConstantDataSequential>(C) &&
  2109. cast<ConstantDataSequential>(C)->isString()) {
  2110. const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
  2111. // Emit constant strings specially.
  2112. unsigned NumElts = Str->getNumElements();
  2113. // If this is a null-terminated string, use the denser CSTRING encoding.
  2114. if (Str->isCString()) {
  2115. Code = bitc::CST_CODE_CSTRING;
  2116. --NumElts; // Don't encode the null, which isn't allowed by char6.
  2117. } else {
  2118. Code = bitc::CST_CODE_STRING;
  2119. AbbrevToUse = String8Abbrev;
  2120. }
  2121. bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
  2122. bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
  2123. for (unsigned i = 0; i != NumElts; ++i) {
  2124. unsigned char V = Str->getElementAsInteger(i);
  2125. Record.push_back(V);
  2126. isCStr7 &= (V & 128) == 0;
  2127. if (isCStrChar6)
  2128. isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
  2129. }
  2130. if (isCStrChar6)
  2131. AbbrevToUse = CString6Abbrev;
  2132. else if (isCStr7)
  2133. AbbrevToUse = CString7Abbrev;
  2134. } else if (const ConstantDataSequential *CDS =
  2135. dyn_cast<ConstantDataSequential>(C)) {
  2136. Code = bitc::CST_CODE_DATA;
  2137. Type *EltTy = CDS->getType()->getElementType();
  2138. if (isa<IntegerType>(EltTy)) {
  2139. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
  2140. Record.push_back(CDS->getElementAsInteger(i));
  2141. } else {
  2142. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
  2143. Record.push_back(
  2144. CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
  2145. }
  2146. } else if (isa<ConstantAggregate>(C)) {
  2147. Code = bitc::CST_CODE_AGGREGATE;
  2148. for (const Value *Op : C->operands())
  2149. Record.push_back(VE.getValueID(Op));
  2150. AbbrevToUse = AggregateAbbrev;
  2151. } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  2152. switch (CE->getOpcode()) {
  2153. default:
  2154. if (Instruction::isCast(CE->getOpcode())) {
  2155. Code = bitc::CST_CODE_CE_CAST;
  2156. Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
  2157. Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
  2158. Record.push_back(VE.getValueID(C->getOperand(0)));
  2159. AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
  2160. } else {
  2161. assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
  2162. Code = bitc::CST_CODE_CE_BINOP;
  2163. Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
  2164. Record.push_back(VE.getValueID(C->getOperand(0)));
  2165. Record.push_back(VE.getValueID(C->getOperand(1)));
  2166. uint64_t Flags = getOptimizationFlags(CE);
  2167. if (Flags != 0)
  2168. Record.push_back(Flags);
  2169. }
  2170. break;
  2171. case Instruction::FNeg: {
  2172. assert(CE->getNumOperands() == 1 && "Unknown constant expr!");
  2173. Code = bitc::CST_CODE_CE_UNOP;
  2174. Record.push_back(getEncodedUnaryOpcode(CE->getOpcode()));
  2175. Record.push_back(VE.getValueID(C->getOperand(0)));
  2176. uint64_t Flags = getOptimizationFlags(CE);
  2177. if (Flags != 0)
  2178. Record.push_back(Flags);
  2179. break;
  2180. }
  2181. case Instruction::GetElementPtr: {
  2182. Code = bitc::CST_CODE_CE_GEP;
  2183. const auto *GO = cast<GEPOperator>(C);
  2184. Record.push_back(VE.getTypeID(GO->getSourceElementType()));
  2185. if (Optional<unsigned> Idx = GO->getInRangeIndex()) {
  2186. Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX;
  2187. Record.push_back((*Idx << 1) | GO->isInBounds());
  2188. } else if (GO->isInBounds())
  2189. Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
  2190. for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
  2191. Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
  2192. Record.push_back(VE.getValueID(C->getOperand(i)));
  2193. }
  2194. break;
  2195. }
  2196. case Instruction::Select:
  2197. Code = bitc::CST_CODE_CE_SELECT;
  2198. Record.push_back(VE.getValueID(C->getOperand(0)));
  2199. Record.push_back(VE.getValueID(C->getOperand(1)));
  2200. Record.push_back(VE.getValueID(C->getOperand(2)));
  2201. break;
  2202. case Instruction::ExtractElement:
  2203. Code = bitc::CST_CODE_CE_EXTRACTELT;
  2204. Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
  2205. Record.push_back(VE.getValueID(C->getOperand(0)));
  2206. Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
  2207. Record.push_back(VE.getValueID(C->getOperand(1)));
  2208. break;
  2209. case Instruction::InsertElement:
  2210. Code = bitc::CST_CODE_CE_INSERTELT;
  2211. Record.push_back(VE.getValueID(C->getOperand(0)));
  2212. Record.push_back(VE.getValueID(C->getOperand(1)));
  2213. Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
  2214. Record.push_back(VE.getValueID(C->getOperand(2)));
  2215. break;
  2216. case Instruction::ShuffleVector:
  2217. // If the return type and argument types are the same, this is a
  2218. // standard shufflevector instruction. If the types are different,
  2219. // then the shuffle is widening or truncating the input vectors, and
  2220. // the argument type must also be encoded.
  2221. if (C->getType() == C->getOperand(0)->getType()) {
  2222. Code = bitc::CST_CODE_CE_SHUFFLEVEC;
  2223. } else {
  2224. Code = bitc::CST_CODE_CE_SHUFVEC_EX;
  2225. Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
  2226. }
  2227. Record.push_back(VE.getValueID(C->getOperand(0)));
  2228. Record.push_back(VE.getValueID(C->getOperand(1)));
  2229. Record.push_back(VE.getValueID(C->getOperand(2)));
  2230. break;
  2231. case Instruction::ICmp:
  2232. case Instruction::FCmp:
  2233. Code = bitc::CST_CODE_CE_CMP;
  2234. Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
  2235. Record.push_back(VE.getValueID(C->getOperand(0)));
  2236. Record.push_back(VE.getValueID(C->getOperand(1)));
  2237. Record.push_back(CE->getPredicate());
  2238. break;
  2239. }
  2240. } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
  2241. Code = bitc::CST_CODE_BLOCKADDRESS;
  2242. Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
  2243. Record.push_back(VE.getValueID(BA->getFunction()));
  2244. Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
  2245. } else {
  2246. #ifndef NDEBUG
  2247. C->dump();
  2248. #endif
  2249. llvm_unreachable("Unknown constant!");
  2250. }
  2251. Stream.EmitRecord(Code, Record, AbbrevToUse);
  2252. Record.clear();
  2253. }
  2254. Stream.ExitBlock();
  2255. }
  2256. void ModuleBitcodeWriter::writeModuleConstants() {
  2257. const ValueEnumerator::ValueList &Vals = VE.getValues();
  2258. // Find the first constant to emit, which is the first non-globalvalue value.
  2259. // We know globalvalues have been emitted by WriteModuleInfo.
  2260. for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
  2261. if (!isa<GlobalValue>(Vals[i].first)) {
  2262. writeConstants(i, Vals.size(), true);
  2263. return;
  2264. }
  2265. }
  2266. }
  2267. /// pushValueAndType - The file has to encode both the value and type id for
  2268. /// many values, because we need to know what type to create for forward
  2269. /// references. However, most operands are not forward references, so this type
  2270. /// field is not needed.
  2271. ///
  2272. /// This function adds V's value ID to Vals. If the value ID is higher than the
  2273. /// instruction ID, then it is a forward reference, and it also includes the
  2274. /// type ID. The value ID that is written is encoded relative to the InstID.
  2275. bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
  2276. SmallVectorImpl<unsigned> &Vals) {
  2277. unsigned ValID = VE.getValueID(V);
  2278. // Make encoding relative to the InstID.
  2279. Vals.push_back(InstID - ValID);
  2280. if (ValID >= InstID) {
  2281. Vals.push_back(VE.getTypeID(V->getType()));
  2282. return true;
  2283. }
  2284. return false;
  2285. }
  2286. void ModuleBitcodeWriter::writeOperandBundles(ImmutableCallSite CS,
  2287. unsigned InstID) {
  2288. SmallVector<unsigned, 64> Record;
  2289. LLVMContext &C = CS.getInstruction()->getContext();
  2290. for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
  2291. const auto &Bundle = CS.getOperandBundleAt(i);
  2292. Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
  2293. for (auto &Input : Bundle.Inputs)
  2294. pushValueAndType(Input, InstID, Record);
  2295. Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
  2296. Record.clear();
  2297. }
  2298. }
  2299. /// pushValue - Like pushValueAndType, but where the type of the value is
  2300. /// omitted (perhaps it was already encoded in an earlier operand).
  2301. void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
  2302. SmallVectorImpl<unsigned> &Vals) {
  2303. unsigned ValID = VE.getValueID(V);
  2304. Vals.push_back(InstID - ValID);
  2305. }
  2306. void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
  2307. SmallVectorImpl<uint64_t> &Vals) {
  2308. unsigned ValID = VE.getValueID(V);
  2309. int64_t diff = ((int32_t)InstID - (int32_t)ValID);
  2310. emitSignedInt64(Vals, diff);
  2311. }
  2312. /// WriteInstruction - Emit an instruction to the specified stream.
  2313. void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
  2314. unsigned InstID,
  2315. SmallVectorImpl<unsigned> &Vals) {
  2316. unsigned Code = 0;
  2317. unsigned AbbrevToUse = 0;
  2318. VE.setInstructionID(&I);
  2319. switch (I.getOpcode()) {
  2320. default:
  2321. if (Instruction::isCast(I.getOpcode())) {
  2322. Code = bitc::FUNC_CODE_INST_CAST;
  2323. if (!pushValueAndType(I.getOperand(0), InstID, Vals))
  2324. AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
  2325. Vals.push_back(VE.getTypeID(I.getType()));
  2326. Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
  2327. } else {
  2328. assert(isa<BinaryOperator>(I) && "Unknown instruction!");
  2329. Code = bitc::FUNC_CODE_INST_BINOP;
  2330. if (!pushValueAndType(I.getOperand(0), InstID, Vals))
  2331. AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
  2332. pushValue(I.getOperand(1), InstID, Vals);
  2333. Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
  2334. uint64_t Flags = getOptimizationFlags(&I);
  2335. if (Flags != 0) {
  2336. if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
  2337. AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
  2338. Vals.push_back(Flags);
  2339. }
  2340. }
  2341. break;
  2342. case Instruction::FNeg: {
  2343. Code = bitc::FUNC_CODE_INST_UNOP;
  2344. if (!pushValueAndType(I.getOperand(0), InstID, Vals))
  2345. AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
  2346. Vals.push_back(getEncodedUnaryOpcode(I.getOpcode()));
  2347. uint64_t Flags = getOptimizationFlags(&I);
  2348. if (Flags != 0) {
  2349. if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
  2350. AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
  2351. Vals.push_back(Flags);
  2352. }
  2353. break;
  2354. }
  2355. case Instruction::GetElementPtr: {
  2356. Code = bitc::FUNC_CODE_INST_GEP;
  2357. AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
  2358. auto &GEPInst = cast<GetElementPtrInst>(I);
  2359. Vals.push_back(GEPInst.isInBounds());
  2360. Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
  2361. for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
  2362. pushValueAndType(I.getOperand(i), InstID, Vals);
  2363. break;
  2364. }
  2365. case Instruction::ExtractValue: {
  2366. Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
  2367. pushValueAndType(I.getOperand(0), InstID, Vals);
  2368. const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
  2369. Vals.append(EVI->idx_begin(), EVI->idx_end());
  2370. break;
  2371. }
  2372. case Instruction::InsertValue: {
  2373. Code = bitc::FUNC_CODE_INST_INSERTVAL;
  2374. pushValueAndType(I.getOperand(0), InstID, Vals);
  2375. pushValueAndType(I.getOperand(1), InstID, Vals);
  2376. const InsertValueInst *IVI = cast<InsertValueInst>(&I);
  2377. Vals.append(IVI->idx_begin(), IVI->idx_end());
  2378. break;
  2379. }
  2380. case Instruction::Select: {
  2381. Code = bitc::FUNC_CODE_INST_VSELECT;
  2382. pushValueAndType(I.getOperand(1), InstID, Vals);
  2383. pushValue(I.getOperand(2), InstID, Vals);
  2384. pushValueAndType(I.getOperand(0), InstID, Vals);
  2385. uint64_t Flags = getOptimizationFlags(&I);
  2386. if (Flags != 0)
  2387. Vals.push_back(Flags);
  2388. break;
  2389. }
  2390. case Instruction::ExtractElement:
  2391. Code = bitc::FUNC_CODE_INST_EXTRACTELT;
  2392. pushValueAndType(I.getOperand(0), InstID, Vals);
  2393. pushValueAndType(I.getOperand(1), InstID, Vals);
  2394. break;
  2395. case Instruction::InsertElement:
  2396. Code = bitc::FUNC_CODE_INST_INSERTELT;
  2397. pushValueAndType(I.getOperand(0), InstID, Vals);
  2398. pushValue(I.getOperand(1), InstID, Vals);
  2399. pushValueAndType(I.getOperand(2), InstID, Vals);
  2400. break;
  2401. case Instruction::ShuffleVector:
  2402. Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
  2403. pushValueAndType(I.getOperand(0), InstID, Vals);
  2404. pushValue(I.getOperand(1), InstID, Vals);
  2405. pushValue(I.getOperand(2), InstID, Vals);
  2406. break;
  2407. case Instruction::ICmp:
  2408. case Instruction::FCmp: {
  2409. // compare returning Int1Ty or vector of Int1Ty
  2410. Code = bitc::FUNC_CODE_INST_CMP2;
  2411. pushValueAndType(I.getOperand(0), InstID, Vals);
  2412. pushValue(I.getOperand(1), InstID, Vals);
  2413. Vals.push_back(cast<CmpInst>(I).getPredicate());
  2414. uint64_t Flags = getOptimizationFlags(&I);
  2415. if (Flags != 0)
  2416. Vals.push_back(Flags);
  2417. break;
  2418. }
  2419. case Instruction::Ret:
  2420. {
  2421. Code = bitc::FUNC_CODE_INST_RET;
  2422. unsigned NumOperands = I.getNumOperands();
  2423. if (NumOperands == 0)
  2424. AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
  2425. else if (NumOperands == 1) {
  2426. if (!pushValueAndType(I.getOperand(0), InstID, Vals))
  2427. AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
  2428. } else {
  2429. for (unsigned i = 0, e = NumOperands; i != e; ++i)
  2430. pushValueAndType(I.getOperand(i), InstID, Vals);
  2431. }
  2432. }
  2433. break;
  2434. case Instruction::Br:
  2435. {
  2436. Code = bitc::FUNC_CODE_INST_BR;
  2437. const BranchInst &II = cast<BranchInst>(I);
  2438. Vals.push_back(VE.getValueID(II.getSuccessor(0)));
  2439. if (II.isConditional()) {
  2440. Vals.push_back(VE.getValueID(II.getSuccessor(1)));
  2441. pushValue(II.getCondition(), InstID, Vals);
  2442. }
  2443. }
  2444. break;
  2445. case Instruction::Switch:
  2446. {
  2447. Code = bitc::FUNC_CODE_INST_SWITCH;
  2448. const SwitchInst &SI = cast<SwitchInst>(I);
  2449. Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
  2450. pushValue(SI.getCondition(), InstID, Vals);
  2451. Vals.push_back(VE.getValueID(SI.getDefaultDest()));
  2452. for (auto Case : SI.cases()) {
  2453. Vals.push_back(VE.getValueID(Case.getCaseValue()));
  2454. Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
  2455. }
  2456. }
  2457. break;
  2458. case Instruction::IndirectBr:
  2459. Code = bitc::FUNC_CODE_INST_INDIRECTBR;
  2460. Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
  2461. // Encode the address operand as relative, but not the basic blocks.
  2462. pushValue(I.getOperand(0), InstID, Vals);
  2463. for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
  2464. Vals.push_back(VE.getValueID(I.getOperand(i)));
  2465. break;
  2466. case Instruction::Invoke: {
  2467. const InvokeInst *II = cast<InvokeInst>(&I);
  2468. const Value *Callee = II->getCalledValue();
  2469. FunctionType *FTy = II->getFunctionType();
  2470. if (II->hasOperandBundles())
  2471. writeOperandBundles(II, InstID);
  2472. Code = bitc::FUNC_CODE_INST_INVOKE;
  2473. Vals.push_back(VE.getAttributeListID(II->getAttributes()));
  2474. Vals.push_back(II->getCallingConv() | 1 << 13);
  2475. Vals.push_back(VE.getValueID(II->getNormalDest()));
  2476. Vals.push_back(VE.getValueID(II->getUnwindDest()));
  2477. Vals.push_back(VE.getTypeID(FTy));
  2478. pushValueAndType(Callee, InstID, Vals);
  2479. // Emit value #'s for the fixed parameters.
  2480. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
  2481. pushValue(I.getOperand(i), InstID, Vals); // fixed param.
  2482. // Emit type/value pairs for varargs params.
  2483. if (FTy->isVarArg()) {
  2484. for (unsigned i = FTy->getNumParams(), e = II->getNumArgOperands();
  2485. i != e; ++i)
  2486. pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
  2487. }
  2488. break;
  2489. }
  2490. case Instruction::Resume:
  2491. Code = bitc::FUNC_CODE_INST_RESUME;
  2492. pushValueAndType(I.getOperand(0), InstID, Vals);
  2493. break;
  2494. case Instruction::CleanupRet: {
  2495. Code = bitc::FUNC_CODE_INST_CLEANUPRET;
  2496. const auto &CRI = cast<CleanupReturnInst>(I);
  2497. pushValue(CRI.getCleanupPad(), InstID, Vals);
  2498. if (CRI.hasUnwindDest())
  2499. Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
  2500. break;
  2501. }
  2502. case Instruction::CatchRet: {
  2503. Code = bitc::FUNC_CODE_INST_CATCHRET;
  2504. const auto &CRI = cast<CatchReturnInst>(I);
  2505. pushValue(CRI.getCatchPad(), InstID, Vals);
  2506. Vals.push_back(VE.getValueID(CRI.getSuccessor()));
  2507. break;
  2508. }
  2509. case Instruction::CleanupPad:
  2510. case Instruction::CatchPad: {
  2511. const auto &FuncletPad = cast<FuncletPadInst>(I);
  2512. Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
  2513. : bitc::FUNC_CODE_INST_CLEANUPPAD;
  2514. pushValue(FuncletPad.getParentPad(), InstID, Vals);
  2515. unsigned NumArgOperands = FuncletPad.getNumArgOperands();
  2516. Vals.push_back(NumArgOperands);
  2517. for (unsigned Op = 0; Op != NumArgOperands; ++Op)
  2518. pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
  2519. break;
  2520. }
  2521. case Instruction::CatchSwitch: {
  2522. Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
  2523. const auto &CatchSwitch = cast<CatchSwitchInst>(I);
  2524. pushValue(CatchSwitch.getParentPad(), InstID, Vals);
  2525. unsigned NumHandlers = CatchSwitch.getNumHandlers();
  2526. Vals.push_back(NumHandlers);
  2527. for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
  2528. Vals.push_back(VE.getValueID(CatchPadBB));
  2529. if (CatchSwitch.hasUnwindDest())
  2530. Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
  2531. break;
  2532. }
  2533. case Instruction::CallBr: {
  2534. const CallBrInst *CBI = cast<CallBrInst>(&I);
  2535. const Value *Callee = CBI->getCalledValue();
  2536. FunctionType *FTy = CBI->getFunctionType();
  2537. if (CBI->hasOperandBundles())
  2538. writeOperandBundles(CBI, InstID);
  2539. Code = bitc::FUNC_CODE_INST_CALLBR;
  2540. Vals.push_back(VE.getAttributeListID(CBI->getAttributes()));
  2541. Vals.push_back(CBI->getCallingConv() << bitc::CALL_CCONV |
  2542. 1 << bitc::CALL_EXPLICIT_TYPE);
  2543. Vals.push_back(VE.getValueID(CBI->getDefaultDest()));
  2544. Vals.push_back(CBI->getNumIndirectDests());
  2545. for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
  2546. Vals.push_back(VE.getValueID(CBI->getIndirectDest(i)));
  2547. Vals.push_back(VE.getTypeID(FTy));
  2548. pushValueAndType(Callee, InstID, Vals);
  2549. // Emit value #'s for the fixed parameters.
  2550. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
  2551. pushValue(I.getOperand(i), InstID, Vals); // fixed param.
  2552. // Emit type/value pairs for varargs params.
  2553. if (FTy->isVarArg()) {
  2554. for (unsigned i = FTy->getNumParams(), e = CBI->getNumArgOperands();
  2555. i != e; ++i)
  2556. pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
  2557. }
  2558. break;
  2559. }
  2560. case Instruction::Unreachable:
  2561. Code = bitc::FUNC_CODE_INST_UNREACHABLE;
  2562. AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
  2563. break;
  2564. case Instruction::PHI: {
  2565. const PHINode &PN = cast<PHINode>(I);
  2566. Code = bitc::FUNC_CODE_INST_PHI;
  2567. // With the newer instruction encoding, forward references could give
  2568. // negative valued IDs. This is most common for PHIs, so we use
  2569. // signed VBRs.
  2570. SmallVector<uint64_t, 128> Vals64;
  2571. Vals64.push_back(VE.getTypeID(PN.getType()));
  2572. for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
  2573. pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
  2574. Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
  2575. }
  2576. // Emit a Vals64 vector and exit.
  2577. Stream.EmitRecord(Code, Vals64, AbbrevToUse);
  2578. Vals64.clear();
  2579. return;
  2580. }
  2581. case Instruction::LandingPad: {
  2582. const LandingPadInst &LP = cast<LandingPadInst>(I);
  2583. Code = bitc::FUNC_CODE_INST_LANDINGPAD;
  2584. Vals.push_back(VE.getTypeID(LP.getType()));
  2585. Vals.push_back(LP.isCleanup());
  2586. Vals.push_back(LP.getNumClauses());
  2587. for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
  2588. if (LP.isCatch(I))
  2589. Vals.push_back(LandingPadInst::Catch);
  2590. else
  2591. Vals.push_back(LandingPadInst::Filter);
  2592. pushValueAndType(LP.getClause(I), InstID, Vals);
  2593. }
  2594. break;
  2595. }
  2596. case Instruction::Alloca: {
  2597. Code = bitc::FUNC_CODE_INST_ALLOCA;
  2598. const AllocaInst &AI = cast<AllocaInst>(I);
  2599. Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
  2600. Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
  2601. Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
  2602. unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
  2603. assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
  2604. "not enough bits for maximum alignment");
  2605. assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
  2606. AlignRecord |= AI.isUsedWithInAlloca() << 5;
  2607. AlignRecord |= 1 << 6;
  2608. AlignRecord |= AI.isSwiftError() << 7;
  2609. Vals.push_back(AlignRecord);
  2610. break;
  2611. }
  2612. case Instruction::Load:
  2613. if (cast<LoadInst>(I).isAtomic()) {
  2614. Code = bitc::FUNC_CODE_INST_LOADATOMIC;
  2615. pushValueAndType(I.getOperand(0), InstID, Vals);
  2616. } else {
  2617. Code = bitc::FUNC_CODE_INST_LOAD;
  2618. if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
  2619. AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
  2620. }
  2621. Vals.push_back(VE.getTypeID(I.getType()));
  2622. Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
  2623. Vals.push_back(cast<LoadInst>(I).isVolatile());
  2624. if (cast<LoadInst>(I).isAtomic()) {
  2625. Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
  2626. Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
  2627. }
  2628. break;
  2629. case Instruction::Store:
  2630. if (cast<StoreInst>(I).isAtomic())
  2631. Code = bitc::FUNC_CODE_INST_STOREATOMIC;
  2632. else
  2633. Code = bitc::FUNC_CODE_INST_STORE;
  2634. pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
  2635. pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
  2636. Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
  2637. Vals.push_back(cast<StoreInst>(I).isVolatile());
  2638. if (cast<StoreInst>(I).isAtomic()) {
  2639. Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
  2640. Vals.push_back(
  2641. getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
  2642. }
  2643. break;
  2644. case Instruction::AtomicCmpXchg:
  2645. Code = bitc::FUNC_CODE_INST_CMPXCHG;
  2646. pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
  2647. pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
  2648. pushValue(I.getOperand(2), InstID, Vals); // newval.
  2649. Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
  2650. Vals.push_back(
  2651. getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
  2652. Vals.push_back(
  2653. getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
  2654. Vals.push_back(
  2655. getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
  2656. Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
  2657. break;
  2658. case Instruction::AtomicRMW:
  2659. Code = bitc::FUNC_CODE_INST_ATOMICRMW;
  2660. pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
  2661. pushValue(I.getOperand(1), InstID, Vals); // val.
  2662. Vals.push_back(
  2663. getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
  2664. Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
  2665. Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
  2666. Vals.push_back(
  2667. getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
  2668. break;
  2669. case Instruction::Fence:
  2670. Code = bitc::FUNC_CODE_INST_FENCE;
  2671. Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
  2672. Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
  2673. break;
  2674. case Instruction::Call: {
  2675. const CallInst &CI = cast<CallInst>(I);
  2676. FunctionType *FTy = CI.getFunctionType();
  2677. if (CI.hasOperandBundles())
  2678. writeOperandBundles(&CI, InstID);
  2679. Code = bitc::FUNC_CODE_INST_CALL;
  2680. Vals.push_back(VE.getAttributeListID(CI.getAttributes()));
  2681. unsigned Flags = getOptimizationFlags(&I);
  2682. Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
  2683. unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
  2684. unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
  2685. 1 << bitc::CALL_EXPLICIT_TYPE |
  2686. unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
  2687. unsigned(Flags != 0) << bitc::CALL_FMF);
  2688. if (Flags != 0)
  2689. Vals.push_back(Flags);
  2690. Vals.push_back(VE.getTypeID(FTy));
  2691. pushValueAndType(CI.getCalledValue(), InstID, Vals); // Callee
  2692. // Emit value #'s for the fixed parameters.
  2693. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
  2694. // Check for labels (can happen with asm labels).
  2695. if (FTy->getParamType(i)->isLabelTy())
  2696. Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
  2697. else
  2698. pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
  2699. }
  2700. // Emit type/value pairs for varargs params.
  2701. if (FTy->isVarArg()) {
  2702. for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
  2703. i != e; ++i)
  2704. pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
  2705. }
  2706. break;
  2707. }
  2708. case Instruction::VAArg:
  2709. Code = bitc::FUNC_CODE_INST_VAARG;
  2710. Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
  2711. pushValue(I.getOperand(0), InstID, Vals); // valist.
  2712. Vals.push_back(VE.getTypeID(I.getType())); // restype.
  2713. break;
  2714. }
  2715. Stream.EmitRecord(Code, Vals, AbbrevToUse);
  2716. Vals.clear();
  2717. }
  2718. /// Write a GlobalValue VST to the module. The purpose of this data structure is
  2719. /// to allow clients to efficiently find the function body.
  2720. void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
  2721. DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
  2722. // Get the offset of the VST we are writing, and backpatch it into
  2723. // the VST forward declaration record.
  2724. uint64_t VSTOffset = Stream.GetCurrentBitNo();
  2725. // The BitcodeStartBit was the stream offset of the identification block.
  2726. VSTOffset -= bitcodeStartBit();
  2727. assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
  2728. // Note that we add 1 here because the offset is relative to one word
  2729. // before the start of the identification block, which was historically
  2730. // always the start of the regular bitcode header.
  2731. Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
  2732. Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
  2733. auto Abbv = std::make_shared<BitCodeAbbrev>();
  2734. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
  2735. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
  2736. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
  2737. unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  2738. for (const Function &F : M) {
  2739. uint64_t Record[2];
  2740. if (F.isDeclaration())
  2741. continue;
  2742. Record[0] = VE.getValueID(&F);
  2743. // Save the word offset of the function (from the start of the
  2744. // actual bitcode written to the stream).
  2745. uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
  2746. assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
  2747. // Note that we add 1 here because the offset is relative to one word
  2748. // before the start of the identification block, which was historically
  2749. // always the start of the regular bitcode header.
  2750. Record[1] = BitcodeIndex / 32 + 1;
  2751. Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
  2752. }
  2753. Stream.ExitBlock();
  2754. }
  2755. /// Emit names for arguments, instructions and basic blocks in a function.
  2756. void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
  2757. const ValueSymbolTable &VST) {
  2758. if (VST.empty())
  2759. return;
  2760. Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
  2761. // FIXME: Set up the abbrev, we know how many values there are!
  2762. // FIXME: We know if the type names can use 7-bit ascii.
  2763. SmallVector<uint64_t, 64> NameVals;
  2764. for (const ValueName &Name : VST) {
  2765. // Figure out the encoding to use for the name.
  2766. StringEncoding Bits = getStringEncoding(Name.getKey());
  2767. unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
  2768. NameVals.push_back(VE.getValueID(Name.getValue()));
  2769. // VST_CODE_ENTRY: [valueid, namechar x N]
  2770. // VST_CODE_BBENTRY: [bbid, namechar x N]
  2771. unsigned Code;
  2772. if (isa<BasicBlock>(Name.getValue())) {
  2773. Code = bitc::VST_CODE_BBENTRY;
  2774. if (Bits == SE_Char6)
  2775. AbbrevToUse = VST_BBENTRY_6_ABBREV;
  2776. } else {
  2777. Code = bitc::VST_CODE_ENTRY;
  2778. if (Bits == SE_Char6)
  2779. AbbrevToUse = VST_ENTRY_6_ABBREV;
  2780. else if (Bits == SE_Fixed7)
  2781. AbbrevToUse = VST_ENTRY_7_ABBREV;
  2782. }
  2783. for (const auto P : Name.getKey())
  2784. NameVals.push_back((unsigned char)P);
  2785. // Emit the finished record.
  2786. Stream.EmitRecord(Code, NameVals, AbbrevToUse);
  2787. NameVals.clear();
  2788. }
  2789. Stream.ExitBlock();
  2790. }
  2791. void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
  2792. assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
  2793. unsigned Code;
  2794. if (isa<BasicBlock>(Order.V))
  2795. Code = bitc::USELIST_CODE_BB;
  2796. else
  2797. Code = bitc::USELIST_CODE_DEFAULT;
  2798. SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
  2799. Record.push_back(VE.getValueID(Order.V));
  2800. Stream.EmitRecord(Code, Record);
  2801. }
  2802. void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
  2803. assert(VE.shouldPreserveUseListOrder() &&
  2804. "Expected to be preserving use-list order");
  2805. auto hasMore = [&]() {
  2806. return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
  2807. };
  2808. if (!hasMore())
  2809. // Nothing to do.
  2810. return;
  2811. Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
  2812. while (hasMore()) {
  2813. writeUseList(std::move(VE.UseListOrders.back()));
  2814. VE.UseListOrders.pop_back();
  2815. }
  2816. Stream.ExitBlock();
  2817. }
  2818. /// Emit a function body to the module stream.
  2819. void ModuleBitcodeWriter::writeFunction(
  2820. const Function &F,
  2821. DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
  2822. // Save the bitcode index of the start of this function block for recording
  2823. // in the VST.
  2824. FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
  2825. Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
  2826. VE.incorporateFunction(F);
  2827. SmallVector<unsigned, 64> Vals;
  2828. // Emit the number of basic blocks, so the reader can create them ahead of
  2829. // time.
  2830. Vals.push_back(VE.getBasicBlocks().size());
  2831. Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
  2832. Vals.clear();
  2833. // If there are function-local constants, emit them now.
  2834. unsigned CstStart, CstEnd;
  2835. VE.getFunctionConstantRange(CstStart, CstEnd);
  2836. writeConstants(CstStart, CstEnd, false);
  2837. // If there is function-local metadata, emit it now.
  2838. writeFunctionMetadata(F);
  2839. // Keep a running idea of what the instruction ID is.
  2840. unsigned InstID = CstEnd;
  2841. bool NeedsMetadataAttachment = F.hasMetadata();
  2842. DILocation *LastDL = nullptr;
  2843. // Finally, emit all the instructions, in order.
  2844. for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
  2845. for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
  2846. I != E; ++I) {
  2847. writeInstruction(*I, InstID, Vals);
  2848. if (!I->getType()->isVoidTy())
  2849. ++InstID;
  2850. // If the instruction has metadata, write a metadata attachment later.
  2851. NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
  2852. // If the instruction has a debug location, emit it.
  2853. DILocation *DL = I->getDebugLoc();
  2854. if (!DL)
  2855. continue;
  2856. if (DL == LastDL) {
  2857. // Just repeat the same debug loc as last time.
  2858. Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
  2859. continue;
  2860. }
  2861. Vals.push_back(DL->getLine());
  2862. Vals.push_back(DL->getColumn());
  2863. Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
  2864. Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
  2865. Vals.push_back(DL->isImplicitCode());
  2866. Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
  2867. Vals.clear();
  2868. LastDL = DL;
  2869. }
  2870. // Emit names for all the instructions etc.
  2871. if (auto *Symtab = F.getValueSymbolTable())
  2872. writeFunctionLevelValueSymbolTable(*Symtab);
  2873. if (NeedsMetadataAttachment)
  2874. writeFunctionMetadataAttachment(F);
  2875. if (VE.shouldPreserveUseListOrder())
  2876. writeUseListBlock(&F);
  2877. VE.purgeFunction();
  2878. Stream.ExitBlock();
  2879. }
  2880. // Emit blockinfo, which defines the standard abbreviations etc.
  2881. void ModuleBitcodeWriter::writeBlockInfo() {
  2882. // We only want to emit block info records for blocks that have multiple
  2883. // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
  2884. // Other blocks can define their abbrevs inline.
  2885. Stream.EnterBlockInfoBlock();
  2886. { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
  2887. auto Abbv = std::make_shared<BitCodeAbbrev>();
  2888. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
  2889. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  2890. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2891. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
  2892. if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
  2893. VST_ENTRY_8_ABBREV)
  2894. llvm_unreachable("Unexpected abbrev ordering!");
  2895. }
  2896. { // 7-bit fixed width VST_CODE_ENTRY strings.
  2897. auto Abbv = std::make_shared<BitCodeAbbrev>();
  2898. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
  2899. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  2900. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2901. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
  2902. if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
  2903. VST_ENTRY_7_ABBREV)
  2904. llvm_unreachable("Unexpected abbrev ordering!");
  2905. }
  2906. { // 6-bit char6 VST_CODE_ENTRY strings.
  2907. auto Abbv = std::make_shared<BitCodeAbbrev>();
  2908. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
  2909. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  2910. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2911. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  2912. if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
  2913. VST_ENTRY_6_ABBREV)
  2914. llvm_unreachable("Unexpected abbrev ordering!");
  2915. }
  2916. { // 6-bit char6 VST_CODE_BBENTRY strings.
  2917. auto Abbv = std::make_shared<BitCodeAbbrev>();
  2918. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
  2919. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  2920. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2921. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  2922. if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
  2923. VST_BBENTRY_6_ABBREV)
  2924. llvm_unreachable("Unexpected abbrev ordering!");
  2925. }
  2926. { // SETTYPE abbrev for CONSTANTS_BLOCK.
  2927. auto Abbv = std::make_shared<BitCodeAbbrev>();
  2928. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
  2929. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  2930. VE.computeBitsRequiredForTypeIndicies()));
  2931. if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
  2932. CONSTANTS_SETTYPE_ABBREV)
  2933. llvm_unreachable("Unexpected abbrev ordering!");
  2934. }
  2935. { // INTEGER abbrev for CONSTANTS_BLOCK.
  2936. auto Abbv = std::make_shared<BitCodeAbbrev>();
  2937. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
  2938. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  2939. if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
  2940. CONSTANTS_INTEGER_ABBREV)
  2941. llvm_unreachable("Unexpected abbrev ordering!");
  2942. }
  2943. { // CE_CAST abbrev for CONSTANTS_BLOCK.
  2944. auto Abbv = std::make_shared<BitCodeAbbrev>();
  2945. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
  2946. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
  2947. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
  2948. VE.computeBitsRequiredForTypeIndicies()));
  2949. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
  2950. if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
  2951. CONSTANTS_CE_CAST_Abbrev)
  2952. llvm_unreachable("Unexpected abbrev ordering!");
  2953. }
  2954. { // NULL abbrev for CONSTANTS_BLOCK.
  2955. auto Abbv = std::make_shared<BitCodeAbbrev>();
  2956. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
  2957. if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
  2958. CONSTANTS_NULL_Abbrev)
  2959. llvm_unreachable("Unexpected abbrev ordering!");
  2960. }
  2961. // FIXME: This should only use space for first class types!
  2962. { // INST_LOAD abbrev for FUNCTION_BLOCK.
  2963. auto Abbv = std::make_shared<BitCodeAbbrev>();
  2964. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
  2965. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
  2966. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
  2967. VE.computeBitsRequiredForTypeIndicies()));
  2968. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
  2969. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
  2970. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
  2971. FUNCTION_INST_LOAD_ABBREV)
  2972. llvm_unreachable("Unexpected abbrev ordering!");
  2973. }
  2974. { // INST_UNOP abbrev for FUNCTION_BLOCK.
  2975. auto Abbv = std::make_shared<BitCodeAbbrev>();
  2976. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
  2977. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
  2978. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
  2979. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
  2980. FUNCTION_INST_UNOP_ABBREV)
  2981. llvm_unreachable("Unexpected abbrev ordering!");
  2982. }
  2983. { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.
  2984. auto Abbv = std::make_shared<BitCodeAbbrev>();
  2985. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
  2986. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
  2987. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
  2988. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
  2989. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
  2990. FUNCTION_INST_UNOP_FLAGS_ABBREV)
  2991. llvm_unreachable("Unexpected abbrev ordering!");
  2992. }
  2993. { // INST_BINOP abbrev for FUNCTION_BLOCK.
  2994. auto Abbv = std::make_shared<BitCodeAbbrev>();
  2995. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
  2996. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
  2997. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
  2998. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
  2999. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
  3000. FUNCTION_INST_BINOP_ABBREV)
  3001. llvm_unreachable("Unexpected abbrev ordering!");
  3002. }
  3003. { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
  3004. auto Abbv = std::make_shared<BitCodeAbbrev>();
  3005. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
  3006. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
  3007. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
  3008. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
  3009. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
  3010. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
  3011. FUNCTION_INST_BINOP_FLAGS_ABBREV)
  3012. llvm_unreachable("Unexpected abbrev ordering!");
  3013. }
  3014. { // INST_CAST abbrev for FUNCTION_BLOCK.
  3015. auto Abbv = std::make_shared<BitCodeAbbrev>();
  3016. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
  3017. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
  3018. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
  3019. VE.computeBitsRequiredForTypeIndicies()));
  3020. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
  3021. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
  3022. FUNCTION_INST_CAST_ABBREV)
  3023. llvm_unreachable("Unexpected abbrev ordering!");
  3024. }
  3025. { // INST_RET abbrev for FUNCTION_BLOCK.
  3026. auto Abbv = std::make_shared<BitCodeAbbrev>();
  3027. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
  3028. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
  3029. FUNCTION_INST_RET_VOID_ABBREV)
  3030. llvm_unreachable("Unexpected abbrev ordering!");
  3031. }
  3032. { // INST_RET abbrev for FUNCTION_BLOCK.
  3033. auto Abbv = std::make_shared<BitCodeAbbrev>();
  3034. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
  3035. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
  3036. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
  3037. FUNCTION_INST_RET_VAL_ABBREV)
  3038. llvm_unreachable("Unexpected abbrev ordering!");
  3039. }
  3040. { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
  3041. auto Abbv = std::make_shared<BitCodeAbbrev>();
  3042. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
  3043. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
  3044. FUNCTION_INST_UNREACHABLE_ABBREV)
  3045. llvm_unreachable("Unexpected abbrev ordering!");
  3046. }
  3047. {
  3048. auto Abbv = std::make_shared<BitCodeAbbrev>();
  3049. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
  3050. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
  3051. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
  3052. Log2_32_Ceil(VE.getTypes().size() + 1)));
  3053. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  3054. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  3055. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
  3056. FUNCTION_INST_GEP_ABBREV)
  3057. llvm_unreachable("Unexpected abbrev ordering!");
  3058. }
  3059. Stream.ExitBlock();
  3060. }
  3061. /// Write the module path strings, currently only used when generating
  3062. /// a combined index file.
  3063. void IndexBitcodeWriter::writeModStrings() {
  3064. Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
  3065. // TODO: See which abbrev sizes we actually need to emit
  3066. // 8-bit fixed-width MST_ENTRY strings.
  3067. auto Abbv = std::make_shared<BitCodeAbbrev>();
  3068. Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
  3069. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  3070. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  3071. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
  3072. unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
  3073. // 7-bit fixed width MST_ENTRY strings.
  3074. Abbv = std::make_shared<BitCodeAbbrev>();
  3075. Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
  3076. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  3077. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  3078. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
  3079. unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
  3080. // 6-bit char6 MST_ENTRY strings.
  3081. Abbv = std::make_shared<BitCodeAbbrev>();
  3082. Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
  3083. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  3084. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  3085. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  3086. unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
  3087. // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
  3088. Abbv = std::make_shared<BitCodeAbbrev>();
  3089. Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
  3090. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  3091. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  3092. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  3093. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  3094. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  3095. unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
  3096. SmallVector<unsigned, 64> Vals;
  3097. forEachModule(
  3098. [&](const StringMapEntry<std::pair<uint64_t, ModuleHash>> &MPSE) {
  3099. StringRef Key = MPSE.getKey();
  3100. const auto &Value = MPSE.getValue();
  3101. StringEncoding Bits = getStringEncoding(Key);
  3102. unsigned AbbrevToUse = Abbrev8Bit;
  3103. if (Bits == SE_Char6)
  3104. AbbrevToUse = Abbrev6Bit;
  3105. else if (Bits == SE_Fixed7)
  3106. AbbrevToUse = Abbrev7Bit;
  3107. Vals.push_back(Value.first);
  3108. Vals.append(Key.begin(), Key.end());
  3109. // Emit the finished record.
  3110. Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
  3111. // Emit an optional hash for the module now
  3112. const auto &Hash = Value.second;
  3113. if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
  3114. Vals.assign(Hash.begin(), Hash.end());
  3115. // Emit the hash record.
  3116. Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
  3117. }
  3118. Vals.clear();
  3119. });
  3120. Stream.ExitBlock();
  3121. }
  3122. /// Write the function type metadata related records that need to appear before
  3123. /// a function summary entry (whether per-module or combined).
  3124. static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream,
  3125. FunctionSummary *FS) {
  3126. if (!FS->type_tests().empty())
  3127. Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
  3128. SmallVector<uint64_t, 64> Record;
  3129. auto WriteVFuncIdVec = [&](uint64_t Ty,
  3130. ArrayRef<FunctionSummary::VFuncId> VFs) {
  3131. if (VFs.empty())
  3132. return;
  3133. Record.clear();
  3134. for (auto &VF : VFs) {
  3135. Record.push_back(VF.GUID);
  3136. Record.push_back(VF.Offset);
  3137. }
  3138. Stream.EmitRecord(Ty, Record);
  3139. };
  3140. WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
  3141. FS->type_test_assume_vcalls());
  3142. WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
  3143. FS->type_checked_load_vcalls());
  3144. auto WriteConstVCallVec = [&](uint64_t Ty,
  3145. ArrayRef<FunctionSummary::ConstVCall> VCs) {
  3146. for (auto &VC : VCs) {
  3147. Record.clear();
  3148. Record.push_back(VC.VFunc.GUID);
  3149. Record.push_back(VC.VFunc.Offset);
  3150. Record.insert(Record.end(), VC.Args.begin(), VC.Args.end());
  3151. Stream.EmitRecord(Ty, Record);
  3152. }
  3153. };
  3154. WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
  3155. FS->type_test_assume_const_vcalls());
  3156. WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
  3157. FS->type_checked_load_const_vcalls());
  3158. }
  3159. /// Collect type IDs from type tests used by function.
  3160. static void
  3161. getReferencedTypeIds(FunctionSummary *FS,
  3162. std::set<GlobalValue::GUID> &ReferencedTypeIds) {
  3163. if (!FS->type_tests().empty())
  3164. for (auto &TT : FS->type_tests())
  3165. ReferencedTypeIds.insert(TT);
  3166. auto GetReferencedTypesFromVFuncIdVec =
  3167. [&](ArrayRef<FunctionSummary::VFuncId> VFs) {
  3168. for (auto &VF : VFs)
  3169. ReferencedTypeIds.insert(VF.GUID);
  3170. };
  3171. GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
  3172. GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
  3173. auto GetReferencedTypesFromConstVCallVec =
  3174. [&](ArrayRef<FunctionSummary::ConstVCall> VCs) {
  3175. for (auto &VC : VCs)
  3176. ReferencedTypeIds.insert(VC.VFunc.GUID);
  3177. };
  3178. GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
  3179. GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
  3180. }
  3181. static void writeWholeProgramDevirtResolutionByArg(
  3182. SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
  3183. const WholeProgramDevirtResolution::ByArg &ByArg) {
  3184. NameVals.push_back(args.size());
  3185. NameVals.insert(NameVals.end(), args.begin(), args.end());
  3186. NameVals.push_back(ByArg.TheKind);
  3187. NameVals.push_back(ByArg.Info);
  3188. NameVals.push_back(ByArg.Byte);
  3189. NameVals.push_back(ByArg.Bit);
  3190. }
  3191. static void writeWholeProgramDevirtResolution(
  3192. SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
  3193. uint64_t Id, const WholeProgramDevirtResolution &Wpd) {
  3194. NameVals.push_back(Id);
  3195. NameVals.push_back(Wpd.TheKind);
  3196. NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
  3197. NameVals.push_back(Wpd.SingleImplName.size());
  3198. NameVals.push_back(Wpd.ResByArg.size());
  3199. for (auto &A : Wpd.ResByArg)
  3200. writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
  3201. }
  3202. static void writeTypeIdSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
  3203. StringTableBuilder &StrtabBuilder,
  3204. const std::string &Id,
  3205. const TypeIdSummary &Summary) {
  3206. NameVals.push_back(StrtabBuilder.add(Id));
  3207. NameVals.push_back(Id.size());
  3208. NameVals.push_back(Summary.TTRes.TheKind);
  3209. NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
  3210. NameVals.push_back(Summary.TTRes.AlignLog2);
  3211. NameVals.push_back(Summary.TTRes.SizeM1);
  3212. NameVals.push_back(Summary.TTRes.BitMask);
  3213. NameVals.push_back(Summary.TTRes.InlineBits);
  3214. for (auto &W : Summary.WPDRes)
  3215. writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
  3216. W.second);
  3217. }
  3218. static void writeTypeIdCompatibleVtableSummaryRecord(
  3219. SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
  3220. const std::string &Id, const TypeIdCompatibleVtableInfo &Summary,
  3221. ValueEnumerator &VE) {
  3222. NameVals.push_back(StrtabBuilder.add(Id));
  3223. NameVals.push_back(Id.size());
  3224. for (auto &P : Summary) {
  3225. NameVals.push_back(P.AddressPointOffset);
  3226. NameVals.push_back(VE.getValueID(P.VTableVI.getValue()));
  3227. }
  3228. }
  3229. // Helper to emit a single function summary record.
  3230. void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
  3231. SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
  3232. unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
  3233. const Function &F) {
  3234. NameVals.push_back(ValueID);
  3235. FunctionSummary *FS = cast<FunctionSummary>(Summary);
  3236. writeFunctionTypeMetadataRecords(Stream, FS);
  3237. NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
  3238. NameVals.push_back(FS->instCount());
  3239. NameVals.push_back(getEncodedFFlags(FS->fflags()));
  3240. NameVals.push_back(FS->refs().size());
  3241. NameVals.push_back(FS->immutableRefCount());
  3242. for (auto &RI : FS->refs())
  3243. NameVals.push_back(VE.getValueID(RI.getValue()));
  3244. bool HasProfileData =
  3245. F.hasProfileData() || ForceSummaryEdgesCold != FunctionSummary::FSHT_None;
  3246. for (auto &ECI : FS->calls()) {
  3247. NameVals.push_back(getValueId(ECI.first));
  3248. if (HasProfileData)
  3249. NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
  3250. else if (WriteRelBFToSummary)
  3251. NameVals.push_back(ECI.second.RelBlockFreq);
  3252. }
  3253. unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
  3254. unsigned Code =
  3255. (HasProfileData ? bitc::FS_PERMODULE_PROFILE
  3256. : (WriteRelBFToSummary ? bitc::FS_PERMODULE_RELBF
  3257. : bitc::FS_PERMODULE));
  3258. // Emit the finished record.
  3259. Stream.EmitRecord(Code, NameVals, FSAbbrev);
  3260. NameVals.clear();
  3261. }
  3262. // Collect the global value references in the given variable's initializer,
  3263. // and emit them in a summary record.
  3264. void ModuleBitcodeWriterBase::writeModuleLevelReferences(
  3265. const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
  3266. unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) {
  3267. auto VI = Index->getValueInfo(V.getGUID());
  3268. if (!VI || VI.getSummaryList().empty()) {
  3269. // Only declarations should not have a summary (a declaration might however
  3270. // have a summary if the def was in module level asm).
  3271. assert(V.isDeclaration());
  3272. return;
  3273. }
  3274. auto *Summary = VI.getSummaryList()[0].get();
  3275. NameVals.push_back(VE.getValueID(&V));
  3276. GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
  3277. NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
  3278. NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
  3279. auto VTableFuncs = VS->vTableFuncs();
  3280. if (!VTableFuncs.empty())
  3281. NameVals.push_back(VS->refs().size());
  3282. unsigned SizeBeforeRefs = NameVals.size();
  3283. for (auto &RI : VS->refs())
  3284. NameVals.push_back(VE.getValueID(RI.getValue()));
  3285. // Sort the refs for determinism output, the vector returned by FS->refs() has
  3286. // been initialized from a DenseSet.
  3287. llvm::sort(NameVals.begin() + SizeBeforeRefs, NameVals.end());
  3288. if (VTableFuncs.empty())
  3289. Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
  3290. FSModRefsAbbrev);
  3291. else {
  3292. // VTableFuncs pairs should already be sorted by offset.
  3293. for (auto &P : VTableFuncs) {
  3294. NameVals.push_back(VE.getValueID(P.FuncVI.getValue()));
  3295. NameVals.push_back(P.VTableOffset);
  3296. }
  3297. Stream.EmitRecord(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS, NameVals,
  3298. FSModVTableRefsAbbrev);
  3299. }
  3300. NameVals.clear();
  3301. }
  3302. // Current version for the summary.
  3303. // This is bumped whenever we introduce changes in the way some record are
  3304. // interpreted, like flags for instance.
  3305. static const uint64_t INDEX_VERSION = 6;
  3306. /// Emit the per-module summary section alongside the rest of
  3307. /// the module's bitcode.
  3308. void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
  3309. // By default we compile with ThinLTO if the module has a summary, but the
  3310. // client can request full LTO with a module flag.
  3311. bool IsThinLTO = true;
  3312. if (auto *MD =
  3313. mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
  3314. IsThinLTO = MD->getZExtValue();
  3315. Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID
  3316. : bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID,
  3317. 4);
  3318. Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
  3319. // Write the index flags.
  3320. uint64_t Flags = 0;
  3321. // Bits 1-3 are set only in the combined index, skip them.
  3322. if (Index->enableSplitLTOUnit())
  3323. Flags |= 0x8;
  3324. Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags});
  3325. if (Index->begin() == Index->end()) {
  3326. Stream.ExitBlock();
  3327. return;
  3328. }
  3329. for (const auto &GVI : valueIds()) {
  3330. Stream.EmitRecord(bitc::FS_VALUE_GUID,
  3331. ArrayRef<uint64_t>{GVI.second, GVI.first});
  3332. }
  3333. // Abbrev for FS_PERMODULE_PROFILE.
  3334. auto Abbv = std::make_shared<BitCodeAbbrev>();
  3335. Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
  3336. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
  3337. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
  3338. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
  3339. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
  3340. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
  3341. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // immutablerefcnt
  3342. // numrefs x valueid, n x (valueid, hotness)
  3343. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  3344. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  3345. unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  3346. // Abbrev for FS_PERMODULE or FS_PERMODULE_RELBF.
  3347. Abbv = std::make_shared<BitCodeAbbrev>();
  3348. if (WriteRelBFToSummary)
  3349. Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_RELBF));
  3350. else
  3351. Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
  3352. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
  3353. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
  3354. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
  3355. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
  3356. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
  3357. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // immutablerefcnt
  3358. // numrefs x valueid, n x (valueid [, rel_block_freq])
  3359. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  3360. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  3361. unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  3362. // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
  3363. Abbv = std::make_shared<BitCodeAbbrev>();
  3364. Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
  3365. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
  3366. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
  3367. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
  3368. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  3369. unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  3370. // Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS.
  3371. Abbv = std::make_shared<BitCodeAbbrev>();
  3372. Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS));
  3373. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
  3374. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
  3375. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
  3376. // numrefs x valueid, n x (valueid , offset)
  3377. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  3378. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  3379. unsigned FSModVTableRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  3380. // Abbrev for FS_ALIAS.
  3381. Abbv = std::make_shared<BitCodeAbbrev>();
  3382. Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
  3383. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
  3384. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
  3385. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
  3386. unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  3387. // Abbrev for FS_TYPE_ID_METADATA
  3388. Abbv = std::make_shared<BitCodeAbbrev>();
  3389. Abbv->Add(BitCodeAbbrevOp(bitc::FS_TYPE_ID_METADATA));
  3390. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid strtab index
  3391. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid length
  3392. // n x (valueid , offset)
  3393. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  3394. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  3395. unsigned TypeIdCompatibleVtableAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  3396. SmallVector<uint64_t, 64> NameVals;
  3397. // Iterate over the list of functions instead of the Index to
  3398. // ensure the ordering is stable.
  3399. for (const Function &F : M) {
  3400. // Summary emission does not support anonymous functions, they have to
  3401. // renamed using the anonymous function renaming pass.
  3402. if (!F.hasName())
  3403. report_fatal_error("Unexpected anonymous function when writing summary");
  3404. ValueInfo VI = Index->getValueInfo(F.getGUID());
  3405. if (!VI || VI.getSummaryList().empty()) {
  3406. // Only declarations should not have a summary (a declaration might
  3407. // however have a summary if the def was in module level asm).
  3408. assert(F.isDeclaration());
  3409. continue;
  3410. }
  3411. auto *Summary = VI.getSummaryList()[0].get();
  3412. writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
  3413. FSCallsAbbrev, FSCallsProfileAbbrev, F);
  3414. }
  3415. // Capture references from GlobalVariable initializers, which are outside
  3416. // of a function scope.
  3417. for (const GlobalVariable &G : M.globals())
  3418. writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev,
  3419. FSModVTableRefsAbbrev);
  3420. for (const GlobalAlias &A : M.aliases()) {
  3421. auto *Aliasee = A.getBaseObject();
  3422. if (!Aliasee->hasName())
  3423. // Nameless function don't have an entry in the summary, skip it.
  3424. continue;
  3425. auto AliasId = VE.getValueID(&A);
  3426. auto AliaseeId = VE.getValueID(Aliasee);
  3427. NameVals.push_back(AliasId);
  3428. auto *Summary = Index->getGlobalValueSummary(A);
  3429. AliasSummary *AS = cast<AliasSummary>(Summary);
  3430. NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
  3431. NameVals.push_back(AliaseeId);
  3432. Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
  3433. NameVals.clear();
  3434. }
  3435. for (auto &S : Index->typeIdCompatibleVtableMap()) {
  3436. writeTypeIdCompatibleVtableSummaryRecord(NameVals, StrtabBuilder, S.first,
  3437. S.second, VE);
  3438. Stream.EmitRecord(bitc::FS_TYPE_ID_METADATA, NameVals,
  3439. TypeIdCompatibleVtableAbbrev);
  3440. NameVals.clear();
  3441. }
  3442. Stream.ExitBlock();
  3443. }
  3444. /// Emit the combined summary section into the combined index file.
  3445. void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
  3446. Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
  3447. Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
  3448. // Write the index flags.
  3449. uint64_t Flags = 0;
  3450. if (Index.withGlobalValueDeadStripping())
  3451. Flags |= 0x1;
  3452. if (Index.skipModuleByDistributedBackend())
  3453. Flags |= 0x2;
  3454. if (Index.hasSyntheticEntryCounts())
  3455. Flags |= 0x4;
  3456. if (Index.enableSplitLTOUnit())
  3457. Flags |= 0x8;
  3458. if (Index.partiallySplitLTOUnits())
  3459. Flags |= 0x10;
  3460. Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags});
  3461. for (const auto &GVI : valueIds()) {
  3462. Stream.EmitRecord(bitc::FS_VALUE_GUID,
  3463. ArrayRef<uint64_t>{GVI.second, GVI.first});
  3464. }
  3465. // Abbrev for FS_COMBINED.
  3466. auto Abbv = std::make_shared<BitCodeAbbrev>();
  3467. Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
  3468. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
  3469. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
  3470. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
  3471. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
  3472. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
  3473. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // entrycount
  3474. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
  3475. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // immutablerefcnt
  3476. // numrefs x valueid, n x (valueid)
  3477. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  3478. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  3479. unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  3480. // Abbrev for FS_COMBINED_PROFILE.
  3481. Abbv = std::make_shared<BitCodeAbbrev>();
  3482. Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
  3483. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
  3484. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
  3485. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
  3486. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
  3487. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
  3488. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // entrycount
  3489. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
  3490. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // immutablerefcnt
  3491. // numrefs x valueid, n x (valueid, hotness)
  3492. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  3493. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  3494. unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  3495. // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
  3496. Abbv = std::make_shared<BitCodeAbbrev>();
  3497. Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
  3498. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
  3499. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
  3500. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
  3501. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
  3502. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  3503. unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  3504. // Abbrev for FS_COMBINED_ALIAS.
  3505. Abbv = std::make_shared<BitCodeAbbrev>();
  3506. Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
  3507. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
  3508. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
  3509. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
  3510. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
  3511. unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  3512. // The aliases are emitted as a post-pass, and will point to the value
  3513. // id of the aliasee. Save them in a vector for post-processing.
  3514. SmallVector<AliasSummary *, 64> Aliases;
  3515. // Save the value id for each summary for alias emission.
  3516. DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
  3517. SmallVector<uint64_t, 64> NameVals;
  3518. // Set that will be populated during call to writeFunctionTypeMetadataRecords
  3519. // with the type ids referenced by this index file.
  3520. std::set<GlobalValue::GUID> ReferencedTypeIds;
  3521. // For local linkage, we also emit the original name separately
  3522. // immediately after the record.
  3523. auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
  3524. if (!GlobalValue::isLocalLinkage(S.linkage()))
  3525. return;
  3526. NameVals.push_back(S.getOriginalName());
  3527. Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
  3528. NameVals.clear();
  3529. };
  3530. forEachSummary([&](GVInfo I, bool IsAliasee) {
  3531. GlobalValueSummary *S = I.second;
  3532. assert(S);
  3533. auto ValueId = getValueId(I.first);
  3534. assert(ValueId);
  3535. SummaryToValueIdMap[S] = *ValueId;
  3536. // If this is invoked for an aliasee, we want to record the above
  3537. // mapping, but then not emit a summary entry (if the aliasee is
  3538. // to be imported, we will invoke this separately with IsAliasee=false).
  3539. if (IsAliasee)
  3540. return;
  3541. if (auto *AS = dyn_cast<AliasSummary>(S)) {
  3542. // Will process aliases as a post-pass because the reader wants all
  3543. // global to be loaded first.
  3544. Aliases.push_back(AS);
  3545. return;
  3546. }
  3547. if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
  3548. NameVals.push_back(*ValueId);
  3549. NameVals.push_back(Index.getModuleId(VS->modulePath()));
  3550. NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
  3551. NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
  3552. for (auto &RI : VS->refs()) {
  3553. auto RefValueId = getValueId(RI.getGUID());
  3554. if (!RefValueId)
  3555. continue;
  3556. NameVals.push_back(*RefValueId);
  3557. }
  3558. // Emit the finished record.
  3559. Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
  3560. FSModRefsAbbrev);
  3561. NameVals.clear();
  3562. MaybeEmitOriginalName(*S);
  3563. return;
  3564. }
  3565. auto *FS = cast<FunctionSummary>(S);
  3566. writeFunctionTypeMetadataRecords(Stream, FS);
  3567. getReferencedTypeIds(FS, ReferencedTypeIds);
  3568. NameVals.push_back(*ValueId);
  3569. NameVals.push_back(Index.getModuleId(FS->modulePath()));
  3570. NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
  3571. NameVals.push_back(FS->instCount());
  3572. NameVals.push_back(getEncodedFFlags(FS->fflags()));
  3573. NameVals.push_back(FS->entryCount());
  3574. // Fill in below
  3575. NameVals.push_back(0); // numrefs
  3576. NameVals.push_back(0); // immutablerefcnt
  3577. unsigned Count = 0, ImmutableRefCnt = 0;
  3578. for (auto &RI : FS->refs()) {
  3579. auto RefValueId = getValueId(RI.getGUID());
  3580. if (!RefValueId)
  3581. continue;
  3582. NameVals.push_back(*RefValueId);
  3583. if (RI.isReadOnly())
  3584. ImmutableRefCnt++;
  3585. Count++;
  3586. }
  3587. NameVals[6] = Count;
  3588. NameVals[7] = ImmutableRefCnt;
  3589. bool HasProfileData = false;
  3590. for (auto &EI : FS->calls()) {
  3591. HasProfileData |=
  3592. EI.second.getHotness() != CalleeInfo::HotnessType::Unknown;
  3593. if (HasProfileData)
  3594. break;
  3595. }
  3596. for (auto &EI : FS->calls()) {
  3597. // If this GUID doesn't have a value id, it doesn't have a function
  3598. // summary and we don't need to record any calls to it.
  3599. GlobalValue::GUID GUID = EI.first.getGUID();
  3600. auto CallValueId = getValueId(GUID);
  3601. if (!CallValueId) {
  3602. // For SamplePGO, the indirect call targets for local functions will
  3603. // have its original name annotated in profile. We try to find the
  3604. // corresponding PGOFuncName as the GUID.
  3605. GUID = Index.getGUIDFromOriginalID(GUID);
  3606. if (GUID == 0)
  3607. continue;
  3608. CallValueId = getValueId(GUID);
  3609. if (!CallValueId)
  3610. continue;
  3611. // The mapping from OriginalId to GUID may return a GUID
  3612. // that corresponds to a static variable. Filter it out here.
  3613. // This can happen when
  3614. // 1) There is a call to a library function which does not have
  3615. // a CallValidId;
  3616. // 2) There is a static variable with the OriginalGUID identical
  3617. // to the GUID of the library function in 1);
  3618. // When this happens, the logic for SamplePGO kicks in and
  3619. // the static variable in 2) will be found, which needs to be
  3620. // filtered out.
  3621. auto *GVSum = Index.getGlobalValueSummary(GUID, false);
  3622. if (GVSum &&
  3623. GVSum->getSummaryKind() == GlobalValueSummary::GlobalVarKind)
  3624. continue;
  3625. }
  3626. NameVals.push_back(*CallValueId);
  3627. if (HasProfileData)
  3628. NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness));
  3629. }
  3630. unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
  3631. unsigned Code =
  3632. (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
  3633. // Emit the finished record.
  3634. Stream.EmitRecord(Code, NameVals, FSAbbrev);
  3635. NameVals.clear();
  3636. MaybeEmitOriginalName(*S);
  3637. });
  3638. for (auto *AS : Aliases) {
  3639. auto AliasValueId = SummaryToValueIdMap[AS];
  3640. assert(AliasValueId);
  3641. NameVals.push_back(AliasValueId);
  3642. NameVals.push_back(Index.getModuleId(AS->modulePath()));
  3643. NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
  3644. auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
  3645. assert(AliaseeValueId);
  3646. NameVals.push_back(AliaseeValueId);
  3647. // Emit the finished record.
  3648. Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
  3649. NameVals.clear();
  3650. MaybeEmitOriginalName(*AS);
  3651. if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee()))
  3652. getReferencedTypeIds(FS, ReferencedTypeIds);
  3653. }
  3654. if (!Index.cfiFunctionDefs().empty()) {
  3655. for (auto &S : Index.cfiFunctionDefs()) {
  3656. NameVals.push_back(StrtabBuilder.add(S));
  3657. NameVals.push_back(S.size());
  3658. }
  3659. Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals);
  3660. NameVals.clear();
  3661. }
  3662. if (!Index.cfiFunctionDecls().empty()) {
  3663. for (auto &S : Index.cfiFunctionDecls()) {
  3664. NameVals.push_back(StrtabBuilder.add(S));
  3665. NameVals.push_back(S.size());
  3666. }
  3667. Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals);
  3668. NameVals.clear();
  3669. }
  3670. // Walk the GUIDs that were referenced, and write the
  3671. // corresponding type id records.
  3672. for (auto &T : ReferencedTypeIds) {
  3673. auto TidIter = Index.typeIds().equal_range(T);
  3674. for (auto It = TidIter.first; It != TidIter.second; ++It) {
  3675. writeTypeIdSummaryRecord(NameVals, StrtabBuilder, It->second.first,
  3676. It->second.second);
  3677. Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);
  3678. NameVals.clear();
  3679. }
  3680. }
  3681. Stream.ExitBlock();
  3682. }
  3683. /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
  3684. /// current llvm version, and a record for the epoch number.
  3685. static void writeIdentificationBlock(BitstreamWriter &Stream) {
  3686. Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
  3687. // Write the "user readable" string identifying the bitcode producer
  3688. auto Abbv = std::make_shared<BitCodeAbbrev>();
  3689. Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
  3690. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  3691. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  3692. auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  3693. writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,
  3694. "LLVM" LLVM_VERSION_STRING, StringAbbrev);
  3695. // Write the epoch version
  3696. Abbv = std::make_shared<BitCodeAbbrev>();
  3697. Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
  3698. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  3699. auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  3700. SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
  3701. Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
  3702. Stream.ExitBlock();
  3703. }
  3704. void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
  3705. // Emit the module's hash.
  3706. // MODULE_CODE_HASH: [5*i32]
  3707. if (GenerateHash) {
  3708. uint32_t Vals[5];
  3709. Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
  3710. Buffer.size() - BlockStartPos));
  3711. StringRef Hash = Hasher.result();
  3712. for (int Pos = 0; Pos < 20; Pos += 4) {
  3713. Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
  3714. }
  3715. // Emit the finished record.
  3716. Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
  3717. if (ModHash)
  3718. // Save the written hash value.
  3719. llvm::copy(Vals, std::begin(*ModHash));
  3720. }
  3721. }
  3722. void ModuleBitcodeWriter::write() {
  3723. writeIdentificationBlock(Stream);
  3724. Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
  3725. size_t BlockStartPos = Buffer.size();
  3726. writeModuleVersion();
  3727. // Emit blockinfo, which defines the standard abbreviations etc.
  3728. writeBlockInfo();
  3729. // Emit information describing all of the types in the module.
  3730. writeTypeTable();
  3731. // Emit information about attribute groups.
  3732. writeAttributeGroupTable();
  3733. // Emit information about parameter attributes.
  3734. writeAttributeTable();
  3735. writeComdats();
  3736. // Emit top-level description of module, including target triple, inline asm,
  3737. // descriptors for global variables, and function prototype info.
  3738. writeModuleInfo();
  3739. // Emit constants.
  3740. writeModuleConstants();
  3741. // Emit metadata kind names.
  3742. writeModuleMetadataKinds();
  3743. // Emit metadata.
  3744. writeModuleMetadata();
  3745. // Emit module-level use-lists.
  3746. if (VE.shouldPreserveUseListOrder())
  3747. writeUseListBlock(nullptr);
  3748. writeOperandBundleTags();
  3749. writeSyncScopeNames();
  3750. // Emit function bodies.
  3751. DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
  3752. for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F)
  3753. if (!F->isDeclaration())
  3754. writeFunction(*F, FunctionToBitcodeIndex);
  3755. // Need to write after the above call to WriteFunction which populates
  3756. // the summary information in the index.
  3757. if (Index)
  3758. writePerModuleGlobalValueSummary();
  3759. writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
  3760. writeModuleHash(BlockStartPos);
  3761. Stream.ExitBlock();
  3762. }
  3763. static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
  3764. uint32_t &Position) {
  3765. support::endian::write32le(&Buffer[Position], Value);
  3766. Position += 4;
  3767. }
  3768. /// If generating a bc file on darwin, we have to emit a
  3769. /// header and trailer to make it compatible with the system archiver. To do
  3770. /// this we emit the following header, and then emit a trailer that pads the
  3771. /// file out to be a multiple of 16 bytes.
  3772. ///
  3773. /// struct bc_header {
  3774. /// uint32_t Magic; // 0x0B17C0DE
  3775. /// uint32_t Version; // Version, currently always 0.
  3776. /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
  3777. /// uint32_t BitcodeSize; // Size of traditional bitcode file.
  3778. /// uint32_t CPUType; // CPU specifier.
  3779. /// ... potentially more later ...
  3780. /// };
  3781. static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
  3782. const Triple &TT) {
  3783. unsigned CPUType = ~0U;
  3784. // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
  3785. // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
  3786. // number from /usr/include/mach/machine.h. It is ok to reproduce the
  3787. // specific constants here because they are implicitly part of the Darwin ABI.
  3788. enum {
  3789. DARWIN_CPU_ARCH_ABI64 = 0x01000000,
  3790. DARWIN_CPU_TYPE_X86 = 7,
  3791. DARWIN_CPU_TYPE_ARM = 12,
  3792. DARWIN_CPU_TYPE_POWERPC = 18
  3793. };
  3794. Triple::ArchType Arch = TT.getArch();
  3795. if (Arch == Triple::x86_64)
  3796. CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
  3797. else if (Arch == Triple::x86)
  3798. CPUType = DARWIN_CPU_TYPE_X86;
  3799. else if (Arch == Triple::ppc)
  3800. CPUType = DARWIN_CPU_TYPE_POWERPC;
  3801. else if (Arch == Triple::ppc64)
  3802. CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
  3803. else if (Arch == Triple::arm || Arch == Triple::thumb)
  3804. CPUType = DARWIN_CPU_TYPE_ARM;
  3805. // Traditional Bitcode starts after header.
  3806. assert(Buffer.size() >= BWH_HeaderSize &&
  3807. "Expected header size to be reserved");
  3808. unsigned BCOffset = BWH_HeaderSize;
  3809. unsigned BCSize = Buffer.size() - BWH_HeaderSize;
  3810. // Write the magic and version.
  3811. unsigned Position = 0;
  3812. writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
  3813. writeInt32ToBuffer(0, Buffer, Position); // Version.
  3814. writeInt32ToBuffer(BCOffset, Buffer, Position);
  3815. writeInt32ToBuffer(BCSize, Buffer, Position);
  3816. writeInt32ToBuffer(CPUType, Buffer, Position);
  3817. // If the file is not a multiple of 16 bytes, insert dummy padding.
  3818. while (Buffer.size() & 15)
  3819. Buffer.push_back(0);
  3820. }
  3821. /// Helper to write the header common to all bitcode files.
  3822. static void writeBitcodeHeader(BitstreamWriter &Stream) {
  3823. // Emit the file header.
  3824. Stream.Emit((unsigned)'B', 8);
  3825. Stream.Emit((unsigned)'C', 8);
  3826. Stream.Emit(0x0, 4);
  3827. Stream.Emit(0xC, 4);
  3828. Stream.Emit(0xE, 4);
  3829. Stream.Emit(0xD, 4);
  3830. }
  3831. BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer)
  3832. : Buffer(Buffer), Stream(new BitstreamWriter(Buffer)) {
  3833. writeBitcodeHeader(*Stream);
  3834. }
  3835. BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); }
  3836. void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
  3837. Stream->EnterSubblock(Block, 3);
  3838. auto Abbv = std::make_shared<BitCodeAbbrev>();
  3839. Abbv->Add(BitCodeAbbrevOp(Record));
  3840. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  3841. auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
  3842. Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
  3843. Stream->ExitBlock();
  3844. }
  3845. void BitcodeWriter::writeSymtab() {
  3846. assert(!WroteStrtab && !WroteSymtab);
  3847. // If any module has module-level inline asm, we will require a registered asm
  3848. // parser for the target so that we can create an accurate symbol table for
  3849. // the module.
  3850. for (Module *M : Mods) {
  3851. if (M->getModuleInlineAsm().empty())
  3852. continue;
  3853. std::string Err;
  3854. const Triple TT(M->getTargetTriple());
  3855. const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);
  3856. if (!T || !T->hasMCAsmParser())
  3857. return;
  3858. }
  3859. WroteSymtab = true;
  3860. SmallVector<char, 0> Symtab;
  3861. // The irsymtab::build function may be unable to create a symbol table if the
  3862. // module is malformed (e.g. it contains an invalid alias). Writing a symbol
  3863. // table is not required for correctness, but we still want to be able to
  3864. // write malformed modules to bitcode files, so swallow the error.
  3865. if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
  3866. consumeError(std::move(E));
  3867. return;
  3868. }
  3869. writeBlob(bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB,
  3870. {Symtab.data(), Symtab.size()});
  3871. }
  3872. void BitcodeWriter::writeStrtab() {
  3873. assert(!WroteStrtab);
  3874. std::vector<char> Strtab;
  3875. StrtabBuilder.finalizeInOrder();
  3876. Strtab.resize(StrtabBuilder.getSize());
  3877. StrtabBuilder.write((uint8_t *)Strtab.data());
  3878. writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB,
  3879. {Strtab.data(), Strtab.size()});
  3880. WroteStrtab = true;
  3881. }
  3882. void BitcodeWriter::copyStrtab(StringRef Strtab) {
  3883. writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
  3884. WroteStrtab = true;
  3885. }
  3886. void BitcodeWriter::writeModule(const Module &M,
  3887. bool ShouldPreserveUseListOrder,
  3888. const ModuleSummaryIndex *Index,
  3889. bool GenerateHash, ModuleHash *ModHash) {
  3890. assert(!WroteStrtab);
  3891. // The Mods vector is used by irsymtab::build, which requires non-const
  3892. // Modules in case it needs to materialize metadata. But the bitcode writer
  3893. // requires that the module is materialized, so we can cast to non-const here,
  3894. // after checking that it is in fact materialized.
  3895. assert(M.isMaterialized());
  3896. Mods.push_back(const_cast<Module *>(&M));
  3897. ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream,
  3898. ShouldPreserveUseListOrder, Index,
  3899. GenerateHash, ModHash);
  3900. ModuleWriter.write();
  3901. }
  3902. void BitcodeWriter::writeIndex(
  3903. const ModuleSummaryIndex *Index,
  3904. const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
  3905. IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index,
  3906. ModuleToSummariesForIndex);
  3907. IndexWriter.write();
  3908. }
  3909. /// Write the specified module to the specified output stream.
  3910. void llvm::WriteBitcodeToFile(const Module &M, raw_ostream &Out,
  3911. bool ShouldPreserveUseListOrder,
  3912. const ModuleSummaryIndex *Index,
  3913. bool GenerateHash, ModuleHash *ModHash) {
  3914. SmallVector<char, 0> Buffer;
  3915. Buffer.reserve(256*1024);
  3916. // If this is darwin or another generic macho target, reserve space for the
  3917. // header.
  3918. Triple TT(M.getTargetTriple());
  3919. if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
  3920. Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
  3921. BitcodeWriter Writer(Buffer);
  3922. Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
  3923. ModHash);
  3924. Writer.writeSymtab();
  3925. Writer.writeStrtab();
  3926. if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
  3927. emitDarwinBCHeaderAndTrailer(Buffer, TT);
  3928. // Write the generated bitstream to "Out".
  3929. Out.write((char*)&Buffer.front(), Buffer.size());
  3930. }
  3931. void IndexBitcodeWriter::write() {
  3932. Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
  3933. writeModuleVersion();
  3934. // Write the module paths in the combined index.
  3935. writeModStrings();
  3936. // Write the summary combined index records.
  3937. writeCombinedGlobalValueSummary();
  3938. Stream.ExitBlock();
  3939. }
  3940. // Write the specified module summary index to the given raw output stream,
  3941. // where it will be written in a new bitcode block. This is used when
  3942. // writing the combined index file for ThinLTO. When writing a subset of the
  3943. // index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
  3944. void llvm::WriteIndexToFile(
  3945. const ModuleSummaryIndex &Index, raw_ostream &Out,
  3946. const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
  3947. SmallVector<char, 0> Buffer;
  3948. Buffer.reserve(256 * 1024);
  3949. BitcodeWriter Writer(Buffer);
  3950. Writer.writeIndex(&Index, ModuleToSummariesForIndex);
  3951. Writer.writeStrtab();
  3952. Out.write((char *)&Buffer.front(), Buffer.size());
  3953. }
  3954. namespace {
  3955. /// Class to manage the bitcode writing for a thin link bitcode file.
  3956. class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase {
  3957. /// ModHash is for use in ThinLTO incremental build, generated while writing
  3958. /// the module bitcode file.
  3959. const ModuleHash *ModHash;
  3960. public:
  3961. ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
  3962. BitstreamWriter &Stream,
  3963. const ModuleSummaryIndex &Index,
  3964. const ModuleHash &ModHash)
  3965. : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
  3966. /*ShouldPreserveUseListOrder=*/false, &Index),
  3967. ModHash(&ModHash) {}
  3968. void write();
  3969. private:
  3970. void writeSimplifiedModuleInfo();
  3971. };
  3972. } // end anonymous namespace
  3973. // This function writes a simpilified module info for thin link bitcode file.
  3974. // It only contains the source file name along with the name(the offset and
  3975. // size in strtab) and linkage for global values. For the global value info
  3976. // entry, in order to keep linkage at offset 5, there are three zeros used
  3977. // as padding.
  3978. void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
  3979. SmallVector<unsigned, 64> Vals;
  3980. // Emit the module's source file name.
  3981. {
  3982. StringEncoding Bits = getStringEncoding(M.getSourceFileName());
  3983. BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
  3984. if (Bits == SE_Char6)
  3985. AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
  3986. else if (Bits == SE_Fixed7)
  3987. AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
  3988. // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
  3989. auto Abbv = std::make_shared<BitCodeAbbrev>();
  3990. Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
  3991. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  3992. Abbv->Add(AbbrevOpToUse);
  3993. unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  3994. for (const auto P : M.getSourceFileName())
  3995. Vals.push_back((unsigned char)P);
  3996. Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
  3997. Vals.clear();
  3998. }
  3999. // Emit the global variable information.
  4000. for (const GlobalVariable &GV : M.globals()) {
  4001. // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
  4002. Vals.push_back(StrtabBuilder.add(GV.getName()));
  4003. Vals.push_back(GV.getName().size());
  4004. Vals.push_back(0);
  4005. Vals.push_back(0);
  4006. Vals.push_back(0);
  4007. Vals.push_back(getEncodedLinkage(GV));
  4008. Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals);
  4009. Vals.clear();
  4010. }
  4011. // Emit the function proto information.
  4012. for (const Function &F : M) {
  4013. // FUNCTION: [strtab offset, strtab size, 0, 0, 0, linkage]
  4014. Vals.push_back(StrtabBuilder.add(F.getName()));
  4015. Vals.push_back(F.getName().size());
  4016. Vals.push_back(0);
  4017. Vals.push_back(0);
  4018. Vals.push_back(0);
  4019. Vals.push_back(getEncodedLinkage(F));
  4020. Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals);
  4021. Vals.clear();
  4022. }
  4023. // Emit the alias information.
  4024. for (const GlobalAlias &A : M.aliases()) {
  4025. // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]
  4026. Vals.push_back(StrtabBuilder.add(A.getName()));
  4027. Vals.push_back(A.getName().size());
  4028. Vals.push_back(0);
  4029. Vals.push_back(0);
  4030. Vals.push_back(0);
  4031. Vals.push_back(getEncodedLinkage(A));
  4032. Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals);
  4033. Vals.clear();
  4034. }
  4035. // Emit the ifunc information.
  4036. for (const GlobalIFunc &I : M.ifuncs()) {
  4037. // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]
  4038. Vals.push_back(StrtabBuilder.add(I.getName()));
  4039. Vals.push_back(I.getName().size());
  4040. Vals.push_back(0);
  4041. Vals.push_back(0);
  4042. Vals.push_back(0);
  4043. Vals.push_back(getEncodedLinkage(I));
  4044. Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
  4045. Vals.clear();
  4046. }
  4047. }
  4048. void ThinLinkBitcodeWriter::write() {
  4049. Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
  4050. writeModuleVersion();
  4051. writeSimplifiedModuleInfo();
  4052. writePerModuleGlobalValueSummary();
  4053. // Write module hash.
  4054. Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash));
  4055. Stream.ExitBlock();
  4056. }
  4057. void BitcodeWriter::writeThinLinkBitcode(const Module &M,
  4058. const ModuleSummaryIndex &Index,
  4059. const ModuleHash &ModHash) {
  4060. assert(!WroteStrtab);
  4061. // The Mods vector is used by irsymtab::build, which requires non-const
  4062. // Modules in case it needs to materialize metadata. But the bitcode writer
  4063. // requires that the module is materialized, so we can cast to non-const here,
  4064. // after checking that it is in fact materialized.
  4065. assert(M.isMaterialized());
  4066. Mods.push_back(const_cast<Module *>(&M));
  4067. ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
  4068. ModHash);
  4069. ThinLinkWriter.write();
  4070. }
  4071. // Write the specified thin link bitcode file to the given raw output stream,
  4072. // where it will be written in a new bitcode block. This is used when
  4073. // writing the per-module index file for ThinLTO.
  4074. void llvm::WriteThinLinkBitcodeToFile(const Module &M, raw_ostream &Out,
  4075. const ModuleSummaryIndex &Index,
  4076. const ModuleHash &ModHash) {
  4077. SmallVector<char, 0> Buffer;
  4078. Buffer.reserve(256 * 1024);
  4079. BitcodeWriter Writer(Buffer);
  4080. Writer.writeThinLinkBitcode(M, Index, ModHash);
  4081. Writer.writeSymtab();
  4082. Writer.writeStrtab();
  4083. Out.write((char *)&Buffer.front(), Buffer.size());
  4084. }