BitcodeWriter.cpp 167 KB

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