BitcodeWriter.cpp 161 KB

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