BitcodeWriter.cpp 189 KB

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