BitcodeWriter.cpp 173 KB

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