BitcodeWriter.cpp 147 KB

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