BitcodeWriter.cpp 168 KB

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