BitcodeWriter.cpp 170 KB

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