BitcodeWriter.cpp 164 KB

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