BitcodeWriter.cpp 162 KB

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