BitcodeReader.cpp 219 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199
  1. //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
  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. #include "llvm/Bitcode/BitcodeReader.h"
  9. #include "MetadataLoader.h"
  10. #include "ValueList.h"
  11. #include "llvm/ADT/APFloat.h"
  12. #include "llvm/ADT/APInt.h"
  13. #include "llvm/ADT/ArrayRef.h"
  14. #include "llvm/ADT/DenseMap.h"
  15. #include "llvm/ADT/Optional.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/SmallString.h"
  18. #include "llvm/ADT/SmallVector.h"
  19. #include "llvm/ADT/StringRef.h"
  20. #include "llvm/ADT/Triple.h"
  21. #include "llvm/ADT/Twine.h"
  22. #include "llvm/Bitcode/BitstreamReader.h"
  23. #include "llvm/Bitcode/LLVMBitCodes.h"
  24. #include "llvm/Config/llvm-config.h"
  25. #include "llvm/IR/Argument.h"
  26. #include "llvm/IR/Attributes.h"
  27. #include "llvm/IR/AutoUpgrade.h"
  28. #include "llvm/IR/BasicBlock.h"
  29. #include "llvm/IR/CallSite.h"
  30. #include "llvm/IR/CallingConv.h"
  31. #include "llvm/IR/Comdat.h"
  32. #include "llvm/IR/Constant.h"
  33. #include "llvm/IR/Constants.h"
  34. #include "llvm/IR/DataLayout.h"
  35. #include "llvm/IR/DebugInfo.h"
  36. #include "llvm/IR/DebugInfoMetadata.h"
  37. #include "llvm/IR/DebugLoc.h"
  38. #include "llvm/IR/DerivedTypes.h"
  39. #include "llvm/IR/Function.h"
  40. #include "llvm/IR/GVMaterializer.h"
  41. #include "llvm/IR/GlobalAlias.h"
  42. #include "llvm/IR/GlobalIFunc.h"
  43. #include "llvm/IR/GlobalIndirectSymbol.h"
  44. #include "llvm/IR/GlobalObject.h"
  45. #include "llvm/IR/GlobalValue.h"
  46. #include "llvm/IR/GlobalVariable.h"
  47. #include "llvm/IR/InlineAsm.h"
  48. #include "llvm/IR/InstIterator.h"
  49. #include "llvm/IR/InstrTypes.h"
  50. #include "llvm/IR/Instruction.h"
  51. #include "llvm/IR/Instructions.h"
  52. #include "llvm/IR/Intrinsics.h"
  53. #include "llvm/IR/LLVMContext.h"
  54. #include "llvm/IR/Metadata.h"
  55. #include "llvm/IR/Module.h"
  56. #include "llvm/IR/ModuleSummaryIndex.h"
  57. #include "llvm/IR/Operator.h"
  58. #include "llvm/IR/Type.h"
  59. #include "llvm/IR/Value.h"
  60. #include "llvm/IR/Verifier.h"
  61. #include "llvm/Support/AtomicOrdering.h"
  62. #include "llvm/Support/Casting.h"
  63. #include "llvm/Support/CommandLine.h"
  64. #include "llvm/Support/Compiler.h"
  65. #include "llvm/Support/Debug.h"
  66. #include "llvm/Support/Error.h"
  67. #include "llvm/Support/ErrorHandling.h"
  68. #include "llvm/Support/ErrorOr.h"
  69. #include "llvm/Support/ManagedStatic.h"
  70. #include "llvm/Support/MathExtras.h"
  71. #include "llvm/Support/MemoryBuffer.h"
  72. #include "llvm/Support/raw_ostream.h"
  73. #include <algorithm>
  74. #include <cassert>
  75. #include <cstddef>
  76. #include <cstdint>
  77. #include <deque>
  78. #include <map>
  79. #include <memory>
  80. #include <set>
  81. #include <string>
  82. #include <system_error>
  83. #include <tuple>
  84. #include <utility>
  85. #include <vector>
  86. using namespace llvm;
  87. static cl::opt<bool> PrintSummaryGUIDs(
  88. "print-summary-global-ids", cl::init(false), cl::Hidden,
  89. cl::desc(
  90. "Print the global id for each value when reading the module summary"));
  91. namespace {
  92. enum {
  93. SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
  94. };
  95. } // end anonymous namespace
  96. static Error error(const Twine &Message) {
  97. return make_error<StringError>(
  98. Message, make_error_code(BitcodeError::CorruptedBitcode));
  99. }
  100. /// Helper to read the header common to all bitcode files.
  101. static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
  102. // Sniff for the signature.
  103. if (!Stream.canSkipToPos(4) ||
  104. Stream.Read(8) != 'B' ||
  105. Stream.Read(8) != 'C' ||
  106. Stream.Read(4) != 0x0 ||
  107. Stream.Read(4) != 0xC ||
  108. Stream.Read(4) != 0xE ||
  109. Stream.Read(4) != 0xD)
  110. return false;
  111. return true;
  112. }
  113. static Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) {
  114. const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart();
  115. const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize();
  116. if (Buffer.getBufferSize() & 3)
  117. return error("Invalid bitcode signature");
  118. // If we have a wrapper header, parse it and ignore the non-bc file contents.
  119. // The magic number is 0x0B17C0DE stored in little endian.
  120. if (isBitcodeWrapper(BufPtr, BufEnd))
  121. if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
  122. return error("Invalid bitcode wrapper header");
  123. BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd));
  124. if (!hasValidBitcodeHeader(Stream))
  125. return error("Invalid bitcode signature");
  126. return std::move(Stream);
  127. }
  128. /// Convert a string from a record into an std::string, return true on failure.
  129. template <typename StrTy>
  130. static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
  131. StrTy &Result) {
  132. if (Idx > Record.size())
  133. return true;
  134. for (unsigned i = Idx, e = Record.size(); i != e; ++i)
  135. Result += (char)Record[i];
  136. return false;
  137. }
  138. // Strip all the TBAA attachment for the module.
  139. static void stripTBAA(Module *M) {
  140. for (auto &F : *M) {
  141. if (F.isMaterializable())
  142. continue;
  143. for (auto &I : instructions(F))
  144. I.setMetadata(LLVMContext::MD_tbaa, nullptr);
  145. }
  146. }
  147. /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the
  148. /// "epoch" encoded in the bitcode, and return the producer name if any.
  149. static Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) {
  150. if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
  151. return error("Invalid record");
  152. // Read all the records.
  153. SmallVector<uint64_t, 64> Record;
  154. std::string ProducerIdentification;
  155. while (true) {
  156. BitstreamEntry Entry = Stream.advance();
  157. switch (Entry.Kind) {
  158. default:
  159. case BitstreamEntry::Error:
  160. return error("Malformed block");
  161. case BitstreamEntry::EndBlock:
  162. return ProducerIdentification;
  163. case BitstreamEntry::Record:
  164. // The interesting case.
  165. break;
  166. }
  167. // Read a record.
  168. Record.clear();
  169. unsigned BitCode = Stream.readRecord(Entry.ID, Record);
  170. switch (BitCode) {
  171. default: // Default behavior: reject
  172. return error("Invalid value");
  173. case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N]
  174. convertToString(Record, 0, ProducerIdentification);
  175. break;
  176. case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
  177. unsigned epoch = (unsigned)Record[0];
  178. if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
  179. return error(
  180. Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
  181. "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
  182. }
  183. }
  184. }
  185. }
  186. }
  187. static Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) {
  188. // We expect a number of well-defined blocks, though we don't necessarily
  189. // need to understand them all.
  190. while (true) {
  191. if (Stream.AtEndOfStream())
  192. return "";
  193. BitstreamEntry Entry = Stream.advance();
  194. switch (Entry.Kind) {
  195. case BitstreamEntry::EndBlock:
  196. case BitstreamEntry::Error:
  197. return error("Malformed block");
  198. case BitstreamEntry::SubBlock:
  199. if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID)
  200. return readIdentificationBlock(Stream);
  201. // Ignore other sub-blocks.
  202. if (Stream.SkipBlock())
  203. return error("Malformed block");
  204. continue;
  205. case BitstreamEntry::Record:
  206. Stream.skipRecord(Entry.ID);
  207. continue;
  208. }
  209. }
  210. }
  211. static Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) {
  212. if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
  213. return error("Invalid record");
  214. SmallVector<uint64_t, 64> Record;
  215. // Read all the records for this module.
  216. while (true) {
  217. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  218. switch (Entry.Kind) {
  219. case BitstreamEntry::SubBlock: // Handled for us already.
  220. case BitstreamEntry::Error:
  221. return error("Malformed block");
  222. case BitstreamEntry::EndBlock:
  223. return false;
  224. case BitstreamEntry::Record:
  225. // The interesting case.
  226. break;
  227. }
  228. // Read a record.
  229. switch (Stream.readRecord(Entry.ID, Record)) {
  230. default:
  231. break; // Default behavior, ignore unknown content.
  232. case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
  233. std::string S;
  234. if (convertToString(Record, 0, S))
  235. return error("Invalid record");
  236. // Check for the i386 and other (x86_64, ARM) conventions
  237. if (S.find("__DATA,__objc_catlist") != std::string::npos ||
  238. S.find("__OBJC,__category") != std::string::npos)
  239. return true;
  240. break;
  241. }
  242. }
  243. Record.clear();
  244. }
  245. llvm_unreachable("Exit infinite loop");
  246. }
  247. static Expected<bool> hasObjCCategory(BitstreamCursor &Stream) {
  248. // We expect a number of well-defined blocks, though we don't necessarily
  249. // need to understand them all.
  250. while (true) {
  251. BitstreamEntry Entry = Stream.advance();
  252. switch (Entry.Kind) {
  253. case BitstreamEntry::Error:
  254. return error("Malformed block");
  255. case BitstreamEntry::EndBlock:
  256. return false;
  257. case BitstreamEntry::SubBlock:
  258. if (Entry.ID == bitc::MODULE_BLOCK_ID)
  259. return hasObjCCategoryInModule(Stream);
  260. // Ignore other sub-blocks.
  261. if (Stream.SkipBlock())
  262. return error("Malformed block");
  263. continue;
  264. case BitstreamEntry::Record:
  265. Stream.skipRecord(Entry.ID);
  266. continue;
  267. }
  268. }
  269. }
  270. static Expected<std::string> readModuleTriple(BitstreamCursor &Stream) {
  271. if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
  272. return error("Invalid record");
  273. SmallVector<uint64_t, 64> Record;
  274. std::string Triple;
  275. // Read all the records for this module.
  276. while (true) {
  277. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  278. switch (Entry.Kind) {
  279. case BitstreamEntry::SubBlock: // Handled for us already.
  280. case BitstreamEntry::Error:
  281. return error("Malformed block");
  282. case BitstreamEntry::EndBlock:
  283. return Triple;
  284. case BitstreamEntry::Record:
  285. // The interesting case.
  286. break;
  287. }
  288. // Read a record.
  289. switch (Stream.readRecord(Entry.ID, Record)) {
  290. default: break; // Default behavior, ignore unknown content.
  291. case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
  292. std::string S;
  293. if (convertToString(Record, 0, S))
  294. return error("Invalid record");
  295. Triple = S;
  296. break;
  297. }
  298. }
  299. Record.clear();
  300. }
  301. llvm_unreachable("Exit infinite loop");
  302. }
  303. static Expected<std::string> readTriple(BitstreamCursor &Stream) {
  304. // We expect a number of well-defined blocks, though we don't necessarily
  305. // need to understand them all.
  306. while (true) {
  307. BitstreamEntry Entry = Stream.advance();
  308. switch (Entry.Kind) {
  309. case BitstreamEntry::Error:
  310. return error("Malformed block");
  311. case BitstreamEntry::EndBlock:
  312. return "";
  313. case BitstreamEntry::SubBlock:
  314. if (Entry.ID == bitc::MODULE_BLOCK_ID)
  315. return readModuleTriple(Stream);
  316. // Ignore other sub-blocks.
  317. if (Stream.SkipBlock())
  318. return error("Malformed block");
  319. continue;
  320. case BitstreamEntry::Record:
  321. Stream.skipRecord(Entry.ID);
  322. continue;
  323. }
  324. }
  325. }
  326. namespace {
  327. class BitcodeReaderBase {
  328. protected:
  329. BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)
  330. : Stream(std::move(Stream)), Strtab(Strtab) {
  331. this->Stream.setBlockInfo(&BlockInfo);
  332. }
  333. BitstreamBlockInfo BlockInfo;
  334. BitstreamCursor Stream;
  335. StringRef Strtab;
  336. /// In version 2 of the bitcode we store names of global values and comdats in
  337. /// a string table rather than in the VST.
  338. bool UseStrtab = false;
  339. Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
  340. /// If this module uses a string table, pop the reference to the string table
  341. /// and return the referenced string and the rest of the record. Otherwise
  342. /// just return the record itself.
  343. std::pair<StringRef, ArrayRef<uint64_t>>
  344. readNameFromStrtab(ArrayRef<uint64_t> Record);
  345. bool readBlockInfo();
  346. // Contains an arbitrary and optional string identifying the bitcode producer
  347. std::string ProducerIdentification;
  348. Error error(const Twine &Message);
  349. };
  350. } // end anonymous namespace
  351. Error BitcodeReaderBase::error(const Twine &Message) {
  352. std::string FullMsg = Message.str();
  353. if (!ProducerIdentification.empty())
  354. FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " +
  355. LLVM_VERSION_STRING "')";
  356. return ::error(FullMsg);
  357. }
  358. Expected<unsigned>
  359. BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
  360. if (Record.empty())
  361. return error("Invalid record");
  362. unsigned ModuleVersion = Record[0];
  363. if (ModuleVersion > 2)
  364. return error("Invalid value");
  365. UseStrtab = ModuleVersion >= 2;
  366. return ModuleVersion;
  367. }
  368. std::pair<StringRef, ArrayRef<uint64_t>>
  369. BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {
  370. if (!UseStrtab)
  371. return {"", Record};
  372. // Invalid reference. Let the caller complain about the record being empty.
  373. if (Record[0] + Record[1] > Strtab.size())
  374. return {"", {}};
  375. return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)};
  376. }
  377. namespace {
  378. class BitcodeReader : public BitcodeReaderBase, public GVMaterializer {
  379. LLVMContext &Context;
  380. Module *TheModule = nullptr;
  381. // Next offset to start scanning for lazy parsing of function bodies.
  382. uint64_t NextUnreadBit = 0;
  383. // Last function offset found in the VST.
  384. uint64_t LastFunctionBlockBit = 0;
  385. bool SeenValueSymbolTable = false;
  386. uint64_t VSTOffset = 0;
  387. std::vector<std::string> SectionTable;
  388. std::vector<std::string> GCTable;
  389. std::vector<Type*> TypeList;
  390. BitcodeReaderValueList ValueList;
  391. Optional<MetadataLoader> MDLoader;
  392. std::vector<Comdat *> ComdatList;
  393. SmallVector<Instruction *, 64> InstructionList;
  394. std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
  395. std::vector<std::pair<GlobalIndirectSymbol *, unsigned>> IndirectSymbolInits;
  396. std::vector<std::pair<Function *, unsigned>> FunctionPrefixes;
  397. std::vector<std::pair<Function *, unsigned>> FunctionPrologues;
  398. std::vector<std::pair<Function *, unsigned>> FunctionPersonalityFns;
  399. /// The set of attributes by index. Index zero in the file is for null, and
  400. /// is thus not represented here. As such all indices are off by one.
  401. std::vector<AttributeList> MAttributes;
  402. /// The set of attribute groups.
  403. std::map<unsigned, AttributeList> MAttributeGroups;
  404. /// While parsing a function body, this is a list of the basic blocks for the
  405. /// function.
  406. std::vector<BasicBlock*> FunctionBBs;
  407. // When reading the module header, this list is populated with functions that
  408. // have bodies later in the file.
  409. std::vector<Function*> FunctionsWithBodies;
  410. // When intrinsic functions are encountered which require upgrading they are
  411. // stored here with their replacement function.
  412. using UpdatedIntrinsicMap = DenseMap<Function *, Function *>;
  413. UpdatedIntrinsicMap UpgradedIntrinsics;
  414. // Intrinsics which were remangled because of types rename
  415. UpdatedIntrinsicMap RemangledIntrinsics;
  416. // Several operations happen after the module header has been read, but
  417. // before function bodies are processed. This keeps track of whether
  418. // we've done this yet.
  419. bool SeenFirstFunctionBody = false;
  420. /// When function bodies are initially scanned, this map contains info about
  421. /// where to find deferred function body in the stream.
  422. DenseMap<Function*, uint64_t> DeferredFunctionInfo;
  423. /// When Metadata block is initially scanned when parsing the module, we may
  424. /// choose to defer parsing of the metadata. This vector contains info about
  425. /// which Metadata blocks are deferred.
  426. std::vector<uint64_t> DeferredMetadataInfo;
  427. /// These are basic blocks forward-referenced by block addresses. They are
  428. /// inserted lazily into functions when they're loaded. The basic block ID is
  429. /// its index into the vector.
  430. DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
  431. std::deque<Function *> BasicBlockFwdRefQueue;
  432. /// Indicates that we are using a new encoding for instruction operands where
  433. /// most operands in the current FUNCTION_BLOCK are encoded relative to the
  434. /// instruction number, for a more compact encoding. Some instruction
  435. /// operands are not relative to the instruction ID: basic block numbers, and
  436. /// types. Once the old style function blocks have been phased out, we would
  437. /// not need this flag.
  438. bool UseRelativeIDs = false;
  439. /// True if all functions will be materialized, negating the need to process
  440. /// (e.g.) blockaddress forward references.
  441. bool WillMaterializeAllForwardRefs = false;
  442. bool StripDebugInfo = false;
  443. TBAAVerifier TBAAVerifyHelper;
  444. std::vector<std::string> BundleTags;
  445. SmallVector<SyncScope::ID, 8> SSIDs;
  446. public:
  447. BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
  448. StringRef ProducerIdentification, LLVMContext &Context);
  449. Error materializeForwardReferencedFunctions();
  450. Error materialize(GlobalValue *GV) override;
  451. Error materializeModule() override;
  452. std::vector<StructType *> getIdentifiedStructTypes() const override;
  453. /// Main interface to parsing a bitcode buffer.
  454. /// \returns true if an error occurred.
  455. Error parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata = false,
  456. bool IsImporting = false);
  457. static uint64_t decodeSignRotatedValue(uint64_t V);
  458. /// Materialize any deferred Metadata block.
  459. Error materializeMetadata() override;
  460. void setStripDebugInfo() override;
  461. private:
  462. std::vector<StructType *> IdentifiedStructTypes;
  463. StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
  464. StructType *createIdentifiedStructType(LLVMContext &Context);
  465. Type *getTypeByID(unsigned ID);
  466. Value *getFnValueByID(unsigned ID, Type *Ty) {
  467. if (Ty && Ty->isMetadataTy())
  468. return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
  469. return ValueList.getValueFwdRef(ID, Ty);
  470. }
  471. Metadata *getFnMetadataByID(unsigned ID) {
  472. return MDLoader->getMetadataFwdRefOrLoad(ID);
  473. }
  474. BasicBlock *getBasicBlock(unsigned ID) const {
  475. if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
  476. return FunctionBBs[ID];
  477. }
  478. AttributeList getAttributes(unsigned i) const {
  479. if (i-1 < MAttributes.size())
  480. return MAttributes[i-1];
  481. return AttributeList();
  482. }
  483. /// Read a value/type pair out of the specified record from slot 'Slot'.
  484. /// Increment Slot past the number of slots used in the record. Return true on
  485. /// failure.
  486. bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
  487. unsigned InstNum, Value *&ResVal) {
  488. if (Slot == Record.size()) return true;
  489. unsigned ValNo = (unsigned)Record[Slot++];
  490. // Adjust the ValNo, if it was encoded relative to the InstNum.
  491. if (UseRelativeIDs)
  492. ValNo = InstNum - ValNo;
  493. if (ValNo < InstNum) {
  494. // If this is not a forward reference, just return the value we already
  495. // have.
  496. ResVal = getFnValueByID(ValNo, nullptr);
  497. return ResVal == nullptr;
  498. }
  499. if (Slot == Record.size())
  500. return true;
  501. unsigned TypeNo = (unsigned)Record[Slot++];
  502. ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
  503. return ResVal == nullptr;
  504. }
  505. /// Read a value out of the specified record from slot 'Slot'. Increment Slot
  506. /// past the number of slots used by the value in the record. Return true if
  507. /// there is an error.
  508. bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
  509. unsigned InstNum, Type *Ty, Value *&ResVal) {
  510. if (getValue(Record, Slot, InstNum, Ty, ResVal))
  511. return true;
  512. // All values currently take a single record slot.
  513. ++Slot;
  514. return false;
  515. }
  516. /// Like popValue, but does not increment the Slot number.
  517. bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
  518. unsigned InstNum, Type *Ty, Value *&ResVal) {
  519. ResVal = getValue(Record, Slot, InstNum, Ty);
  520. return ResVal == nullptr;
  521. }
  522. /// Version of getValue that returns ResVal directly, or 0 if there is an
  523. /// error.
  524. Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
  525. unsigned InstNum, Type *Ty) {
  526. if (Slot == Record.size()) return nullptr;
  527. unsigned ValNo = (unsigned)Record[Slot];
  528. // Adjust the ValNo, if it was encoded relative to the InstNum.
  529. if (UseRelativeIDs)
  530. ValNo = InstNum - ValNo;
  531. return getFnValueByID(ValNo, Ty);
  532. }
  533. /// Like getValue, but decodes signed VBRs.
  534. Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
  535. unsigned InstNum, Type *Ty) {
  536. if (Slot == Record.size()) return nullptr;
  537. unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
  538. // Adjust the ValNo, if it was encoded relative to the InstNum.
  539. if (UseRelativeIDs)
  540. ValNo = InstNum - ValNo;
  541. return getFnValueByID(ValNo, Ty);
  542. }
  543. /// Converts alignment exponent (i.e. power of two (or zero)) to the
  544. /// corresponding alignment to use. If alignment is too large, returns
  545. /// a corresponding error code.
  546. Error parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
  547. Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
  548. Error parseModule(uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false);
  549. Error parseComdatRecord(ArrayRef<uint64_t> Record);
  550. Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
  551. Error parseFunctionRecord(ArrayRef<uint64_t> Record);
  552. Error parseGlobalIndirectSymbolRecord(unsigned BitCode,
  553. ArrayRef<uint64_t> Record);
  554. Error parseAttributeBlock();
  555. Error parseAttributeGroupBlock();
  556. Error parseTypeTable();
  557. Error parseTypeTableBody();
  558. Error parseOperandBundleTags();
  559. Error parseSyncScopeNames();
  560. Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
  561. unsigned NameIndex, Triple &TT);
  562. void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F,
  563. ArrayRef<uint64_t> Record);
  564. Error parseValueSymbolTable(uint64_t Offset = 0);
  565. Error parseGlobalValueSymbolTable();
  566. Error parseConstants();
  567. Error rememberAndSkipFunctionBodies();
  568. Error rememberAndSkipFunctionBody();
  569. /// Save the positions of the Metadata blocks and skip parsing the blocks.
  570. Error rememberAndSkipMetadata();
  571. Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType);
  572. Error parseFunctionBody(Function *F);
  573. Error globalCleanup();
  574. Error resolveGlobalAndIndirectSymbolInits();
  575. Error parseUseLists();
  576. Error findFunctionInStream(
  577. Function *F,
  578. DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
  579. SyncScope::ID getDecodedSyncScopeID(unsigned Val);
  580. };
  581. /// Class to manage reading and parsing function summary index bitcode
  582. /// files/sections.
  583. class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
  584. /// The module index built during parsing.
  585. ModuleSummaryIndex &TheIndex;
  586. /// Indicates whether we have encountered a global value summary section
  587. /// yet during parsing.
  588. bool SeenGlobalValSummary = false;
  589. /// Indicates whether we have already parsed the VST, used for error checking.
  590. bool SeenValueSymbolTable = false;
  591. /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
  592. /// Used to enable on-demand parsing of the VST.
  593. uint64_t VSTOffset = 0;
  594. // Map to save ValueId to ValueInfo association that was recorded in the
  595. // ValueSymbolTable. It is used after the VST is parsed to convert
  596. // call graph edges read from the function summary from referencing
  597. // callees by their ValueId to using the ValueInfo instead, which is how
  598. // they are recorded in the summary index being built.
  599. // We save a GUID which refers to the same global as the ValueInfo, but
  600. // ignoring the linkage, i.e. for values other than local linkage they are
  601. // identical.
  602. DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>>
  603. ValueIdToValueInfoMap;
  604. /// Map populated during module path string table parsing, from the
  605. /// module ID to a string reference owned by the index's module
  606. /// path string table, used to correlate with combined index
  607. /// summary records.
  608. DenseMap<uint64_t, StringRef> ModuleIdMap;
  609. /// Original source file name recorded in a bitcode record.
  610. std::string SourceFileName;
  611. /// The string identifier given to this module by the client, normally the
  612. /// path to the bitcode file.
  613. StringRef ModulePath;
  614. /// For per-module summary indexes, the unique numerical identifier given to
  615. /// this module by the client.
  616. unsigned ModuleId;
  617. public:
  618. ModuleSummaryIndexBitcodeReader(BitstreamCursor Stream, StringRef Strtab,
  619. ModuleSummaryIndex &TheIndex,
  620. StringRef ModulePath, unsigned ModuleId);
  621. Error parseModule();
  622. private:
  623. void setValueGUID(uint64_t ValueID, StringRef ValueName,
  624. GlobalValue::LinkageTypes Linkage,
  625. StringRef SourceFileName);
  626. Error parseValueSymbolTable(
  627. uint64_t Offset,
  628. DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
  629. std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record);
  630. std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record,
  631. bool IsOldProfileFormat,
  632. bool HasProfile,
  633. bool HasRelBF);
  634. Error parseEntireSummary(unsigned ID);
  635. Error parseModuleStringTable();
  636. std::pair<ValueInfo, GlobalValue::GUID>
  637. getValueInfoFromValueId(unsigned ValueId);
  638. void addThisModule();
  639. ModuleSummaryIndex::ModuleInfo *getThisModule();
  640. };
  641. } // end anonymous namespace
  642. std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx,
  643. Error Err) {
  644. if (Err) {
  645. std::error_code EC;
  646. handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
  647. EC = EIB.convertToErrorCode();
  648. Ctx.emitError(EIB.message());
  649. });
  650. return EC;
  651. }
  652. return std::error_code();
  653. }
  654. BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
  655. StringRef ProducerIdentification,
  656. LLVMContext &Context)
  657. : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context),
  658. ValueList(Context) {
  659. this->ProducerIdentification = ProducerIdentification;
  660. }
  661. Error BitcodeReader::materializeForwardReferencedFunctions() {
  662. if (WillMaterializeAllForwardRefs)
  663. return Error::success();
  664. // Prevent recursion.
  665. WillMaterializeAllForwardRefs = true;
  666. while (!BasicBlockFwdRefQueue.empty()) {
  667. Function *F = BasicBlockFwdRefQueue.front();
  668. BasicBlockFwdRefQueue.pop_front();
  669. assert(F && "Expected valid function");
  670. if (!BasicBlockFwdRefs.count(F))
  671. // Already materialized.
  672. continue;
  673. // Check for a function that isn't materializable to prevent an infinite
  674. // loop. When parsing a blockaddress stored in a global variable, there
  675. // isn't a trivial way to check if a function will have a body without a
  676. // linear search through FunctionsWithBodies, so just check it here.
  677. if (!F->isMaterializable())
  678. return error("Never resolved function from blockaddress");
  679. // Try to materialize F.
  680. if (Error Err = materialize(F))
  681. return Err;
  682. }
  683. assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
  684. // Reset state.
  685. WillMaterializeAllForwardRefs = false;
  686. return Error::success();
  687. }
  688. //===----------------------------------------------------------------------===//
  689. // Helper functions to implement forward reference resolution, etc.
  690. //===----------------------------------------------------------------------===//
  691. static bool hasImplicitComdat(size_t Val) {
  692. switch (Val) {
  693. default:
  694. return false;
  695. case 1: // Old WeakAnyLinkage
  696. case 4: // Old LinkOnceAnyLinkage
  697. case 10: // Old WeakODRLinkage
  698. case 11: // Old LinkOnceODRLinkage
  699. return true;
  700. }
  701. }
  702. static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
  703. switch (Val) {
  704. default: // Map unknown/new linkages to external
  705. case 0:
  706. return GlobalValue::ExternalLinkage;
  707. case 2:
  708. return GlobalValue::AppendingLinkage;
  709. case 3:
  710. return GlobalValue::InternalLinkage;
  711. case 5:
  712. return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
  713. case 6:
  714. return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
  715. case 7:
  716. return GlobalValue::ExternalWeakLinkage;
  717. case 8:
  718. return GlobalValue::CommonLinkage;
  719. case 9:
  720. return GlobalValue::PrivateLinkage;
  721. case 12:
  722. return GlobalValue::AvailableExternallyLinkage;
  723. case 13:
  724. return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
  725. case 14:
  726. return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
  727. case 15:
  728. return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
  729. case 1: // Old value with implicit comdat.
  730. case 16:
  731. return GlobalValue::WeakAnyLinkage;
  732. case 10: // Old value with implicit comdat.
  733. case 17:
  734. return GlobalValue::WeakODRLinkage;
  735. case 4: // Old value with implicit comdat.
  736. case 18:
  737. return GlobalValue::LinkOnceAnyLinkage;
  738. case 11: // Old value with implicit comdat.
  739. case 19:
  740. return GlobalValue::LinkOnceODRLinkage;
  741. }
  742. }
  743. static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags) {
  744. FunctionSummary::FFlags Flags;
  745. Flags.ReadNone = RawFlags & 0x1;
  746. Flags.ReadOnly = (RawFlags >> 1) & 0x1;
  747. Flags.NoRecurse = (RawFlags >> 2) & 0x1;
  748. Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
  749. Flags.NoInline = (RawFlags >> 4) & 0x1;
  750. return Flags;
  751. }
  752. /// Decode the flags for GlobalValue in the summary.
  753. static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags,
  754. uint64_t Version) {
  755. // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
  756. // like getDecodedLinkage() above. Any future change to the linkage enum and
  757. // to getDecodedLinkage() will need to be taken into account here as above.
  758. auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
  759. RawFlags = RawFlags >> 4;
  760. bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
  761. // The Live flag wasn't introduced until version 3. For dead stripping
  762. // to work correctly on earlier versions, we must conservatively treat all
  763. // values as live.
  764. bool Live = (RawFlags & 0x2) || Version < 3;
  765. bool Local = (RawFlags & 0x4);
  766. return GlobalValueSummary::GVFlags(Linkage, NotEligibleToImport, Live, Local);
  767. }
  768. // Decode the flags for GlobalVariable in the summary
  769. static GlobalVarSummary::GVarFlags getDecodedGVarFlags(uint64_t RawFlags) {
  770. return GlobalVarSummary::GVarFlags((RawFlags & 0x1) ? true : false);
  771. }
  772. static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
  773. switch (Val) {
  774. default: // Map unknown visibilities to default.
  775. case 0: return GlobalValue::DefaultVisibility;
  776. case 1: return GlobalValue::HiddenVisibility;
  777. case 2: return GlobalValue::ProtectedVisibility;
  778. }
  779. }
  780. static GlobalValue::DLLStorageClassTypes
  781. getDecodedDLLStorageClass(unsigned Val) {
  782. switch (Val) {
  783. default: // Map unknown values to default.
  784. case 0: return GlobalValue::DefaultStorageClass;
  785. case 1: return GlobalValue::DLLImportStorageClass;
  786. case 2: return GlobalValue::DLLExportStorageClass;
  787. }
  788. }
  789. static bool getDecodedDSOLocal(unsigned Val) {
  790. switch(Val) {
  791. default: // Map unknown values to preemptable.
  792. case 0: return false;
  793. case 1: return true;
  794. }
  795. }
  796. static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
  797. switch (Val) {
  798. case 0: return GlobalVariable::NotThreadLocal;
  799. default: // Map unknown non-zero value to general dynamic.
  800. case 1: return GlobalVariable::GeneralDynamicTLSModel;
  801. case 2: return GlobalVariable::LocalDynamicTLSModel;
  802. case 3: return GlobalVariable::InitialExecTLSModel;
  803. case 4: return GlobalVariable::LocalExecTLSModel;
  804. }
  805. }
  806. static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
  807. switch (Val) {
  808. default: // Map unknown to UnnamedAddr::None.
  809. case 0: return GlobalVariable::UnnamedAddr::None;
  810. case 1: return GlobalVariable::UnnamedAddr::Global;
  811. case 2: return GlobalVariable::UnnamedAddr::Local;
  812. }
  813. }
  814. static int getDecodedCastOpcode(unsigned Val) {
  815. switch (Val) {
  816. default: return -1;
  817. case bitc::CAST_TRUNC : return Instruction::Trunc;
  818. case bitc::CAST_ZEXT : return Instruction::ZExt;
  819. case bitc::CAST_SEXT : return Instruction::SExt;
  820. case bitc::CAST_FPTOUI : return Instruction::FPToUI;
  821. case bitc::CAST_FPTOSI : return Instruction::FPToSI;
  822. case bitc::CAST_UITOFP : return Instruction::UIToFP;
  823. case bitc::CAST_SITOFP : return Instruction::SIToFP;
  824. case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
  825. case bitc::CAST_FPEXT : return Instruction::FPExt;
  826. case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
  827. case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
  828. case bitc::CAST_BITCAST : return Instruction::BitCast;
  829. case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
  830. }
  831. }
  832. static int getDecodedUnaryOpcode(unsigned Val, Type *Ty) {
  833. bool IsFP = Ty->isFPOrFPVectorTy();
  834. // UnOps are only valid for int/fp or vector of int/fp types
  835. if (!IsFP && !Ty->isIntOrIntVectorTy())
  836. return -1;
  837. switch (Val) {
  838. default:
  839. return -1;
  840. case bitc::UNOP_NEG:
  841. return IsFP ? Instruction::FNeg : -1;
  842. }
  843. }
  844. static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
  845. bool IsFP = Ty->isFPOrFPVectorTy();
  846. // BinOps are only valid for int/fp or vector of int/fp types
  847. if (!IsFP && !Ty->isIntOrIntVectorTy())
  848. return -1;
  849. switch (Val) {
  850. default:
  851. return -1;
  852. case bitc::BINOP_ADD:
  853. return IsFP ? Instruction::FAdd : Instruction::Add;
  854. case bitc::BINOP_SUB:
  855. return IsFP ? Instruction::FSub : Instruction::Sub;
  856. case bitc::BINOP_MUL:
  857. return IsFP ? Instruction::FMul : Instruction::Mul;
  858. case bitc::BINOP_UDIV:
  859. return IsFP ? -1 : Instruction::UDiv;
  860. case bitc::BINOP_SDIV:
  861. return IsFP ? Instruction::FDiv : Instruction::SDiv;
  862. case bitc::BINOP_UREM:
  863. return IsFP ? -1 : Instruction::URem;
  864. case bitc::BINOP_SREM:
  865. return IsFP ? Instruction::FRem : Instruction::SRem;
  866. case bitc::BINOP_SHL:
  867. return IsFP ? -1 : Instruction::Shl;
  868. case bitc::BINOP_LSHR:
  869. return IsFP ? -1 : Instruction::LShr;
  870. case bitc::BINOP_ASHR:
  871. return IsFP ? -1 : Instruction::AShr;
  872. case bitc::BINOP_AND:
  873. return IsFP ? -1 : Instruction::And;
  874. case bitc::BINOP_OR:
  875. return IsFP ? -1 : Instruction::Or;
  876. case bitc::BINOP_XOR:
  877. return IsFP ? -1 : Instruction::Xor;
  878. }
  879. }
  880. static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
  881. switch (Val) {
  882. default: return AtomicRMWInst::BAD_BINOP;
  883. case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
  884. case bitc::RMW_ADD: return AtomicRMWInst::Add;
  885. case bitc::RMW_SUB: return AtomicRMWInst::Sub;
  886. case bitc::RMW_AND: return AtomicRMWInst::And;
  887. case bitc::RMW_NAND: return AtomicRMWInst::Nand;
  888. case bitc::RMW_OR: return AtomicRMWInst::Or;
  889. case bitc::RMW_XOR: return AtomicRMWInst::Xor;
  890. case bitc::RMW_MAX: return AtomicRMWInst::Max;
  891. case bitc::RMW_MIN: return AtomicRMWInst::Min;
  892. case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
  893. case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
  894. case bitc::RMW_FADD: return AtomicRMWInst::FAdd;
  895. case bitc::RMW_FSUB: return AtomicRMWInst::FSub;
  896. }
  897. }
  898. static AtomicOrdering getDecodedOrdering(unsigned Val) {
  899. switch (Val) {
  900. case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
  901. case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
  902. case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
  903. case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
  904. case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
  905. case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
  906. default: // Map unknown orderings to sequentially-consistent.
  907. case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
  908. }
  909. }
  910. static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
  911. switch (Val) {
  912. default: // Map unknown selection kinds to any.
  913. case bitc::COMDAT_SELECTION_KIND_ANY:
  914. return Comdat::Any;
  915. case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
  916. return Comdat::ExactMatch;
  917. case bitc::COMDAT_SELECTION_KIND_LARGEST:
  918. return Comdat::Largest;
  919. case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
  920. return Comdat::NoDuplicates;
  921. case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
  922. return Comdat::SameSize;
  923. }
  924. }
  925. static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
  926. FastMathFlags FMF;
  927. if (0 != (Val & bitc::UnsafeAlgebra))
  928. FMF.setFast();
  929. if (0 != (Val & bitc::AllowReassoc))
  930. FMF.setAllowReassoc();
  931. if (0 != (Val & bitc::NoNaNs))
  932. FMF.setNoNaNs();
  933. if (0 != (Val & bitc::NoInfs))
  934. FMF.setNoInfs();
  935. if (0 != (Val & bitc::NoSignedZeros))
  936. FMF.setNoSignedZeros();
  937. if (0 != (Val & bitc::AllowReciprocal))
  938. FMF.setAllowReciprocal();
  939. if (0 != (Val & bitc::AllowContract))
  940. FMF.setAllowContract(true);
  941. if (0 != (Val & bitc::ApproxFunc))
  942. FMF.setApproxFunc();
  943. return FMF;
  944. }
  945. static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
  946. switch (Val) {
  947. case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
  948. case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
  949. }
  950. }
  951. Type *BitcodeReader::getTypeByID(unsigned ID) {
  952. // The type table size is always specified correctly.
  953. if (ID >= TypeList.size())
  954. return nullptr;
  955. if (Type *Ty = TypeList[ID])
  956. return Ty;
  957. // If we have a forward reference, the only possible case is when it is to a
  958. // named struct. Just create a placeholder for now.
  959. return TypeList[ID] = createIdentifiedStructType(Context);
  960. }
  961. StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
  962. StringRef Name) {
  963. auto *Ret = StructType::create(Context, Name);
  964. IdentifiedStructTypes.push_back(Ret);
  965. return Ret;
  966. }
  967. StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
  968. auto *Ret = StructType::create(Context);
  969. IdentifiedStructTypes.push_back(Ret);
  970. return Ret;
  971. }
  972. //===----------------------------------------------------------------------===//
  973. // Functions for parsing blocks from the bitcode file
  974. //===----------------------------------------------------------------------===//
  975. static uint64_t getRawAttributeMask(Attribute::AttrKind Val) {
  976. switch (Val) {
  977. case Attribute::EndAttrKinds:
  978. llvm_unreachable("Synthetic enumerators which should never get here");
  979. case Attribute::None: return 0;
  980. case Attribute::ZExt: return 1 << 0;
  981. case Attribute::SExt: return 1 << 1;
  982. case Attribute::NoReturn: return 1 << 2;
  983. case Attribute::InReg: return 1 << 3;
  984. case Attribute::StructRet: return 1 << 4;
  985. case Attribute::NoUnwind: return 1 << 5;
  986. case Attribute::NoAlias: return 1 << 6;
  987. case Attribute::ByVal: return 1 << 7;
  988. case Attribute::Nest: return 1 << 8;
  989. case Attribute::ReadNone: return 1 << 9;
  990. case Attribute::ReadOnly: return 1 << 10;
  991. case Attribute::NoInline: return 1 << 11;
  992. case Attribute::AlwaysInline: return 1 << 12;
  993. case Attribute::OptimizeForSize: return 1 << 13;
  994. case Attribute::StackProtect: return 1 << 14;
  995. case Attribute::StackProtectReq: return 1 << 15;
  996. case Attribute::Alignment: return 31 << 16;
  997. case Attribute::NoCapture: return 1 << 21;
  998. case Attribute::NoRedZone: return 1 << 22;
  999. case Attribute::NoImplicitFloat: return 1 << 23;
  1000. case Attribute::Naked: return 1 << 24;
  1001. case Attribute::InlineHint: return 1 << 25;
  1002. case Attribute::StackAlignment: return 7 << 26;
  1003. case Attribute::ReturnsTwice: return 1 << 29;
  1004. case Attribute::UWTable: return 1 << 30;
  1005. case Attribute::NonLazyBind: return 1U << 31;
  1006. case Attribute::SanitizeAddress: return 1ULL << 32;
  1007. case Attribute::MinSize: return 1ULL << 33;
  1008. case Attribute::NoDuplicate: return 1ULL << 34;
  1009. case Attribute::StackProtectStrong: return 1ULL << 35;
  1010. case Attribute::SanitizeThread: return 1ULL << 36;
  1011. case Attribute::SanitizeMemory: return 1ULL << 37;
  1012. case Attribute::NoBuiltin: return 1ULL << 38;
  1013. case Attribute::Returned: return 1ULL << 39;
  1014. case Attribute::Cold: return 1ULL << 40;
  1015. case Attribute::Builtin: return 1ULL << 41;
  1016. case Attribute::OptimizeNone: return 1ULL << 42;
  1017. case Attribute::InAlloca: return 1ULL << 43;
  1018. case Attribute::NonNull: return 1ULL << 44;
  1019. case Attribute::JumpTable: return 1ULL << 45;
  1020. case Attribute::Convergent: return 1ULL << 46;
  1021. case Attribute::SafeStack: return 1ULL << 47;
  1022. case Attribute::NoRecurse: return 1ULL << 48;
  1023. case Attribute::InaccessibleMemOnly: return 1ULL << 49;
  1024. case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50;
  1025. case Attribute::SwiftSelf: return 1ULL << 51;
  1026. case Attribute::SwiftError: return 1ULL << 52;
  1027. case Attribute::WriteOnly: return 1ULL << 53;
  1028. case Attribute::Speculatable: return 1ULL << 54;
  1029. case Attribute::StrictFP: return 1ULL << 55;
  1030. case Attribute::SanitizeHWAddress: return 1ULL << 56;
  1031. case Attribute::NoCfCheck: return 1ULL << 57;
  1032. case Attribute::OptForFuzzing: return 1ULL << 58;
  1033. case Attribute::ShadowCallStack: return 1ULL << 59;
  1034. case Attribute::SpeculativeLoadHardening:
  1035. return 1ULL << 60;
  1036. case Attribute::ImmArg:
  1037. return 1ULL << 61;
  1038. case Attribute::Dereferenceable:
  1039. llvm_unreachable("dereferenceable attribute not supported in raw format");
  1040. break;
  1041. case Attribute::DereferenceableOrNull:
  1042. llvm_unreachable("dereferenceable_or_null attribute not supported in raw "
  1043. "format");
  1044. break;
  1045. case Attribute::ArgMemOnly:
  1046. llvm_unreachable("argmemonly attribute not supported in raw format");
  1047. break;
  1048. case Attribute::AllocSize:
  1049. llvm_unreachable("allocsize not supported in raw format");
  1050. break;
  1051. }
  1052. llvm_unreachable("Unsupported attribute type");
  1053. }
  1054. static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) {
  1055. if (!Val) return;
  1056. for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
  1057. I = Attribute::AttrKind(I + 1)) {
  1058. if (I == Attribute::Dereferenceable ||
  1059. I == Attribute::DereferenceableOrNull ||
  1060. I == Attribute::ArgMemOnly ||
  1061. I == Attribute::AllocSize)
  1062. continue;
  1063. if (uint64_t A = (Val & getRawAttributeMask(I))) {
  1064. if (I == Attribute::Alignment)
  1065. B.addAlignmentAttr(1ULL << ((A >> 16) - 1));
  1066. else if (I == Attribute::StackAlignment)
  1067. B.addStackAlignmentAttr(1ULL << ((A >> 26)-1));
  1068. else
  1069. B.addAttribute(I);
  1070. }
  1071. }
  1072. }
  1073. /// This fills an AttrBuilder object with the LLVM attributes that have
  1074. /// been decoded from the given integer. This function must stay in sync with
  1075. /// 'encodeLLVMAttributesForBitcode'.
  1076. static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
  1077. uint64_t EncodedAttrs) {
  1078. // FIXME: Remove in 4.0.
  1079. // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
  1080. // the bits above 31 down by 11 bits.
  1081. unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
  1082. assert((!Alignment || isPowerOf2_32(Alignment)) &&
  1083. "Alignment must be a power of two.");
  1084. if (Alignment)
  1085. B.addAlignmentAttr(Alignment);
  1086. addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
  1087. (EncodedAttrs & 0xffff));
  1088. }
  1089. Error BitcodeReader::parseAttributeBlock() {
  1090. if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
  1091. return error("Invalid record");
  1092. if (!MAttributes.empty())
  1093. return error("Invalid multiple blocks");
  1094. SmallVector<uint64_t, 64> Record;
  1095. SmallVector<AttributeList, 8> Attrs;
  1096. // Read all the records.
  1097. while (true) {
  1098. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  1099. switch (Entry.Kind) {
  1100. case BitstreamEntry::SubBlock: // Handled for us already.
  1101. case BitstreamEntry::Error:
  1102. return error("Malformed block");
  1103. case BitstreamEntry::EndBlock:
  1104. return Error::success();
  1105. case BitstreamEntry::Record:
  1106. // The interesting case.
  1107. break;
  1108. }
  1109. // Read a record.
  1110. Record.clear();
  1111. switch (Stream.readRecord(Entry.ID, Record)) {
  1112. default: // Default behavior: ignore.
  1113. break;
  1114. case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...]
  1115. // FIXME: Remove in 4.0.
  1116. if (Record.size() & 1)
  1117. return error("Invalid record");
  1118. for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
  1119. AttrBuilder B;
  1120. decodeLLVMAttributesForBitcode(B, Record[i+1]);
  1121. Attrs.push_back(AttributeList::get(Context, Record[i], B));
  1122. }
  1123. MAttributes.push_back(AttributeList::get(Context, Attrs));
  1124. Attrs.clear();
  1125. break;
  1126. case bitc::PARAMATTR_CODE_ENTRY: // ENTRY: [attrgrp0, attrgrp1, ...]
  1127. for (unsigned i = 0, e = Record.size(); i != e; ++i)
  1128. Attrs.push_back(MAttributeGroups[Record[i]]);
  1129. MAttributes.push_back(AttributeList::get(Context, Attrs));
  1130. Attrs.clear();
  1131. break;
  1132. }
  1133. }
  1134. }
  1135. // Returns Attribute::None on unrecognized codes.
  1136. static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
  1137. switch (Code) {
  1138. default:
  1139. return Attribute::None;
  1140. case bitc::ATTR_KIND_ALIGNMENT:
  1141. return Attribute::Alignment;
  1142. case bitc::ATTR_KIND_ALWAYS_INLINE:
  1143. return Attribute::AlwaysInline;
  1144. case bitc::ATTR_KIND_ARGMEMONLY:
  1145. return Attribute::ArgMemOnly;
  1146. case bitc::ATTR_KIND_BUILTIN:
  1147. return Attribute::Builtin;
  1148. case bitc::ATTR_KIND_BY_VAL:
  1149. return Attribute::ByVal;
  1150. case bitc::ATTR_KIND_IN_ALLOCA:
  1151. return Attribute::InAlloca;
  1152. case bitc::ATTR_KIND_COLD:
  1153. return Attribute::Cold;
  1154. case bitc::ATTR_KIND_CONVERGENT:
  1155. return Attribute::Convergent;
  1156. case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
  1157. return Attribute::InaccessibleMemOnly;
  1158. case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
  1159. return Attribute::InaccessibleMemOrArgMemOnly;
  1160. case bitc::ATTR_KIND_INLINE_HINT:
  1161. return Attribute::InlineHint;
  1162. case bitc::ATTR_KIND_IN_REG:
  1163. return Attribute::InReg;
  1164. case bitc::ATTR_KIND_JUMP_TABLE:
  1165. return Attribute::JumpTable;
  1166. case bitc::ATTR_KIND_MIN_SIZE:
  1167. return Attribute::MinSize;
  1168. case bitc::ATTR_KIND_NAKED:
  1169. return Attribute::Naked;
  1170. case bitc::ATTR_KIND_NEST:
  1171. return Attribute::Nest;
  1172. case bitc::ATTR_KIND_NO_ALIAS:
  1173. return Attribute::NoAlias;
  1174. case bitc::ATTR_KIND_NO_BUILTIN:
  1175. return Attribute::NoBuiltin;
  1176. case bitc::ATTR_KIND_NO_CAPTURE:
  1177. return Attribute::NoCapture;
  1178. case bitc::ATTR_KIND_NO_DUPLICATE:
  1179. return Attribute::NoDuplicate;
  1180. case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
  1181. return Attribute::NoImplicitFloat;
  1182. case bitc::ATTR_KIND_NO_INLINE:
  1183. return Attribute::NoInline;
  1184. case bitc::ATTR_KIND_NO_RECURSE:
  1185. return Attribute::NoRecurse;
  1186. case bitc::ATTR_KIND_NON_LAZY_BIND:
  1187. return Attribute::NonLazyBind;
  1188. case bitc::ATTR_KIND_NON_NULL:
  1189. return Attribute::NonNull;
  1190. case bitc::ATTR_KIND_DEREFERENCEABLE:
  1191. return Attribute::Dereferenceable;
  1192. case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
  1193. return Attribute::DereferenceableOrNull;
  1194. case bitc::ATTR_KIND_ALLOC_SIZE:
  1195. return Attribute::AllocSize;
  1196. case bitc::ATTR_KIND_NO_RED_ZONE:
  1197. return Attribute::NoRedZone;
  1198. case bitc::ATTR_KIND_NO_RETURN:
  1199. return Attribute::NoReturn;
  1200. case bitc::ATTR_KIND_NOCF_CHECK:
  1201. return Attribute::NoCfCheck;
  1202. case bitc::ATTR_KIND_NO_UNWIND:
  1203. return Attribute::NoUnwind;
  1204. case bitc::ATTR_KIND_OPT_FOR_FUZZING:
  1205. return Attribute::OptForFuzzing;
  1206. case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
  1207. return Attribute::OptimizeForSize;
  1208. case bitc::ATTR_KIND_OPTIMIZE_NONE:
  1209. return Attribute::OptimizeNone;
  1210. case bitc::ATTR_KIND_READ_NONE:
  1211. return Attribute::ReadNone;
  1212. case bitc::ATTR_KIND_READ_ONLY:
  1213. return Attribute::ReadOnly;
  1214. case bitc::ATTR_KIND_RETURNED:
  1215. return Attribute::Returned;
  1216. case bitc::ATTR_KIND_RETURNS_TWICE:
  1217. return Attribute::ReturnsTwice;
  1218. case bitc::ATTR_KIND_S_EXT:
  1219. return Attribute::SExt;
  1220. case bitc::ATTR_KIND_SPECULATABLE:
  1221. return Attribute::Speculatable;
  1222. case bitc::ATTR_KIND_STACK_ALIGNMENT:
  1223. return Attribute::StackAlignment;
  1224. case bitc::ATTR_KIND_STACK_PROTECT:
  1225. return Attribute::StackProtect;
  1226. case bitc::ATTR_KIND_STACK_PROTECT_REQ:
  1227. return Attribute::StackProtectReq;
  1228. case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
  1229. return Attribute::StackProtectStrong;
  1230. case bitc::ATTR_KIND_SAFESTACK:
  1231. return Attribute::SafeStack;
  1232. case bitc::ATTR_KIND_SHADOWCALLSTACK:
  1233. return Attribute::ShadowCallStack;
  1234. case bitc::ATTR_KIND_STRICT_FP:
  1235. return Attribute::StrictFP;
  1236. case bitc::ATTR_KIND_STRUCT_RET:
  1237. return Attribute::StructRet;
  1238. case bitc::ATTR_KIND_SANITIZE_ADDRESS:
  1239. return Attribute::SanitizeAddress;
  1240. case bitc::ATTR_KIND_SANITIZE_HWADDRESS:
  1241. return Attribute::SanitizeHWAddress;
  1242. case bitc::ATTR_KIND_SANITIZE_THREAD:
  1243. return Attribute::SanitizeThread;
  1244. case bitc::ATTR_KIND_SANITIZE_MEMORY:
  1245. return Attribute::SanitizeMemory;
  1246. case bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING:
  1247. return Attribute::SpeculativeLoadHardening;
  1248. case bitc::ATTR_KIND_SWIFT_ERROR:
  1249. return Attribute::SwiftError;
  1250. case bitc::ATTR_KIND_SWIFT_SELF:
  1251. return Attribute::SwiftSelf;
  1252. case bitc::ATTR_KIND_UW_TABLE:
  1253. return Attribute::UWTable;
  1254. case bitc::ATTR_KIND_WRITEONLY:
  1255. return Attribute::WriteOnly;
  1256. case bitc::ATTR_KIND_Z_EXT:
  1257. return Attribute::ZExt;
  1258. case bitc::ATTR_KIND_IMMARG:
  1259. return Attribute::ImmArg;
  1260. }
  1261. }
  1262. Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
  1263. unsigned &Alignment) {
  1264. // Note: Alignment in bitcode files is incremented by 1, so that zero
  1265. // can be used for default alignment.
  1266. if (Exponent > Value::MaxAlignmentExponent + 1)
  1267. return error("Invalid alignment value");
  1268. Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
  1269. return Error::success();
  1270. }
  1271. Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
  1272. *Kind = getAttrFromCode(Code);
  1273. if (*Kind == Attribute::None)
  1274. return error("Unknown attribute kind (" + Twine(Code) + ")");
  1275. return Error::success();
  1276. }
  1277. Error BitcodeReader::parseAttributeGroupBlock() {
  1278. if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
  1279. return error("Invalid record");
  1280. if (!MAttributeGroups.empty())
  1281. return error("Invalid multiple blocks");
  1282. SmallVector<uint64_t, 64> Record;
  1283. // Read all the records.
  1284. while (true) {
  1285. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  1286. switch (Entry.Kind) {
  1287. case BitstreamEntry::SubBlock: // Handled for us already.
  1288. case BitstreamEntry::Error:
  1289. return error("Malformed block");
  1290. case BitstreamEntry::EndBlock:
  1291. return Error::success();
  1292. case BitstreamEntry::Record:
  1293. // The interesting case.
  1294. break;
  1295. }
  1296. // Read a record.
  1297. Record.clear();
  1298. switch (Stream.readRecord(Entry.ID, Record)) {
  1299. default: // Default behavior: ignore.
  1300. break;
  1301. case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
  1302. if (Record.size() < 3)
  1303. return error("Invalid record");
  1304. uint64_t GrpID = Record[0];
  1305. uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
  1306. AttrBuilder B;
  1307. for (unsigned i = 2, e = Record.size(); i != e; ++i) {
  1308. if (Record[i] == 0) { // Enum attribute
  1309. Attribute::AttrKind Kind;
  1310. if (Error Err = parseAttrKind(Record[++i], &Kind))
  1311. return Err;
  1312. B.addAttribute(Kind);
  1313. } else if (Record[i] == 1) { // Integer attribute
  1314. Attribute::AttrKind Kind;
  1315. if (Error Err = parseAttrKind(Record[++i], &Kind))
  1316. return Err;
  1317. if (Kind == Attribute::Alignment)
  1318. B.addAlignmentAttr(Record[++i]);
  1319. else if (Kind == Attribute::StackAlignment)
  1320. B.addStackAlignmentAttr(Record[++i]);
  1321. else if (Kind == Attribute::Dereferenceable)
  1322. B.addDereferenceableAttr(Record[++i]);
  1323. else if (Kind == Attribute::DereferenceableOrNull)
  1324. B.addDereferenceableOrNullAttr(Record[++i]);
  1325. else if (Kind == Attribute::AllocSize)
  1326. B.addAllocSizeAttrFromRawRepr(Record[++i]);
  1327. } else { // String attribute
  1328. assert((Record[i] == 3 || Record[i] == 4) &&
  1329. "Invalid attribute group entry");
  1330. bool HasValue = (Record[i++] == 4);
  1331. SmallString<64> KindStr;
  1332. SmallString<64> ValStr;
  1333. while (Record[i] != 0 && i != e)
  1334. KindStr += Record[i++];
  1335. assert(Record[i] == 0 && "Kind string not null terminated");
  1336. if (HasValue) {
  1337. // Has a value associated with it.
  1338. ++i; // Skip the '0' that terminates the "kind" string.
  1339. while (Record[i] != 0 && i != e)
  1340. ValStr += Record[i++];
  1341. assert(Record[i] == 0 && "Value string not null terminated");
  1342. }
  1343. B.addAttribute(KindStr.str(), ValStr.str());
  1344. }
  1345. }
  1346. MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B);
  1347. break;
  1348. }
  1349. }
  1350. }
  1351. }
  1352. Error BitcodeReader::parseTypeTable() {
  1353. if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
  1354. return error("Invalid record");
  1355. return parseTypeTableBody();
  1356. }
  1357. Error BitcodeReader::parseTypeTableBody() {
  1358. if (!TypeList.empty())
  1359. return error("Invalid multiple blocks");
  1360. SmallVector<uint64_t, 64> Record;
  1361. unsigned NumRecords = 0;
  1362. SmallString<64> TypeName;
  1363. // Read all the records for this type table.
  1364. while (true) {
  1365. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  1366. switch (Entry.Kind) {
  1367. case BitstreamEntry::SubBlock: // Handled for us already.
  1368. case BitstreamEntry::Error:
  1369. return error("Malformed block");
  1370. case BitstreamEntry::EndBlock:
  1371. if (NumRecords != TypeList.size())
  1372. return error("Malformed block");
  1373. return Error::success();
  1374. case BitstreamEntry::Record:
  1375. // The interesting case.
  1376. break;
  1377. }
  1378. // Read a record.
  1379. Record.clear();
  1380. Type *ResultTy = nullptr;
  1381. switch (Stream.readRecord(Entry.ID, Record)) {
  1382. default:
  1383. return error("Invalid value");
  1384. case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
  1385. // TYPE_CODE_NUMENTRY contains a count of the number of types in the
  1386. // type list. This allows us to reserve space.
  1387. if (Record.size() < 1)
  1388. return error("Invalid record");
  1389. TypeList.resize(Record[0]);
  1390. continue;
  1391. case bitc::TYPE_CODE_VOID: // VOID
  1392. ResultTy = Type::getVoidTy(Context);
  1393. break;
  1394. case bitc::TYPE_CODE_HALF: // HALF
  1395. ResultTy = Type::getHalfTy(Context);
  1396. break;
  1397. case bitc::TYPE_CODE_FLOAT: // FLOAT
  1398. ResultTy = Type::getFloatTy(Context);
  1399. break;
  1400. case bitc::TYPE_CODE_DOUBLE: // DOUBLE
  1401. ResultTy = Type::getDoubleTy(Context);
  1402. break;
  1403. case bitc::TYPE_CODE_X86_FP80: // X86_FP80
  1404. ResultTy = Type::getX86_FP80Ty(Context);
  1405. break;
  1406. case bitc::TYPE_CODE_FP128: // FP128
  1407. ResultTy = Type::getFP128Ty(Context);
  1408. break;
  1409. case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
  1410. ResultTy = Type::getPPC_FP128Ty(Context);
  1411. break;
  1412. case bitc::TYPE_CODE_LABEL: // LABEL
  1413. ResultTy = Type::getLabelTy(Context);
  1414. break;
  1415. case bitc::TYPE_CODE_METADATA: // METADATA
  1416. ResultTy = Type::getMetadataTy(Context);
  1417. break;
  1418. case bitc::TYPE_CODE_X86_MMX: // X86_MMX
  1419. ResultTy = Type::getX86_MMXTy(Context);
  1420. break;
  1421. case bitc::TYPE_CODE_TOKEN: // TOKEN
  1422. ResultTy = Type::getTokenTy(Context);
  1423. break;
  1424. case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
  1425. if (Record.size() < 1)
  1426. return error("Invalid record");
  1427. uint64_t NumBits = Record[0];
  1428. if (NumBits < IntegerType::MIN_INT_BITS ||
  1429. NumBits > IntegerType::MAX_INT_BITS)
  1430. return error("Bitwidth for integer type out of range");
  1431. ResultTy = IntegerType::get(Context, NumBits);
  1432. break;
  1433. }
  1434. case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
  1435. // [pointee type, address space]
  1436. if (Record.size() < 1)
  1437. return error("Invalid record");
  1438. unsigned AddressSpace = 0;
  1439. if (Record.size() == 2)
  1440. AddressSpace = Record[1];
  1441. ResultTy = getTypeByID(Record[0]);
  1442. if (!ResultTy ||
  1443. !PointerType::isValidElementType(ResultTy))
  1444. return error("Invalid type");
  1445. ResultTy = PointerType::get(ResultTy, AddressSpace);
  1446. break;
  1447. }
  1448. case bitc::TYPE_CODE_FUNCTION_OLD: {
  1449. // FIXME: attrid is dead, remove it in LLVM 4.0
  1450. // FUNCTION: [vararg, attrid, retty, paramty x N]
  1451. if (Record.size() < 3)
  1452. return error("Invalid record");
  1453. SmallVector<Type*, 8> ArgTys;
  1454. for (unsigned i = 3, e = Record.size(); i != e; ++i) {
  1455. if (Type *T = getTypeByID(Record[i]))
  1456. ArgTys.push_back(T);
  1457. else
  1458. break;
  1459. }
  1460. ResultTy = getTypeByID(Record[2]);
  1461. if (!ResultTy || ArgTys.size() < Record.size()-3)
  1462. return error("Invalid type");
  1463. ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
  1464. break;
  1465. }
  1466. case bitc::TYPE_CODE_FUNCTION: {
  1467. // FUNCTION: [vararg, retty, paramty x N]
  1468. if (Record.size() < 2)
  1469. return error("Invalid record");
  1470. SmallVector<Type*, 8> ArgTys;
  1471. for (unsigned i = 2, e = Record.size(); i != e; ++i) {
  1472. if (Type *T = getTypeByID(Record[i])) {
  1473. if (!FunctionType::isValidArgumentType(T))
  1474. return error("Invalid function argument type");
  1475. ArgTys.push_back(T);
  1476. }
  1477. else
  1478. break;
  1479. }
  1480. ResultTy = getTypeByID(Record[1]);
  1481. if (!ResultTy || ArgTys.size() < Record.size()-2)
  1482. return error("Invalid type");
  1483. ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
  1484. break;
  1485. }
  1486. case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
  1487. if (Record.size() < 1)
  1488. return error("Invalid record");
  1489. SmallVector<Type*, 8> EltTys;
  1490. for (unsigned i = 1, e = Record.size(); i != e; ++i) {
  1491. if (Type *T = getTypeByID(Record[i]))
  1492. EltTys.push_back(T);
  1493. else
  1494. break;
  1495. }
  1496. if (EltTys.size() != Record.size()-1)
  1497. return error("Invalid type");
  1498. ResultTy = StructType::get(Context, EltTys, Record[0]);
  1499. break;
  1500. }
  1501. case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
  1502. if (convertToString(Record, 0, TypeName))
  1503. return error("Invalid record");
  1504. continue;
  1505. case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
  1506. if (Record.size() < 1)
  1507. return error("Invalid record");
  1508. if (NumRecords >= TypeList.size())
  1509. return error("Invalid TYPE table");
  1510. // Check to see if this was forward referenced, if so fill in the temp.
  1511. StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
  1512. if (Res) {
  1513. Res->setName(TypeName);
  1514. TypeList[NumRecords] = nullptr;
  1515. } else // Otherwise, create a new struct.
  1516. Res = createIdentifiedStructType(Context, TypeName);
  1517. TypeName.clear();
  1518. SmallVector<Type*, 8> EltTys;
  1519. for (unsigned i = 1, e = Record.size(); i != e; ++i) {
  1520. if (Type *T = getTypeByID(Record[i]))
  1521. EltTys.push_back(T);
  1522. else
  1523. break;
  1524. }
  1525. if (EltTys.size() != Record.size()-1)
  1526. return error("Invalid record");
  1527. Res->setBody(EltTys, Record[0]);
  1528. ResultTy = Res;
  1529. break;
  1530. }
  1531. case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
  1532. if (Record.size() != 1)
  1533. return error("Invalid record");
  1534. if (NumRecords >= TypeList.size())
  1535. return error("Invalid TYPE table");
  1536. // Check to see if this was forward referenced, if so fill in the temp.
  1537. StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
  1538. if (Res) {
  1539. Res->setName(TypeName);
  1540. TypeList[NumRecords] = nullptr;
  1541. } else // Otherwise, create a new struct with no body.
  1542. Res = createIdentifiedStructType(Context, TypeName);
  1543. TypeName.clear();
  1544. ResultTy = Res;
  1545. break;
  1546. }
  1547. case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
  1548. if (Record.size() < 2)
  1549. return error("Invalid record");
  1550. ResultTy = getTypeByID(Record[1]);
  1551. if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
  1552. return error("Invalid type");
  1553. ResultTy = ArrayType::get(ResultTy, Record[0]);
  1554. break;
  1555. case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
  1556. if (Record.size() < 2)
  1557. return error("Invalid record");
  1558. if (Record[0] == 0)
  1559. return error("Invalid vector length");
  1560. ResultTy = getTypeByID(Record[1]);
  1561. if (!ResultTy || !StructType::isValidElementType(ResultTy))
  1562. return error("Invalid type");
  1563. ResultTy = VectorType::get(ResultTy, Record[0]);
  1564. break;
  1565. }
  1566. if (NumRecords >= TypeList.size())
  1567. return error("Invalid TYPE table");
  1568. if (TypeList[NumRecords])
  1569. return error(
  1570. "Invalid TYPE table: Only named structs can be forward referenced");
  1571. assert(ResultTy && "Didn't read a type?");
  1572. TypeList[NumRecords++] = ResultTy;
  1573. }
  1574. }
  1575. Error BitcodeReader::parseOperandBundleTags() {
  1576. if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
  1577. return error("Invalid record");
  1578. if (!BundleTags.empty())
  1579. return error("Invalid multiple blocks");
  1580. SmallVector<uint64_t, 64> Record;
  1581. while (true) {
  1582. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  1583. switch (Entry.Kind) {
  1584. case BitstreamEntry::SubBlock: // Handled for us already.
  1585. case BitstreamEntry::Error:
  1586. return error("Malformed block");
  1587. case BitstreamEntry::EndBlock:
  1588. return Error::success();
  1589. case BitstreamEntry::Record:
  1590. // The interesting case.
  1591. break;
  1592. }
  1593. // Tags are implicitly mapped to integers by their order.
  1594. if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
  1595. return error("Invalid record");
  1596. // OPERAND_BUNDLE_TAG: [strchr x N]
  1597. BundleTags.emplace_back();
  1598. if (convertToString(Record, 0, BundleTags.back()))
  1599. return error("Invalid record");
  1600. Record.clear();
  1601. }
  1602. }
  1603. Error BitcodeReader::parseSyncScopeNames() {
  1604. if (Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID))
  1605. return error("Invalid record");
  1606. if (!SSIDs.empty())
  1607. return error("Invalid multiple synchronization scope names blocks");
  1608. SmallVector<uint64_t, 64> Record;
  1609. while (true) {
  1610. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  1611. switch (Entry.Kind) {
  1612. case BitstreamEntry::SubBlock: // Handled for us already.
  1613. case BitstreamEntry::Error:
  1614. return error("Malformed block");
  1615. case BitstreamEntry::EndBlock:
  1616. if (SSIDs.empty())
  1617. return error("Invalid empty synchronization scope names block");
  1618. return Error::success();
  1619. case BitstreamEntry::Record:
  1620. // The interesting case.
  1621. break;
  1622. }
  1623. // Synchronization scope names are implicitly mapped to synchronization
  1624. // scope IDs by their order.
  1625. if (Stream.readRecord(Entry.ID, Record) != bitc::SYNC_SCOPE_NAME)
  1626. return error("Invalid record");
  1627. SmallString<16> SSN;
  1628. if (convertToString(Record, 0, SSN))
  1629. return error("Invalid record");
  1630. SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN));
  1631. Record.clear();
  1632. }
  1633. }
  1634. /// Associate a value with its name from the given index in the provided record.
  1635. Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
  1636. unsigned NameIndex, Triple &TT) {
  1637. SmallString<128> ValueName;
  1638. if (convertToString(Record, NameIndex, ValueName))
  1639. return error("Invalid record");
  1640. unsigned ValueID = Record[0];
  1641. if (ValueID >= ValueList.size() || !ValueList[ValueID])
  1642. return error("Invalid record");
  1643. Value *V = ValueList[ValueID];
  1644. StringRef NameStr(ValueName.data(), ValueName.size());
  1645. if (NameStr.find_first_of(0) != StringRef::npos)
  1646. return error("Invalid value name");
  1647. V->setName(NameStr);
  1648. auto *GO = dyn_cast<GlobalObject>(V);
  1649. if (GO) {
  1650. if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
  1651. if (TT.supportsCOMDAT())
  1652. GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
  1653. else
  1654. GO->setComdat(nullptr);
  1655. }
  1656. }
  1657. return V;
  1658. }
  1659. /// Helper to note and return the current location, and jump to the given
  1660. /// offset.
  1661. static uint64_t jumpToValueSymbolTable(uint64_t Offset,
  1662. BitstreamCursor &Stream) {
  1663. // Save the current parsing location so we can jump back at the end
  1664. // of the VST read.
  1665. uint64_t CurrentBit = Stream.GetCurrentBitNo();
  1666. Stream.JumpToBit(Offset * 32);
  1667. #ifndef NDEBUG
  1668. // Do some checking if we are in debug mode.
  1669. BitstreamEntry Entry = Stream.advance();
  1670. assert(Entry.Kind == BitstreamEntry::SubBlock);
  1671. assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
  1672. #else
  1673. // In NDEBUG mode ignore the output so we don't get an unused variable
  1674. // warning.
  1675. Stream.advance();
  1676. #endif
  1677. return CurrentBit;
  1678. }
  1679. void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,
  1680. Function *F,
  1681. ArrayRef<uint64_t> Record) {
  1682. // Note that we subtract 1 here because the offset is relative to one word
  1683. // before the start of the identification or module block, which was
  1684. // historically always the start of the regular bitcode header.
  1685. uint64_t FuncWordOffset = Record[1] - 1;
  1686. uint64_t FuncBitOffset = FuncWordOffset * 32;
  1687. DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
  1688. // Set the LastFunctionBlockBit to point to the last function block.
  1689. // Later when parsing is resumed after function materialization,
  1690. // we can simply skip that last function block.
  1691. if (FuncBitOffset > LastFunctionBlockBit)
  1692. LastFunctionBlockBit = FuncBitOffset;
  1693. }
  1694. /// Read a new-style GlobalValue symbol table.
  1695. Error BitcodeReader::parseGlobalValueSymbolTable() {
  1696. unsigned FuncBitcodeOffsetDelta =
  1697. Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
  1698. if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
  1699. return error("Invalid record");
  1700. SmallVector<uint64_t, 64> Record;
  1701. while (true) {
  1702. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  1703. switch (Entry.Kind) {
  1704. case BitstreamEntry::SubBlock:
  1705. case BitstreamEntry::Error:
  1706. return error("Malformed block");
  1707. case BitstreamEntry::EndBlock:
  1708. return Error::success();
  1709. case BitstreamEntry::Record:
  1710. break;
  1711. }
  1712. Record.clear();
  1713. switch (Stream.readRecord(Entry.ID, Record)) {
  1714. case bitc::VST_CODE_FNENTRY: // [valueid, offset]
  1715. setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
  1716. cast<Function>(ValueList[Record[0]]), Record);
  1717. break;
  1718. }
  1719. }
  1720. }
  1721. /// Parse the value symbol table at either the current parsing location or
  1722. /// at the given bit offset if provided.
  1723. Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
  1724. uint64_t CurrentBit;
  1725. // Pass in the Offset to distinguish between calling for the module-level
  1726. // VST (where we want to jump to the VST offset) and the function-level
  1727. // VST (where we don't).
  1728. if (Offset > 0) {
  1729. CurrentBit = jumpToValueSymbolTable(Offset, Stream);
  1730. // If this module uses a string table, read this as a module-level VST.
  1731. if (UseStrtab) {
  1732. if (Error Err = parseGlobalValueSymbolTable())
  1733. return Err;
  1734. Stream.JumpToBit(CurrentBit);
  1735. return Error::success();
  1736. }
  1737. // Otherwise, the VST will be in a similar format to a function-level VST,
  1738. // and will contain symbol names.
  1739. }
  1740. // Compute the delta between the bitcode indices in the VST (the word offset
  1741. // to the word-aligned ENTER_SUBBLOCK for the function block, and that
  1742. // expected by the lazy reader. The reader's EnterSubBlock expects to have
  1743. // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
  1744. // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
  1745. // just before entering the VST subblock because: 1) the EnterSubBlock
  1746. // changes the AbbrevID width; 2) the VST block is nested within the same
  1747. // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
  1748. // AbbrevID width before calling EnterSubBlock; and 3) when we want to
  1749. // jump to the FUNCTION_BLOCK using this offset later, we don't want
  1750. // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
  1751. unsigned FuncBitcodeOffsetDelta =
  1752. Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
  1753. if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
  1754. return error("Invalid record");
  1755. SmallVector<uint64_t, 64> Record;
  1756. Triple TT(TheModule->getTargetTriple());
  1757. // Read all the records for this value table.
  1758. SmallString<128> ValueName;
  1759. while (true) {
  1760. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  1761. switch (Entry.Kind) {
  1762. case BitstreamEntry::SubBlock: // Handled for us already.
  1763. case BitstreamEntry::Error:
  1764. return error("Malformed block");
  1765. case BitstreamEntry::EndBlock:
  1766. if (Offset > 0)
  1767. Stream.JumpToBit(CurrentBit);
  1768. return Error::success();
  1769. case BitstreamEntry::Record:
  1770. // The interesting case.
  1771. break;
  1772. }
  1773. // Read a record.
  1774. Record.clear();
  1775. switch (Stream.readRecord(Entry.ID, Record)) {
  1776. default: // Default behavior: unknown type.
  1777. break;
  1778. case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
  1779. Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
  1780. if (Error Err = ValOrErr.takeError())
  1781. return Err;
  1782. ValOrErr.get();
  1783. break;
  1784. }
  1785. case bitc::VST_CODE_FNENTRY: {
  1786. // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
  1787. Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
  1788. if (Error Err = ValOrErr.takeError())
  1789. return Err;
  1790. Value *V = ValOrErr.get();
  1791. // Ignore function offsets emitted for aliases of functions in older
  1792. // versions of LLVM.
  1793. if (auto *F = dyn_cast<Function>(V))
  1794. setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);
  1795. break;
  1796. }
  1797. case bitc::VST_CODE_BBENTRY: {
  1798. if (convertToString(Record, 1, ValueName))
  1799. return error("Invalid record");
  1800. BasicBlock *BB = getBasicBlock(Record[0]);
  1801. if (!BB)
  1802. return error("Invalid record");
  1803. BB->setName(StringRef(ValueName.data(), ValueName.size()));
  1804. ValueName.clear();
  1805. break;
  1806. }
  1807. }
  1808. }
  1809. }
  1810. /// Decode a signed value stored with the sign bit in the LSB for dense VBR
  1811. /// encoding.
  1812. uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
  1813. if ((V & 1) == 0)
  1814. return V >> 1;
  1815. if (V != 1)
  1816. return -(V >> 1);
  1817. // There is no such thing as -0 with integers. "-0" really means MININT.
  1818. return 1ULL << 63;
  1819. }
  1820. /// Resolve all of the initializers for global values and aliases that we can.
  1821. Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
  1822. std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
  1823. std::vector<std::pair<GlobalIndirectSymbol *, unsigned>>
  1824. IndirectSymbolInitWorklist;
  1825. std::vector<std::pair<Function *, unsigned>> FunctionPrefixWorklist;
  1826. std::vector<std::pair<Function *, unsigned>> FunctionPrologueWorklist;
  1827. std::vector<std::pair<Function *, unsigned>> FunctionPersonalityFnWorklist;
  1828. GlobalInitWorklist.swap(GlobalInits);
  1829. IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
  1830. FunctionPrefixWorklist.swap(FunctionPrefixes);
  1831. FunctionPrologueWorklist.swap(FunctionPrologues);
  1832. FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
  1833. while (!GlobalInitWorklist.empty()) {
  1834. unsigned ValID = GlobalInitWorklist.back().second;
  1835. if (ValID >= ValueList.size()) {
  1836. // Not ready to resolve this yet, it requires something later in the file.
  1837. GlobalInits.push_back(GlobalInitWorklist.back());
  1838. } else {
  1839. if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
  1840. GlobalInitWorklist.back().first->setInitializer(C);
  1841. else
  1842. return error("Expected a constant");
  1843. }
  1844. GlobalInitWorklist.pop_back();
  1845. }
  1846. while (!IndirectSymbolInitWorklist.empty()) {
  1847. unsigned ValID = IndirectSymbolInitWorklist.back().second;
  1848. if (ValID >= ValueList.size()) {
  1849. IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
  1850. } else {
  1851. Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
  1852. if (!C)
  1853. return error("Expected a constant");
  1854. GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first;
  1855. if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType())
  1856. return error("Alias and aliasee types don't match");
  1857. GIS->setIndirectSymbol(C);
  1858. }
  1859. IndirectSymbolInitWorklist.pop_back();
  1860. }
  1861. while (!FunctionPrefixWorklist.empty()) {
  1862. unsigned ValID = FunctionPrefixWorklist.back().second;
  1863. if (ValID >= ValueList.size()) {
  1864. FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
  1865. } else {
  1866. if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
  1867. FunctionPrefixWorklist.back().first->setPrefixData(C);
  1868. else
  1869. return error("Expected a constant");
  1870. }
  1871. FunctionPrefixWorklist.pop_back();
  1872. }
  1873. while (!FunctionPrologueWorklist.empty()) {
  1874. unsigned ValID = FunctionPrologueWorklist.back().second;
  1875. if (ValID >= ValueList.size()) {
  1876. FunctionPrologues.push_back(FunctionPrologueWorklist.back());
  1877. } else {
  1878. if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
  1879. FunctionPrologueWorklist.back().first->setPrologueData(C);
  1880. else
  1881. return error("Expected a constant");
  1882. }
  1883. FunctionPrologueWorklist.pop_back();
  1884. }
  1885. while (!FunctionPersonalityFnWorklist.empty()) {
  1886. unsigned ValID = FunctionPersonalityFnWorklist.back().second;
  1887. if (ValID >= ValueList.size()) {
  1888. FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
  1889. } else {
  1890. if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
  1891. FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
  1892. else
  1893. return error("Expected a constant");
  1894. }
  1895. FunctionPersonalityFnWorklist.pop_back();
  1896. }
  1897. return Error::success();
  1898. }
  1899. static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
  1900. SmallVector<uint64_t, 8> Words(Vals.size());
  1901. transform(Vals, Words.begin(),
  1902. BitcodeReader::decodeSignRotatedValue);
  1903. return APInt(TypeBits, Words);
  1904. }
  1905. Error BitcodeReader::parseConstants() {
  1906. if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
  1907. return error("Invalid record");
  1908. SmallVector<uint64_t, 64> Record;
  1909. // Read all the records for this value table.
  1910. Type *CurTy = Type::getInt32Ty(Context);
  1911. unsigned NextCstNo = ValueList.size();
  1912. while (true) {
  1913. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  1914. switch (Entry.Kind) {
  1915. case BitstreamEntry::SubBlock: // Handled for us already.
  1916. case BitstreamEntry::Error:
  1917. return error("Malformed block");
  1918. case BitstreamEntry::EndBlock:
  1919. if (NextCstNo != ValueList.size())
  1920. return error("Invalid constant reference");
  1921. // Once all the constants have been read, go through and resolve forward
  1922. // references.
  1923. ValueList.resolveConstantForwardRefs();
  1924. return Error::success();
  1925. case BitstreamEntry::Record:
  1926. // The interesting case.
  1927. break;
  1928. }
  1929. // Read a record.
  1930. Record.clear();
  1931. Type *VoidType = Type::getVoidTy(Context);
  1932. Value *V = nullptr;
  1933. unsigned BitCode = Stream.readRecord(Entry.ID, Record);
  1934. switch (BitCode) {
  1935. default: // Default behavior: unknown constant
  1936. case bitc::CST_CODE_UNDEF: // UNDEF
  1937. V = UndefValue::get(CurTy);
  1938. break;
  1939. case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
  1940. if (Record.empty())
  1941. return error("Invalid record");
  1942. if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
  1943. return error("Invalid record");
  1944. if (TypeList[Record[0]] == VoidType)
  1945. return error("Invalid constant type");
  1946. CurTy = TypeList[Record[0]];
  1947. continue; // Skip the ValueList manipulation.
  1948. case bitc::CST_CODE_NULL: // NULL
  1949. V = Constant::getNullValue(CurTy);
  1950. break;
  1951. case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
  1952. if (!CurTy->isIntegerTy() || Record.empty())
  1953. return error("Invalid record");
  1954. V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
  1955. break;
  1956. case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
  1957. if (!CurTy->isIntegerTy() || Record.empty())
  1958. return error("Invalid record");
  1959. APInt VInt =
  1960. readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
  1961. V = ConstantInt::get(Context, VInt);
  1962. break;
  1963. }
  1964. case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
  1965. if (Record.empty())
  1966. return error("Invalid record");
  1967. if (CurTy->isHalfTy())
  1968. V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(),
  1969. APInt(16, (uint16_t)Record[0])));
  1970. else if (CurTy->isFloatTy())
  1971. V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(),
  1972. APInt(32, (uint32_t)Record[0])));
  1973. else if (CurTy->isDoubleTy())
  1974. V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(),
  1975. APInt(64, Record[0])));
  1976. else if (CurTy->isX86_FP80Ty()) {
  1977. // Bits are not stored the same way as a normal i80 APInt, compensate.
  1978. uint64_t Rearrange[2];
  1979. Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
  1980. Rearrange[1] = Record[0] >> 48;
  1981. V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(),
  1982. APInt(80, Rearrange)));
  1983. } else if (CurTy->isFP128Ty())
  1984. V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(),
  1985. APInt(128, Record)));
  1986. else if (CurTy->isPPC_FP128Ty())
  1987. V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(),
  1988. APInt(128, Record)));
  1989. else
  1990. V = UndefValue::get(CurTy);
  1991. break;
  1992. }
  1993. case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
  1994. if (Record.empty())
  1995. return error("Invalid record");
  1996. unsigned Size = Record.size();
  1997. SmallVector<Constant*, 16> Elts;
  1998. if (StructType *STy = dyn_cast<StructType>(CurTy)) {
  1999. for (unsigned i = 0; i != Size; ++i)
  2000. Elts.push_back(ValueList.getConstantFwdRef(Record[i],
  2001. STy->getElementType(i)));
  2002. V = ConstantStruct::get(STy, Elts);
  2003. } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
  2004. Type *EltTy = ATy->getElementType();
  2005. for (unsigned i = 0; i != Size; ++i)
  2006. Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
  2007. V = ConstantArray::get(ATy, Elts);
  2008. } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
  2009. Type *EltTy = VTy->getElementType();
  2010. for (unsigned i = 0; i != Size; ++i)
  2011. Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
  2012. V = ConstantVector::get(Elts);
  2013. } else {
  2014. V = UndefValue::get(CurTy);
  2015. }
  2016. break;
  2017. }
  2018. case bitc::CST_CODE_STRING: // STRING: [values]
  2019. case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
  2020. if (Record.empty())
  2021. return error("Invalid record");
  2022. SmallString<16> Elts(Record.begin(), Record.end());
  2023. V = ConstantDataArray::getString(Context, Elts,
  2024. BitCode == bitc::CST_CODE_CSTRING);
  2025. break;
  2026. }
  2027. case bitc::CST_CODE_DATA: {// DATA: [n x value]
  2028. if (Record.empty())
  2029. return error("Invalid record");
  2030. Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
  2031. if (EltTy->isIntegerTy(8)) {
  2032. SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
  2033. if (isa<VectorType>(CurTy))
  2034. V = ConstantDataVector::get(Context, Elts);
  2035. else
  2036. V = ConstantDataArray::get(Context, Elts);
  2037. } else if (EltTy->isIntegerTy(16)) {
  2038. SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
  2039. if (isa<VectorType>(CurTy))
  2040. V = ConstantDataVector::get(Context, Elts);
  2041. else
  2042. V = ConstantDataArray::get(Context, Elts);
  2043. } else if (EltTy->isIntegerTy(32)) {
  2044. SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
  2045. if (isa<VectorType>(CurTy))
  2046. V = ConstantDataVector::get(Context, Elts);
  2047. else
  2048. V = ConstantDataArray::get(Context, Elts);
  2049. } else if (EltTy->isIntegerTy(64)) {
  2050. SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
  2051. if (isa<VectorType>(CurTy))
  2052. V = ConstantDataVector::get(Context, Elts);
  2053. else
  2054. V = ConstantDataArray::get(Context, Elts);
  2055. } else if (EltTy->isHalfTy()) {
  2056. SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
  2057. if (isa<VectorType>(CurTy))
  2058. V = ConstantDataVector::getFP(Context, Elts);
  2059. else
  2060. V = ConstantDataArray::getFP(Context, Elts);
  2061. } else if (EltTy->isFloatTy()) {
  2062. SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
  2063. if (isa<VectorType>(CurTy))
  2064. V = ConstantDataVector::getFP(Context, Elts);
  2065. else
  2066. V = ConstantDataArray::getFP(Context, Elts);
  2067. } else if (EltTy->isDoubleTy()) {
  2068. SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
  2069. if (isa<VectorType>(CurTy))
  2070. V = ConstantDataVector::getFP(Context, Elts);
  2071. else
  2072. V = ConstantDataArray::getFP(Context, Elts);
  2073. } else {
  2074. return error("Invalid type for value");
  2075. }
  2076. break;
  2077. }
  2078. case bitc::CST_CODE_CE_UNOP: { // CE_UNOP: [opcode, opval]
  2079. if (Record.size() < 2)
  2080. return error("Invalid record");
  2081. int Opc = getDecodedUnaryOpcode(Record[0], CurTy);
  2082. if (Opc < 0) {
  2083. V = UndefValue::get(CurTy); // Unknown unop.
  2084. } else {
  2085. Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
  2086. unsigned Flags = 0;
  2087. V = ConstantExpr::get(Opc, LHS, Flags);
  2088. }
  2089. break;
  2090. }
  2091. case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
  2092. if (Record.size() < 3)
  2093. return error("Invalid record");
  2094. int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
  2095. if (Opc < 0) {
  2096. V = UndefValue::get(CurTy); // Unknown binop.
  2097. } else {
  2098. Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
  2099. Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
  2100. unsigned Flags = 0;
  2101. if (Record.size() >= 4) {
  2102. if (Opc == Instruction::Add ||
  2103. Opc == Instruction::Sub ||
  2104. Opc == Instruction::Mul ||
  2105. Opc == Instruction::Shl) {
  2106. if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
  2107. Flags |= OverflowingBinaryOperator::NoSignedWrap;
  2108. if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
  2109. Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
  2110. } else if (Opc == Instruction::SDiv ||
  2111. Opc == Instruction::UDiv ||
  2112. Opc == Instruction::LShr ||
  2113. Opc == Instruction::AShr) {
  2114. if (Record[3] & (1 << bitc::PEO_EXACT))
  2115. Flags |= SDivOperator::IsExact;
  2116. }
  2117. }
  2118. V = ConstantExpr::get(Opc, LHS, RHS, Flags);
  2119. }
  2120. break;
  2121. }
  2122. case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
  2123. if (Record.size() < 3)
  2124. return error("Invalid record");
  2125. int Opc = getDecodedCastOpcode(Record[0]);
  2126. if (Opc < 0) {
  2127. V = UndefValue::get(CurTy); // Unknown cast.
  2128. } else {
  2129. Type *OpTy = getTypeByID(Record[1]);
  2130. if (!OpTy)
  2131. return error("Invalid record");
  2132. Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
  2133. V = UpgradeBitCastExpr(Opc, Op, CurTy);
  2134. if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
  2135. }
  2136. break;
  2137. }
  2138. case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
  2139. case bitc::CST_CODE_CE_GEP: // [ty, n x operands]
  2140. case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x
  2141. // operands]
  2142. unsigned OpNum = 0;
  2143. Type *PointeeType = nullptr;
  2144. if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX ||
  2145. Record.size() % 2)
  2146. PointeeType = getTypeByID(Record[OpNum++]);
  2147. bool InBounds = false;
  2148. Optional<unsigned> InRangeIndex;
  2149. if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) {
  2150. uint64_t Op = Record[OpNum++];
  2151. InBounds = Op & 1;
  2152. InRangeIndex = Op >> 1;
  2153. } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
  2154. InBounds = true;
  2155. SmallVector<Constant*, 16> Elts;
  2156. while (OpNum != Record.size()) {
  2157. Type *ElTy = getTypeByID(Record[OpNum++]);
  2158. if (!ElTy)
  2159. return error("Invalid record");
  2160. Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
  2161. }
  2162. if (Elts.size() < 1)
  2163. return error("Invalid gep with no operands");
  2164. Type *ImplicitPointeeType =
  2165. cast<PointerType>(Elts[0]->getType()->getScalarType())
  2166. ->getElementType();
  2167. if (!PointeeType)
  2168. PointeeType = ImplicitPointeeType;
  2169. else if (PointeeType != ImplicitPointeeType)
  2170. return error("Explicit gep operator type does not match pointee type "
  2171. "of pointer operand");
  2172. ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
  2173. V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
  2174. InBounds, InRangeIndex);
  2175. break;
  2176. }
  2177. case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
  2178. if (Record.size() < 3)
  2179. return error("Invalid record");
  2180. Type *SelectorTy = Type::getInt1Ty(Context);
  2181. // The selector might be an i1 or an <n x i1>
  2182. // Get the type from the ValueList before getting a forward ref.
  2183. if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
  2184. if (Value *V = ValueList[Record[0]])
  2185. if (SelectorTy != V->getType())
  2186. SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
  2187. V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
  2188. SelectorTy),
  2189. ValueList.getConstantFwdRef(Record[1],CurTy),
  2190. ValueList.getConstantFwdRef(Record[2],CurTy));
  2191. break;
  2192. }
  2193. case bitc::CST_CODE_CE_EXTRACTELT
  2194. : { // CE_EXTRACTELT: [opty, opval, opty, opval]
  2195. if (Record.size() < 3)
  2196. return error("Invalid record");
  2197. VectorType *OpTy =
  2198. dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
  2199. if (!OpTy)
  2200. return error("Invalid record");
  2201. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  2202. Constant *Op1 = nullptr;
  2203. if (Record.size() == 4) {
  2204. Type *IdxTy = getTypeByID(Record[2]);
  2205. if (!IdxTy)
  2206. return error("Invalid record");
  2207. Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
  2208. } else // TODO: Remove with llvm 4.0
  2209. Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
  2210. if (!Op1)
  2211. return error("Invalid record");
  2212. V = ConstantExpr::getExtractElement(Op0, Op1);
  2213. break;
  2214. }
  2215. case bitc::CST_CODE_CE_INSERTELT
  2216. : { // CE_INSERTELT: [opval, opval, opty, opval]
  2217. VectorType *OpTy = dyn_cast<VectorType>(CurTy);
  2218. if (Record.size() < 3 || !OpTy)
  2219. return error("Invalid record");
  2220. Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
  2221. Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
  2222. OpTy->getElementType());
  2223. Constant *Op2 = nullptr;
  2224. if (Record.size() == 4) {
  2225. Type *IdxTy = getTypeByID(Record[2]);
  2226. if (!IdxTy)
  2227. return error("Invalid record");
  2228. Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
  2229. } else // TODO: Remove with llvm 4.0
  2230. Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
  2231. if (!Op2)
  2232. return error("Invalid record");
  2233. V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
  2234. break;
  2235. }
  2236. case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
  2237. VectorType *OpTy = dyn_cast<VectorType>(CurTy);
  2238. if (Record.size() < 3 || !OpTy)
  2239. return error("Invalid record");
  2240. Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
  2241. Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
  2242. Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
  2243. OpTy->getNumElements());
  2244. Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
  2245. V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
  2246. break;
  2247. }
  2248. case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
  2249. VectorType *RTy = dyn_cast<VectorType>(CurTy);
  2250. VectorType *OpTy =
  2251. dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
  2252. if (Record.size() < 4 || !RTy || !OpTy)
  2253. return error("Invalid record");
  2254. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  2255. Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
  2256. Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
  2257. RTy->getNumElements());
  2258. Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
  2259. V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
  2260. break;
  2261. }
  2262. case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
  2263. if (Record.size() < 4)
  2264. return error("Invalid record");
  2265. Type *OpTy = getTypeByID(Record[0]);
  2266. if (!OpTy)
  2267. return error("Invalid record");
  2268. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  2269. Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
  2270. if (OpTy->isFPOrFPVectorTy())
  2271. V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
  2272. else
  2273. V = ConstantExpr::getICmp(Record[3], Op0, Op1);
  2274. break;
  2275. }
  2276. // This maintains backward compatibility, pre-asm dialect keywords.
  2277. // FIXME: Remove with the 4.0 release.
  2278. case bitc::CST_CODE_INLINEASM_OLD: {
  2279. if (Record.size() < 2)
  2280. return error("Invalid record");
  2281. std::string AsmStr, ConstrStr;
  2282. bool HasSideEffects = Record[0] & 1;
  2283. bool IsAlignStack = Record[0] >> 1;
  2284. unsigned AsmStrSize = Record[1];
  2285. if (2+AsmStrSize >= Record.size())
  2286. return error("Invalid record");
  2287. unsigned ConstStrSize = Record[2+AsmStrSize];
  2288. if (3+AsmStrSize+ConstStrSize > Record.size())
  2289. return error("Invalid record");
  2290. for (unsigned i = 0; i != AsmStrSize; ++i)
  2291. AsmStr += (char)Record[2+i];
  2292. for (unsigned i = 0; i != ConstStrSize; ++i)
  2293. ConstrStr += (char)Record[3+AsmStrSize+i];
  2294. PointerType *PTy = cast<PointerType>(CurTy);
  2295. UpgradeInlineAsmString(&AsmStr);
  2296. V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
  2297. AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
  2298. break;
  2299. }
  2300. // This version adds support for the asm dialect keywords (e.g.,
  2301. // inteldialect).
  2302. case bitc::CST_CODE_INLINEASM: {
  2303. if (Record.size() < 2)
  2304. return error("Invalid record");
  2305. std::string AsmStr, ConstrStr;
  2306. bool HasSideEffects = Record[0] & 1;
  2307. bool IsAlignStack = (Record[0] >> 1) & 1;
  2308. unsigned AsmDialect = Record[0] >> 2;
  2309. unsigned AsmStrSize = Record[1];
  2310. if (2+AsmStrSize >= Record.size())
  2311. return error("Invalid record");
  2312. unsigned ConstStrSize = Record[2+AsmStrSize];
  2313. if (3+AsmStrSize+ConstStrSize > Record.size())
  2314. return error("Invalid record");
  2315. for (unsigned i = 0; i != AsmStrSize; ++i)
  2316. AsmStr += (char)Record[2+i];
  2317. for (unsigned i = 0; i != ConstStrSize; ++i)
  2318. ConstrStr += (char)Record[3+AsmStrSize+i];
  2319. PointerType *PTy = cast<PointerType>(CurTy);
  2320. UpgradeInlineAsmString(&AsmStr);
  2321. V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
  2322. AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
  2323. InlineAsm::AsmDialect(AsmDialect));
  2324. break;
  2325. }
  2326. case bitc::CST_CODE_BLOCKADDRESS:{
  2327. if (Record.size() < 3)
  2328. return error("Invalid record");
  2329. Type *FnTy = getTypeByID(Record[0]);
  2330. if (!FnTy)
  2331. return error("Invalid record");
  2332. Function *Fn =
  2333. dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
  2334. if (!Fn)
  2335. return error("Invalid record");
  2336. // If the function is already parsed we can insert the block address right
  2337. // away.
  2338. BasicBlock *BB;
  2339. unsigned BBID = Record[2];
  2340. if (!BBID)
  2341. // Invalid reference to entry block.
  2342. return error("Invalid ID");
  2343. if (!Fn->empty()) {
  2344. Function::iterator BBI = Fn->begin(), BBE = Fn->end();
  2345. for (size_t I = 0, E = BBID; I != E; ++I) {
  2346. if (BBI == BBE)
  2347. return error("Invalid ID");
  2348. ++BBI;
  2349. }
  2350. BB = &*BBI;
  2351. } else {
  2352. // Otherwise insert a placeholder and remember it so it can be inserted
  2353. // when the function is parsed.
  2354. auto &FwdBBs = BasicBlockFwdRefs[Fn];
  2355. if (FwdBBs.empty())
  2356. BasicBlockFwdRefQueue.push_back(Fn);
  2357. if (FwdBBs.size() < BBID + 1)
  2358. FwdBBs.resize(BBID + 1);
  2359. if (!FwdBBs[BBID])
  2360. FwdBBs[BBID] = BasicBlock::Create(Context);
  2361. BB = FwdBBs[BBID];
  2362. }
  2363. V = BlockAddress::get(Fn, BB);
  2364. break;
  2365. }
  2366. }
  2367. ValueList.assignValue(V, NextCstNo);
  2368. ++NextCstNo;
  2369. }
  2370. }
  2371. Error BitcodeReader::parseUseLists() {
  2372. if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
  2373. return error("Invalid record");
  2374. // Read all the records.
  2375. SmallVector<uint64_t, 64> Record;
  2376. while (true) {
  2377. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  2378. switch (Entry.Kind) {
  2379. case BitstreamEntry::SubBlock: // Handled for us already.
  2380. case BitstreamEntry::Error:
  2381. return error("Malformed block");
  2382. case BitstreamEntry::EndBlock:
  2383. return Error::success();
  2384. case BitstreamEntry::Record:
  2385. // The interesting case.
  2386. break;
  2387. }
  2388. // Read a use list record.
  2389. Record.clear();
  2390. bool IsBB = false;
  2391. switch (Stream.readRecord(Entry.ID, Record)) {
  2392. default: // Default behavior: unknown type.
  2393. break;
  2394. case bitc::USELIST_CODE_BB:
  2395. IsBB = true;
  2396. LLVM_FALLTHROUGH;
  2397. case bitc::USELIST_CODE_DEFAULT: {
  2398. unsigned RecordLength = Record.size();
  2399. if (RecordLength < 3)
  2400. // Records should have at least an ID and two indexes.
  2401. return error("Invalid record");
  2402. unsigned ID = Record.back();
  2403. Record.pop_back();
  2404. Value *V;
  2405. if (IsBB) {
  2406. assert(ID < FunctionBBs.size() && "Basic block not found");
  2407. V = FunctionBBs[ID];
  2408. } else
  2409. V = ValueList[ID];
  2410. unsigned NumUses = 0;
  2411. SmallDenseMap<const Use *, unsigned, 16> Order;
  2412. for (const Use &U : V->materialized_uses()) {
  2413. if (++NumUses > Record.size())
  2414. break;
  2415. Order[&U] = Record[NumUses - 1];
  2416. }
  2417. if (Order.size() != Record.size() || NumUses > Record.size())
  2418. // Mismatches can happen if the functions are being materialized lazily
  2419. // (out-of-order), or a value has been upgraded.
  2420. break;
  2421. V->sortUseList([&](const Use &L, const Use &R) {
  2422. return Order.lookup(&L) < Order.lookup(&R);
  2423. });
  2424. break;
  2425. }
  2426. }
  2427. }
  2428. }
  2429. /// When we see the block for metadata, remember where it is and then skip it.
  2430. /// This lets us lazily deserialize the metadata.
  2431. Error BitcodeReader::rememberAndSkipMetadata() {
  2432. // Save the current stream state.
  2433. uint64_t CurBit = Stream.GetCurrentBitNo();
  2434. DeferredMetadataInfo.push_back(CurBit);
  2435. // Skip over the block for now.
  2436. if (Stream.SkipBlock())
  2437. return error("Invalid record");
  2438. return Error::success();
  2439. }
  2440. Error BitcodeReader::materializeMetadata() {
  2441. for (uint64_t BitPos : DeferredMetadataInfo) {
  2442. // Move the bit stream to the saved position.
  2443. Stream.JumpToBit(BitPos);
  2444. if (Error Err = MDLoader->parseModuleMetadata())
  2445. return Err;
  2446. }
  2447. // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level
  2448. // metadata.
  2449. if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) {
  2450. NamedMDNode *LinkerOpts =
  2451. TheModule->getOrInsertNamedMetadata("llvm.linker.options");
  2452. for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands())
  2453. LinkerOpts->addOperand(cast<MDNode>(MDOptions));
  2454. }
  2455. DeferredMetadataInfo.clear();
  2456. return Error::success();
  2457. }
  2458. void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
  2459. /// When we see the block for a function body, remember where it is and then
  2460. /// skip it. This lets us lazily deserialize the functions.
  2461. Error BitcodeReader::rememberAndSkipFunctionBody() {
  2462. // Get the function we are talking about.
  2463. if (FunctionsWithBodies.empty())
  2464. return error("Insufficient function protos");
  2465. Function *Fn = FunctionsWithBodies.back();
  2466. FunctionsWithBodies.pop_back();
  2467. // Save the current stream state.
  2468. uint64_t CurBit = Stream.GetCurrentBitNo();
  2469. assert(
  2470. (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
  2471. "Mismatch between VST and scanned function offsets");
  2472. DeferredFunctionInfo[Fn] = CurBit;
  2473. // Skip over the function block for now.
  2474. if (Stream.SkipBlock())
  2475. return error("Invalid record");
  2476. return Error::success();
  2477. }
  2478. Error BitcodeReader::globalCleanup() {
  2479. // Patch the initializers for globals and aliases up.
  2480. if (Error Err = resolveGlobalAndIndirectSymbolInits())
  2481. return Err;
  2482. if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
  2483. return error("Malformed global initializer set");
  2484. // Look for intrinsic functions which need to be upgraded at some point
  2485. for (Function &F : *TheModule) {
  2486. MDLoader->upgradeDebugIntrinsics(F);
  2487. Function *NewFn;
  2488. if (UpgradeIntrinsicFunction(&F, NewFn))
  2489. UpgradedIntrinsics[&F] = NewFn;
  2490. else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))
  2491. // Some types could be renamed during loading if several modules are
  2492. // loaded in the same LLVMContext (LTO scenario). In this case we should
  2493. // remangle intrinsics names as well.
  2494. RemangledIntrinsics[&F] = Remangled.getValue();
  2495. }
  2496. // Look for global variables which need to be renamed.
  2497. for (GlobalVariable &GV : TheModule->globals())
  2498. UpgradeGlobalVariable(&GV);
  2499. // Force deallocation of memory for these vectors to favor the client that
  2500. // want lazy deserialization.
  2501. std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits);
  2502. std::vector<std::pair<GlobalIndirectSymbol *, unsigned>>().swap(
  2503. IndirectSymbolInits);
  2504. return Error::success();
  2505. }
  2506. /// Support for lazy parsing of function bodies. This is required if we
  2507. /// either have an old bitcode file without a VST forward declaration record,
  2508. /// or if we have an anonymous function being materialized, since anonymous
  2509. /// functions do not have a name and are therefore not in the VST.
  2510. Error BitcodeReader::rememberAndSkipFunctionBodies() {
  2511. Stream.JumpToBit(NextUnreadBit);
  2512. if (Stream.AtEndOfStream())
  2513. return error("Could not find function in stream");
  2514. if (!SeenFirstFunctionBody)
  2515. return error("Trying to materialize functions before seeing function blocks");
  2516. // An old bitcode file with the symbol table at the end would have
  2517. // finished the parse greedily.
  2518. assert(SeenValueSymbolTable);
  2519. SmallVector<uint64_t, 64> Record;
  2520. while (true) {
  2521. BitstreamEntry Entry = Stream.advance();
  2522. switch (Entry.Kind) {
  2523. default:
  2524. return error("Expect SubBlock");
  2525. case BitstreamEntry::SubBlock:
  2526. switch (Entry.ID) {
  2527. default:
  2528. return error("Expect function block");
  2529. case bitc::FUNCTION_BLOCK_ID:
  2530. if (Error Err = rememberAndSkipFunctionBody())
  2531. return Err;
  2532. NextUnreadBit = Stream.GetCurrentBitNo();
  2533. return Error::success();
  2534. }
  2535. }
  2536. }
  2537. }
  2538. bool BitcodeReaderBase::readBlockInfo() {
  2539. Optional<BitstreamBlockInfo> NewBlockInfo = Stream.ReadBlockInfoBlock();
  2540. if (!NewBlockInfo)
  2541. return true;
  2542. BlockInfo = std::move(*NewBlockInfo);
  2543. return false;
  2544. }
  2545. Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
  2546. // v1: [selection_kind, name]
  2547. // v2: [strtab_offset, strtab_size, selection_kind]
  2548. StringRef Name;
  2549. std::tie(Name, Record) = readNameFromStrtab(Record);
  2550. if (Record.empty())
  2551. return error("Invalid record");
  2552. Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
  2553. std::string OldFormatName;
  2554. if (!UseStrtab) {
  2555. if (Record.size() < 2)
  2556. return error("Invalid record");
  2557. unsigned ComdatNameSize = Record[1];
  2558. OldFormatName.reserve(ComdatNameSize);
  2559. for (unsigned i = 0; i != ComdatNameSize; ++i)
  2560. OldFormatName += (char)Record[2 + i];
  2561. Name = OldFormatName;
  2562. }
  2563. Comdat *C = TheModule->getOrInsertComdat(Name);
  2564. C->setSelectionKind(SK);
  2565. ComdatList.push_back(C);
  2566. return Error::success();
  2567. }
  2568. static void inferDSOLocal(GlobalValue *GV) {
  2569. // infer dso_local from linkage and visibility if it is not encoded.
  2570. if (GV->hasLocalLinkage() ||
  2571. (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()))
  2572. GV->setDSOLocal(true);
  2573. }
  2574. Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
  2575. // v1: [pointer type, isconst, initid, linkage, alignment, section,
  2576. // visibility, threadlocal, unnamed_addr, externally_initialized,
  2577. // dllstorageclass, comdat, attributes, preemption specifier] (name in VST)
  2578. // v2: [strtab_offset, strtab_size, v1]
  2579. StringRef Name;
  2580. std::tie(Name, Record) = readNameFromStrtab(Record);
  2581. if (Record.size() < 6)
  2582. return error("Invalid record");
  2583. Type *Ty = getTypeByID(Record[0]);
  2584. if (!Ty)
  2585. return error("Invalid record");
  2586. bool isConstant = Record[1] & 1;
  2587. bool explicitType = Record[1] & 2;
  2588. unsigned AddressSpace;
  2589. if (explicitType) {
  2590. AddressSpace = Record[1] >> 2;
  2591. } else {
  2592. if (!Ty->isPointerTy())
  2593. return error("Invalid type for value");
  2594. AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
  2595. Ty = cast<PointerType>(Ty)->getElementType();
  2596. }
  2597. uint64_t RawLinkage = Record[3];
  2598. GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
  2599. unsigned Alignment;
  2600. if (Error Err = parseAlignmentValue(Record[4], Alignment))
  2601. return Err;
  2602. std::string Section;
  2603. if (Record[5]) {
  2604. if (Record[5] - 1 >= SectionTable.size())
  2605. return error("Invalid ID");
  2606. Section = SectionTable[Record[5] - 1];
  2607. }
  2608. GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
  2609. // Local linkage must have default visibility.
  2610. if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
  2611. // FIXME: Change to an error if non-default in 4.0.
  2612. Visibility = getDecodedVisibility(Record[6]);
  2613. GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
  2614. if (Record.size() > 7)
  2615. TLM = getDecodedThreadLocalMode(Record[7]);
  2616. GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
  2617. if (Record.size() > 8)
  2618. UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
  2619. bool ExternallyInitialized = false;
  2620. if (Record.size() > 9)
  2621. ExternallyInitialized = Record[9];
  2622. GlobalVariable *NewGV =
  2623. new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name,
  2624. nullptr, TLM, AddressSpace, ExternallyInitialized);
  2625. NewGV->setAlignment(Alignment);
  2626. if (!Section.empty())
  2627. NewGV->setSection(Section);
  2628. NewGV->setVisibility(Visibility);
  2629. NewGV->setUnnamedAddr(UnnamedAddr);
  2630. if (Record.size() > 10)
  2631. NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
  2632. else
  2633. upgradeDLLImportExportLinkage(NewGV, RawLinkage);
  2634. ValueList.push_back(NewGV);
  2635. // Remember which value to use for the global initializer.
  2636. if (unsigned InitID = Record[2])
  2637. GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
  2638. if (Record.size() > 11) {
  2639. if (unsigned ComdatID = Record[11]) {
  2640. if (ComdatID > ComdatList.size())
  2641. return error("Invalid global variable comdat ID");
  2642. NewGV->setComdat(ComdatList[ComdatID - 1]);
  2643. }
  2644. } else if (hasImplicitComdat(RawLinkage)) {
  2645. NewGV->setComdat(reinterpret_cast<Comdat *>(1));
  2646. }
  2647. if (Record.size() > 12) {
  2648. auto AS = getAttributes(Record[12]).getFnAttributes();
  2649. NewGV->setAttributes(AS);
  2650. }
  2651. if (Record.size() > 13) {
  2652. NewGV->setDSOLocal(getDecodedDSOLocal(Record[13]));
  2653. }
  2654. inferDSOLocal(NewGV);
  2655. return Error::success();
  2656. }
  2657. Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
  2658. // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
  2659. // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
  2660. // prefixdata, personalityfn, preemption specifier, addrspace] (name in VST)
  2661. // v2: [strtab_offset, strtab_size, v1]
  2662. StringRef Name;
  2663. std::tie(Name, Record) = readNameFromStrtab(Record);
  2664. if (Record.size() < 8)
  2665. return error("Invalid record");
  2666. Type *Ty = getTypeByID(Record[0]);
  2667. if (!Ty)
  2668. return error("Invalid record");
  2669. if (auto *PTy = dyn_cast<PointerType>(Ty))
  2670. Ty = PTy->getElementType();
  2671. auto *FTy = dyn_cast<FunctionType>(Ty);
  2672. if (!FTy)
  2673. return error("Invalid type for value");
  2674. auto CC = static_cast<CallingConv::ID>(Record[1]);
  2675. if (CC & ~CallingConv::MaxID)
  2676. return error("Invalid calling convention ID");
  2677. unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
  2678. if (Record.size() > 16)
  2679. AddrSpace = Record[16];
  2680. Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
  2681. AddrSpace, Name, TheModule);
  2682. Func->setCallingConv(CC);
  2683. bool isProto = Record[2];
  2684. uint64_t RawLinkage = Record[3];
  2685. Func->setLinkage(getDecodedLinkage(RawLinkage));
  2686. Func->setAttributes(getAttributes(Record[4]));
  2687. unsigned Alignment;
  2688. if (Error Err = parseAlignmentValue(Record[5], Alignment))
  2689. return Err;
  2690. Func->setAlignment(Alignment);
  2691. if (Record[6]) {
  2692. if (Record[6] - 1 >= SectionTable.size())
  2693. return error("Invalid ID");
  2694. Func->setSection(SectionTable[Record[6] - 1]);
  2695. }
  2696. // Local linkage must have default visibility.
  2697. if (!Func->hasLocalLinkage())
  2698. // FIXME: Change to an error if non-default in 4.0.
  2699. Func->setVisibility(getDecodedVisibility(Record[7]));
  2700. if (Record.size() > 8 && Record[8]) {
  2701. if (Record[8] - 1 >= GCTable.size())
  2702. return error("Invalid ID");
  2703. Func->setGC(GCTable[Record[8] - 1]);
  2704. }
  2705. GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
  2706. if (Record.size() > 9)
  2707. UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
  2708. Func->setUnnamedAddr(UnnamedAddr);
  2709. if (Record.size() > 10 && Record[10] != 0)
  2710. FunctionPrologues.push_back(std::make_pair(Func, Record[10] - 1));
  2711. if (Record.size() > 11)
  2712. Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
  2713. else
  2714. upgradeDLLImportExportLinkage(Func, RawLinkage);
  2715. if (Record.size() > 12) {
  2716. if (unsigned ComdatID = Record[12]) {
  2717. if (ComdatID > ComdatList.size())
  2718. return error("Invalid function comdat ID");
  2719. Func->setComdat(ComdatList[ComdatID - 1]);
  2720. }
  2721. } else if (hasImplicitComdat(RawLinkage)) {
  2722. Func->setComdat(reinterpret_cast<Comdat *>(1));
  2723. }
  2724. if (Record.size() > 13 && Record[13] != 0)
  2725. FunctionPrefixes.push_back(std::make_pair(Func, Record[13] - 1));
  2726. if (Record.size() > 14 && Record[14] != 0)
  2727. FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
  2728. if (Record.size() > 15) {
  2729. Func->setDSOLocal(getDecodedDSOLocal(Record[15]));
  2730. }
  2731. inferDSOLocal(Func);
  2732. ValueList.push_back(Func);
  2733. // If this is a function with a body, remember the prototype we are
  2734. // creating now, so that we can match up the body with them later.
  2735. if (!isProto) {
  2736. Func->setIsMaterializable(true);
  2737. FunctionsWithBodies.push_back(Func);
  2738. DeferredFunctionInfo[Func] = 0;
  2739. }
  2740. return Error::success();
  2741. }
  2742. Error BitcodeReader::parseGlobalIndirectSymbolRecord(
  2743. unsigned BitCode, ArrayRef<uint64_t> Record) {
  2744. // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
  2745. // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
  2746. // dllstorageclass, threadlocal, unnamed_addr,
  2747. // preemption specifier] (name in VST)
  2748. // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
  2749. // visibility, dllstorageclass, threadlocal, unnamed_addr,
  2750. // preemption specifier] (name in VST)
  2751. // v2: [strtab_offset, strtab_size, v1]
  2752. StringRef Name;
  2753. std::tie(Name, Record) = readNameFromStrtab(Record);
  2754. bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
  2755. if (Record.size() < (3 + (unsigned)NewRecord))
  2756. return error("Invalid record");
  2757. unsigned OpNum = 0;
  2758. Type *Ty = getTypeByID(Record[OpNum++]);
  2759. if (!Ty)
  2760. return error("Invalid record");
  2761. unsigned AddrSpace;
  2762. if (!NewRecord) {
  2763. auto *PTy = dyn_cast<PointerType>(Ty);
  2764. if (!PTy)
  2765. return error("Invalid type for value");
  2766. Ty = PTy->getElementType();
  2767. AddrSpace = PTy->getAddressSpace();
  2768. } else {
  2769. AddrSpace = Record[OpNum++];
  2770. }
  2771. auto Val = Record[OpNum++];
  2772. auto Linkage = Record[OpNum++];
  2773. GlobalIndirectSymbol *NewGA;
  2774. if (BitCode == bitc::MODULE_CODE_ALIAS ||
  2775. BitCode == bitc::MODULE_CODE_ALIAS_OLD)
  2776. NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
  2777. TheModule);
  2778. else
  2779. NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
  2780. nullptr, TheModule);
  2781. // Old bitcode files didn't have visibility field.
  2782. // Local linkage must have default visibility.
  2783. if (OpNum != Record.size()) {
  2784. auto VisInd = OpNum++;
  2785. if (!NewGA->hasLocalLinkage())
  2786. // FIXME: Change to an error if non-default in 4.0.
  2787. NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
  2788. }
  2789. if (BitCode == bitc::MODULE_CODE_ALIAS ||
  2790. BitCode == bitc::MODULE_CODE_ALIAS_OLD) {
  2791. if (OpNum != Record.size())
  2792. NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
  2793. else
  2794. upgradeDLLImportExportLinkage(NewGA, Linkage);
  2795. if (OpNum != Record.size())
  2796. NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
  2797. if (OpNum != Record.size())
  2798. NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
  2799. }
  2800. if (OpNum != Record.size())
  2801. NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++]));
  2802. inferDSOLocal(NewGA);
  2803. ValueList.push_back(NewGA);
  2804. IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
  2805. return Error::success();
  2806. }
  2807. Error BitcodeReader::parseModule(uint64_t ResumeBit,
  2808. bool ShouldLazyLoadMetadata) {
  2809. if (ResumeBit)
  2810. Stream.JumpToBit(ResumeBit);
  2811. else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
  2812. return error("Invalid record");
  2813. SmallVector<uint64_t, 64> Record;
  2814. // Read all the records for this module.
  2815. while (true) {
  2816. BitstreamEntry Entry = Stream.advance();
  2817. switch (Entry.Kind) {
  2818. case BitstreamEntry::Error:
  2819. return error("Malformed block");
  2820. case BitstreamEntry::EndBlock:
  2821. return globalCleanup();
  2822. case BitstreamEntry::SubBlock:
  2823. switch (Entry.ID) {
  2824. default: // Skip unknown content.
  2825. if (Stream.SkipBlock())
  2826. return error("Invalid record");
  2827. break;
  2828. case bitc::BLOCKINFO_BLOCK_ID:
  2829. if (readBlockInfo())
  2830. return error("Malformed block");
  2831. break;
  2832. case bitc::PARAMATTR_BLOCK_ID:
  2833. if (Error Err = parseAttributeBlock())
  2834. return Err;
  2835. break;
  2836. case bitc::PARAMATTR_GROUP_BLOCK_ID:
  2837. if (Error Err = parseAttributeGroupBlock())
  2838. return Err;
  2839. break;
  2840. case bitc::TYPE_BLOCK_ID_NEW:
  2841. if (Error Err = parseTypeTable())
  2842. return Err;
  2843. break;
  2844. case bitc::VALUE_SYMTAB_BLOCK_ID:
  2845. if (!SeenValueSymbolTable) {
  2846. // Either this is an old form VST without function index and an
  2847. // associated VST forward declaration record (which would have caused
  2848. // the VST to be jumped to and parsed before it was encountered
  2849. // normally in the stream), or there were no function blocks to
  2850. // trigger an earlier parsing of the VST.
  2851. assert(VSTOffset == 0 || FunctionsWithBodies.empty());
  2852. if (Error Err = parseValueSymbolTable())
  2853. return Err;
  2854. SeenValueSymbolTable = true;
  2855. } else {
  2856. // We must have had a VST forward declaration record, which caused
  2857. // the parser to jump to and parse the VST earlier.
  2858. assert(VSTOffset > 0);
  2859. if (Stream.SkipBlock())
  2860. return error("Invalid record");
  2861. }
  2862. break;
  2863. case bitc::CONSTANTS_BLOCK_ID:
  2864. if (Error Err = parseConstants())
  2865. return Err;
  2866. if (Error Err = resolveGlobalAndIndirectSymbolInits())
  2867. return Err;
  2868. break;
  2869. case bitc::METADATA_BLOCK_ID:
  2870. if (ShouldLazyLoadMetadata) {
  2871. if (Error Err = rememberAndSkipMetadata())
  2872. return Err;
  2873. break;
  2874. }
  2875. assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
  2876. if (Error Err = MDLoader->parseModuleMetadata())
  2877. return Err;
  2878. break;
  2879. case bitc::METADATA_KIND_BLOCK_ID:
  2880. if (Error Err = MDLoader->parseMetadataKinds())
  2881. return Err;
  2882. break;
  2883. case bitc::FUNCTION_BLOCK_ID:
  2884. // If this is the first function body we've seen, reverse the
  2885. // FunctionsWithBodies list.
  2886. if (!SeenFirstFunctionBody) {
  2887. std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
  2888. if (Error Err = globalCleanup())
  2889. return Err;
  2890. SeenFirstFunctionBody = true;
  2891. }
  2892. if (VSTOffset > 0) {
  2893. // If we have a VST forward declaration record, make sure we
  2894. // parse the VST now if we haven't already. It is needed to
  2895. // set up the DeferredFunctionInfo vector for lazy reading.
  2896. if (!SeenValueSymbolTable) {
  2897. if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
  2898. return Err;
  2899. SeenValueSymbolTable = true;
  2900. // Fall through so that we record the NextUnreadBit below.
  2901. // This is necessary in case we have an anonymous function that
  2902. // is later materialized. Since it will not have a VST entry we
  2903. // need to fall back to the lazy parse to find its offset.
  2904. } else {
  2905. // If we have a VST forward declaration record, but have already
  2906. // parsed the VST (just above, when the first function body was
  2907. // encountered here), then we are resuming the parse after
  2908. // materializing functions. The ResumeBit points to the
  2909. // start of the last function block recorded in the
  2910. // DeferredFunctionInfo map. Skip it.
  2911. if (Stream.SkipBlock())
  2912. return error("Invalid record");
  2913. continue;
  2914. }
  2915. }
  2916. // Support older bitcode files that did not have the function
  2917. // index in the VST, nor a VST forward declaration record, as
  2918. // well as anonymous functions that do not have VST entries.
  2919. // Build the DeferredFunctionInfo vector on the fly.
  2920. if (Error Err = rememberAndSkipFunctionBody())
  2921. return Err;
  2922. // Suspend parsing when we reach the function bodies. Subsequent
  2923. // materialization calls will resume it when necessary. If the bitcode
  2924. // file is old, the symbol table will be at the end instead and will not
  2925. // have been seen yet. In this case, just finish the parse now.
  2926. if (SeenValueSymbolTable) {
  2927. NextUnreadBit = Stream.GetCurrentBitNo();
  2928. // After the VST has been parsed, we need to make sure intrinsic name
  2929. // are auto-upgraded.
  2930. return globalCleanup();
  2931. }
  2932. break;
  2933. case bitc::USELIST_BLOCK_ID:
  2934. if (Error Err = parseUseLists())
  2935. return Err;
  2936. break;
  2937. case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
  2938. if (Error Err = parseOperandBundleTags())
  2939. return Err;
  2940. break;
  2941. case bitc::SYNC_SCOPE_NAMES_BLOCK_ID:
  2942. if (Error Err = parseSyncScopeNames())
  2943. return Err;
  2944. break;
  2945. }
  2946. continue;
  2947. case BitstreamEntry::Record:
  2948. // The interesting case.
  2949. break;
  2950. }
  2951. // Read a record.
  2952. auto BitCode = Stream.readRecord(Entry.ID, Record);
  2953. switch (BitCode) {
  2954. default: break; // Default behavior, ignore unknown content.
  2955. case bitc::MODULE_CODE_VERSION: {
  2956. Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
  2957. if (!VersionOrErr)
  2958. return VersionOrErr.takeError();
  2959. UseRelativeIDs = *VersionOrErr >= 1;
  2960. break;
  2961. }
  2962. case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
  2963. std::string S;
  2964. if (convertToString(Record, 0, S))
  2965. return error("Invalid record");
  2966. TheModule->setTargetTriple(S);
  2967. break;
  2968. }
  2969. case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
  2970. std::string S;
  2971. if (convertToString(Record, 0, S))
  2972. return error("Invalid record");
  2973. TheModule->setDataLayout(S);
  2974. break;
  2975. }
  2976. case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
  2977. std::string S;
  2978. if (convertToString(Record, 0, S))
  2979. return error("Invalid record");
  2980. TheModule->setModuleInlineAsm(S);
  2981. break;
  2982. }
  2983. case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
  2984. // FIXME: Remove in 4.0.
  2985. std::string S;
  2986. if (convertToString(Record, 0, S))
  2987. return error("Invalid record");
  2988. // Ignore value.
  2989. break;
  2990. }
  2991. case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
  2992. std::string S;
  2993. if (convertToString(Record, 0, S))
  2994. return error("Invalid record");
  2995. SectionTable.push_back(S);
  2996. break;
  2997. }
  2998. case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
  2999. std::string S;
  3000. if (convertToString(Record, 0, S))
  3001. return error("Invalid record");
  3002. GCTable.push_back(S);
  3003. break;
  3004. }
  3005. case bitc::MODULE_CODE_COMDAT:
  3006. if (Error Err = parseComdatRecord(Record))
  3007. return Err;
  3008. break;
  3009. case bitc::MODULE_CODE_GLOBALVAR:
  3010. if (Error Err = parseGlobalVarRecord(Record))
  3011. return Err;
  3012. break;
  3013. case bitc::MODULE_CODE_FUNCTION:
  3014. if (Error Err = parseFunctionRecord(Record))
  3015. return Err;
  3016. break;
  3017. case bitc::MODULE_CODE_IFUNC:
  3018. case bitc::MODULE_CODE_ALIAS:
  3019. case bitc::MODULE_CODE_ALIAS_OLD:
  3020. if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
  3021. return Err;
  3022. break;
  3023. /// MODULE_CODE_VSTOFFSET: [offset]
  3024. case bitc::MODULE_CODE_VSTOFFSET:
  3025. if (Record.size() < 1)
  3026. return error("Invalid record");
  3027. // Note that we subtract 1 here because the offset is relative to one word
  3028. // before the start of the identification or module block, which was
  3029. // historically always the start of the regular bitcode header.
  3030. VSTOffset = Record[0] - 1;
  3031. break;
  3032. /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
  3033. case bitc::MODULE_CODE_SOURCE_FILENAME:
  3034. SmallString<128> ValueName;
  3035. if (convertToString(Record, 0, ValueName))
  3036. return error("Invalid record");
  3037. TheModule->setSourceFileName(ValueName);
  3038. break;
  3039. }
  3040. Record.clear();
  3041. }
  3042. }
  3043. Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
  3044. bool IsImporting) {
  3045. TheModule = M;
  3046. MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting,
  3047. [&](unsigned ID) { return getTypeByID(ID); });
  3048. return parseModule(0, ShouldLazyLoadMetadata);
  3049. }
  3050. Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
  3051. if (!isa<PointerType>(PtrType))
  3052. return error("Load/Store operand is not a pointer type");
  3053. Type *ElemType = cast<PointerType>(PtrType)->getElementType();
  3054. if (ValType && ValType != ElemType)
  3055. return error("Explicit load/store type does not match pointee "
  3056. "type of pointer operand");
  3057. if (!PointerType::isLoadableOrStorableType(ElemType))
  3058. return error("Cannot load/store from pointer");
  3059. return Error::success();
  3060. }
  3061. /// Lazily parse the specified function body block.
  3062. Error BitcodeReader::parseFunctionBody(Function *F) {
  3063. if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
  3064. return error("Invalid record");
  3065. // Unexpected unresolved metadata when parsing function.
  3066. if (MDLoader->hasFwdRefs())
  3067. return error("Invalid function metadata: incoming forward references");
  3068. InstructionList.clear();
  3069. unsigned ModuleValueListSize = ValueList.size();
  3070. unsigned ModuleMDLoaderSize = MDLoader->size();
  3071. // Add all the function arguments to the value table.
  3072. for (Argument &I : F->args())
  3073. ValueList.push_back(&I);
  3074. unsigned NextValueNo = ValueList.size();
  3075. BasicBlock *CurBB = nullptr;
  3076. unsigned CurBBNo = 0;
  3077. DebugLoc LastLoc;
  3078. auto getLastInstruction = [&]() -> Instruction * {
  3079. if (CurBB && !CurBB->empty())
  3080. return &CurBB->back();
  3081. else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
  3082. !FunctionBBs[CurBBNo - 1]->empty())
  3083. return &FunctionBBs[CurBBNo - 1]->back();
  3084. return nullptr;
  3085. };
  3086. std::vector<OperandBundleDef> OperandBundles;
  3087. // Read all the records.
  3088. SmallVector<uint64_t, 64> Record;
  3089. while (true) {
  3090. BitstreamEntry Entry = Stream.advance();
  3091. switch (Entry.Kind) {
  3092. case BitstreamEntry::Error:
  3093. return error("Malformed block");
  3094. case BitstreamEntry::EndBlock:
  3095. goto OutOfRecordLoop;
  3096. case BitstreamEntry::SubBlock:
  3097. switch (Entry.ID) {
  3098. default: // Skip unknown content.
  3099. if (Stream.SkipBlock())
  3100. return error("Invalid record");
  3101. break;
  3102. case bitc::CONSTANTS_BLOCK_ID:
  3103. if (Error Err = parseConstants())
  3104. return Err;
  3105. NextValueNo = ValueList.size();
  3106. break;
  3107. case bitc::VALUE_SYMTAB_BLOCK_ID:
  3108. if (Error Err = parseValueSymbolTable())
  3109. return Err;
  3110. break;
  3111. case bitc::METADATA_ATTACHMENT_ID:
  3112. if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
  3113. return Err;
  3114. break;
  3115. case bitc::METADATA_BLOCK_ID:
  3116. assert(DeferredMetadataInfo.empty() &&
  3117. "Must read all module-level metadata before function-level");
  3118. if (Error Err = MDLoader->parseFunctionMetadata())
  3119. return Err;
  3120. break;
  3121. case bitc::USELIST_BLOCK_ID:
  3122. if (Error Err = parseUseLists())
  3123. return Err;
  3124. break;
  3125. }
  3126. continue;
  3127. case BitstreamEntry::Record:
  3128. // The interesting case.
  3129. break;
  3130. }
  3131. // Read a record.
  3132. Record.clear();
  3133. Instruction *I = nullptr;
  3134. unsigned BitCode = Stream.readRecord(Entry.ID, Record);
  3135. switch (BitCode) {
  3136. default: // Default behavior: reject
  3137. return error("Invalid value");
  3138. case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
  3139. if (Record.size() < 1 || Record[0] == 0)
  3140. return error("Invalid record");
  3141. // Create all the basic blocks for the function.
  3142. FunctionBBs.resize(Record[0]);
  3143. // See if anything took the address of blocks in this function.
  3144. auto BBFRI = BasicBlockFwdRefs.find(F);
  3145. if (BBFRI == BasicBlockFwdRefs.end()) {
  3146. for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
  3147. FunctionBBs[i] = BasicBlock::Create(Context, "", F);
  3148. } else {
  3149. auto &BBRefs = BBFRI->second;
  3150. // Check for invalid basic block references.
  3151. if (BBRefs.size() > FunctionBBs.size())
  3152. return error("Invalid ID");
  3153. assert(!BBRefs.empty() && "Unexpected empty array");
  3154. assert(!BBRefs.front() && "Invalid reference to entry block");
  3155. for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
  3156. ++I)
  3157. if (I < RE && BBRefs[I]) {
  3158. BBRefs[I]->insertInto(F);
  3159. FunctionBBs[I] = BBRefs[I];
  3160. } else {
  3161. FunctionBBs[I] = BasicBlock::Create(Context, "", F);
  3162. }
  3163. // Erase from the table.
  3164. BasicBlockFwdRefs.erase(BBFRI);
  3165. }
  3166. CurBB = FunctionBBs[0];
  3167. continue;
  3168. }
  3169. case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
  3170. // This record indicates that the last instruction is at the same
  3171. // location as the previous instruction with a location.
  3172. I = getLastInstruction();
  3173. if (!I)
  3174. return error("Invalid record");
  3175. I->setDebugLoc(LastLoc);
  3176. I = nullptr;
  3177. continue;
  3178. case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
  3179. I = getLastInstruction();
  3180. if (!I || Record.size() < 4)
  3181. return error("Invalid record");
  3182. unsigned Line = Record[0], Col = Record[1];
  3183. unsigned ScopeID = Record[2], IAID = Record[3];
  3184. bool isImplicitCode = Record.size() == 5 && Record[4];
  3185. MDNode *Scope = nullptr, *IA = nullptr;
  3186. if (ScopeID) {
  3187. Scope = dyn_cast_or_null<MDNode>(
  3188. MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
  3189. if (!Scope)
  3190. return error("Invalid record");
  3191. }
  3192. if (IAID) {
  3193. IA = dyn_cast_or_null<MDNode>(
  3194. MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
  3195. if (!IA)
  3196. return error("Invalid record");
  3197. }
  3198. LastLoc = DebugLoc::get(Line, Col, Scope, IA, isImplicitCode);
  3199. I->setDebugLoc(LastLoc);
  3200. I = nullptr;
  3201. continue;
  3202. }
  3203. case bitc::FUNC_CODE_INST_UNOP: { // UNOP: [opval, ty, opcode]
  3204. unsigned OpNum = 0;
  3205. Value *LHS;
  3206. if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
  3207. OpNum+1 > Record.size())
  3208. return error("Invalid record");
  3209. int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType());
  3210. if (Opc == -1)
  3211. return error("Invalid record");
  3212. I = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
  3213. InstructionList.push_back(I);
  3214. if (OpNum < Record.size()) {
  3215. if (isa<FPMathOperator>(I)) {
  3216. FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
  3217. if (FMF.any())
  3218. I->setFastMathFlags(FMF);
  3219. }
  3220. }
  3221. break;
  3222. }
  3223. case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
  3224. unsigned OpNum = 0;
  3225. Value *LHS, *RHS;
  3226. if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
  3227. popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
  3228. OpNum+1 > Record.size())
  3229. return error("Invalid record");
  3230. int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
  3231. if (Opc == -1)
  3232. return error("Invalid record");
  3233. I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
  3234. InstructionList.push_back(I);
  3235. if (OpNum < Record.size()) {
  3236. if (Opc == Instruction::Add ||
  3237. Opc == Instruction::Sub ||
  3238. Opc == Instruction::Mul ||
  3239. Opc == Instruction::Shl) {
  3240. if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
  3241. cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
  3242. if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
  3243. cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
  3244. } else if (Opc == Instruction::SDiv ||
  3245. Opc == Instruction::UDiv ||
  3246. Opc == Instruction::LShr ||
  3247. Opc == Instruction::AShr) {
  3248. if (Record[OpNum] & (1 << bitc::PEO_EXACT))
  3249. cast<BinaryOperator>(I)->setIsExact(true);
  3250. } else if (isa<FPMathOperator>(I)) {
  3251. FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
  3252. if (FMF.any())
  3253. I->setFastMathFlags(FMF);
  3254. }
  3255. }
  3256. break;
  3257. }
  3258. case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
  3259. unsigned OpNum = 0;
  3260. Value *Op;
  3261. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  3262. OpNum+2 != Record.size())
  3263. return error("Invalid record");
  3264. Type *ResTy = getTypeByID(Record[OpNum]);
  3265. int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
  3266. if (Opc == -1 || !ResTy)
  3267. return error("Invalid record");
  3268. Instruction *Temp = nullptr;
  3269. if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
  3270. if (Temp) {
  3271. InstructionList.push_back(Temp);
  3272. CurBB->getInstList().push_back(Temp);
  3273. }
  3274. } else {
  3275. auto CastOp = (Instruction::CastOps)Opc;
  3276. if (!CastInst::castIsValid(CastOp, Op, ResTy))
  3277. return error("Invalid cast");
  3278. I = CastInst::Create(CastOp, Op, ResTy);
  3279. }
  3280. InstructionList.push_back(I);
  3281. break;
  3282. }
  3283. case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
  3284. case bitc::FUNC_CODE_INST_GEP_OLD:
  3285. case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
  3286. unsigned OpNum = 0;
  3287. Type *Ty;
  3288. bool InBounds;
  3289. if (BitCode == bitc::FUNC_CODE_INST_GEP) {
  3290. InBounds = Record[OpNum++];
  3291. Ty = getTypeByID(Record[OpNum++]);
  3292. } else {
  3293. InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
  3294. Ty = nullptr;
  3295. }
  3296. Value *BasePtr;
  3297. if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
  3298. return error("Invalid record");
  3299. if (!Ty)
  3300. Ty = cast<PointerType>(BasePtr->getType()->getScalarType())
  3301. ->getElementType();
  3302. else if (Ty !=
  3303. cast<PointerType>(BasePtr->getType()->getScalarType())
  3304. ->getElementType())
  3305. return error(
  3306. "Explicit gep type does not match pointee type of pointer operand");
  3307. SmallVector<Value*, 16> GEPIdx;
  3308. while (OpNum != Record.size()) {
  3309. Value *Op;
  3310. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  3311. return error("Invalid record");
  3312. GEPIdx.push_back(Op);
  3313. }
  3314. I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
  3315. InstructionList.push_back(I);
  3316. if (InBounds)
  3317. cast<GetElementPtrInst>(I)->setIsInBounds(true);
  3318. break;
  3319. }
  3320. case bitc::FUNC_CODE_INST_EXTRACTVAL: {
  3321. // EXTRACTVAL: [opty, opval, n x indices]
  3322. unsigned OpNum = 0;
  3323. Value *Agg;
  3324. if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
  3325. return error("Invalid record");
  3326. unsigned RecSize = Record.size();
  3327. if (OpNum == RecSize)
  3328. return error("EXTRACTVAL: Invalid instruction with 0 indices");
  3329. SmallVector<unsigned, 4> EXTRACTVALIdx;
  3330. Type *CurTy = Agg->getType();
  3331. for (; OpNum != RecSize; ++OpNum) {
  3332. bool IsArray = CurTy->isArrayTy();
  3333. bool IsStruct = CurTy->isStructTy();
  3334. uint64_t Index = Record[OpNum];
  3335. if (!IsStruct && !IsArray)
  3336. return error("EXTRACTVAL: Invalid type");
  3337. if ((unsigned)Index != Index)
  3338. return error("Invalid value");
  3339. if (IsStruct && Index >= CurTy->getStructNumElements())
  3340. return error("EXTRACTVAL: Invalid struct index");
  3341. if (IsArray && Index >= CurTy->getArrayNumElements())
  3342. return error("EXTRACTVAL: Invalid array index");
  3343. EXTRACTVALIdx.push_back((unsigned)Index);
  3344. if (IsStruct)
  3345. CurTy = CurTy->getStructElementType(Index);
  3346. else
  3347. CurTy = CurTy->getArrayElementType();
  3348. }
  3349. I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
  3350. InstructionList.push_back(I);
  3351. break;
  3352. }
  3353. case bitc::FUNC_CODE_INST_INSERTVAL: {
  3354. // INSERTVAL: [opty, opval, opty, opval, n x indices]
  3355. unsigned OpNum = 0;
  3356. Value *Agg;
  3357. if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
  3358. return error("Invalid record");
  3359. Value *Val;
  3360. if (getValueTypePair(Record, OpNum, NextValueNo, Val))
  3361. return error("Invalid record");
  3362. unsigned RecSize = Record.size();
  3363. if (OpNum == RecSize)
  3364. return error("INSERTVAL: Invalid instruction with 0 indices");
  3365. SmallVector<unsigned, 4> INSERTVALIdx;
  3366. Type *CurTy = Agg->getType();
  3367. for (; OpNum != RecSize; ++OpNum) {
  3368. bool IsArray = CurTy->isArrayTy();
  3369. bool IsStruct = CurTy->isStructTy();
  3370. uint64_t Index = Record[OpNum];
  3371. if (!IsStruct && !IsArray)
  3372. return error("INSERTVAL: Invalid type");
  3373. if ((unsigned)Index != Index)
  3374. return error("Invalid value");
  3375. if (IsStruct && Index >= CurTy->getStructNumElements())
  3376. return error("INSERTVAL: Invalid struct index");
  3377. if (IsArray && Index >= CurTy->getArrayNumElements())
  3378. return error("INSERTVAL: Invalid array index");
  3379. INSERTVALIdx.push_back((unsigned)Index);
  3380. if (IsStruct)
  3381. CurTy = CurTy->getStructElementType(Index);
  3382. else
  3383. CurTy = CurTy->getArrayElementType();
  3384. }
  3385. if (CurTy != Val->getType())
  3386. return error("Inserted value type doesn't match aggregate type");
  3387. I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
  3388. InstructionList.push_back(I);
  3389. break;
  3390. }
  3391. case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
  3392. // obsolete form of select
  3393. // handles select i1 ... in old bitcode
  3394. unsigned OpNum = 0;
  3395. Value *TrueVal, *FalseVal, *Cond;
  3396. if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
  3397. popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
  3398. popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
  3399. return error("Invalid record");
  3400. I = SelectInst::Create(Cond, TrueVal, FalseVal);
  3401. InstructionList.push_back(I);
  3402. break;
  3403. }
  3404. case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
  3405. // new form of select
  3406. // handles select i1 or select [N x i1]
  3407. unsigned OpNum = 0;
  3408. Value *TrueVal, *FalseVal, *Cond;
  3409. if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
  3410. popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
  3411. getValueTypePair(Record, OpNum, NextValueNo, Cond))
  3412. return error("Invalid record");
  3413. // select condition can be either i1 or [N x i1]
  3414. if (VectorType* vector_type =
  3415. dyn_cast<VectorType>(Cond->getType())) {
  3416. // expect <n x i1>
  3417. if (vector_type->getElementType() != Type::getInt1Ty(Context))
  3418. return error("Invalid type for value");
  3419. } else {
  3420. // expect i1
  3421. if (Cond->getType() != Type::getInt1Ty(Context))
  3422. return error("Invalid type for value");
  3423. }
  3424. I = SelectInst::Create(Cond, TrueVal, FalseVal);
  3425. InstructionList.push_back(I);
  3426. break;
  3427. }
  3428. case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
  3429. unsigned OpNum = 0;
  3430. Value *Vec, *Idx;
  3431. if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
  3432. getValueTypePair(Record, OpNum, NextValueNo, Idx))
  3433. return error("Invalid record");
  3434. if (!Vec->getType()->isVectorTy())
  3435. return error("Invalid type for value");
  3436. I = ExtractElementInst::Create(Vec, Idx);
  3437. InstructionList.push_back(I);
  3438. break;
  3439. }
  3440. case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
  3441. unsigned OpNum = 0;
  3442. Value *Vec, *Elt, *Idx;
  3443. if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
  3444. return error("Invalid record");
  3445. if (!Vec->getType()->isVectorTy())
  3446. return error("Invalid type for value");
  3447. if (popValue(Record, OpNum, NextValueNo,
  3448. cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
  3449. getValueTypePair(Record, OpNum, NextValueNo, Idx))
  3450. return error("Invalid record");
  3451. I = InsertElementInst::Create(Vec, Elt, Idx);
  3452. InstructionList.push_back(I);
  3453. break;
  3454. }
  3455. case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
  3456. unsigned OpNum = 0;
  3457. Value *Vec1, *Vec2, *Mask;
  3458. if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
  3459. popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
  3460. return error("Invalid record");
  3461. if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
  3462. return error("Invalid record");
  3463. if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
  3464. return error("Invalid type for value");
  3465. I = new ShuffleVectorInst(Vec1, Vec2, Mask);
  3466. InstructionList.push_back(I);
  3467. break;
  3468. }
  3469. case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
  3470. // Old form of ICmp/FCmp returning bool
  3471. // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
  3472. // both legal on vectors but had different behaviour.
  3473. case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
  3474. // FCmp/ICmp returning bool or vector of bool
  3475. unsigned OpNum = 0;
  3476. Value *LHS, *RHS;
  3477. if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
  3478. popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
  3479. return error("Invalid record");
  3480. unsigned PredVal = Record[OpNum];
  3481. bool IsFP = LHS->getType()->isFPOrFPVectorTy();
  3482. FastMathFlags FMF;
  3483. if (IsFP && Record.size() > OpNum+1)
  3484. FMF = getDecodedFastMathFlags(Record[++OpNum]);
  3485. if (OpNum+1 != Record.size())
  3486. return error("Invalid record");
  3487. if (LHS->getType()->isFPOrFPVectorTy())
  3488. I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
  3489. else
  3490. I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
  3491. if (FMF.any())
  3492. I->setFastMathFlags(FMF);
  3493. InstructionList.push_back(I);
  3494. break;
  3495. }
  3496. case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
  3497. {
  3498. unsigned Size = Record.size();
  3499. if (Size == 0) {
  3500. I = ReturnInst::Create(Context);
  3501. InstructionList.push_back(I);
  3502. break;
  3503. }
  3504. unsigned OpNum = 0;
  3505. Value *Op = nullptr;
  3506. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  3507. return error("Invalid record");
  3508. if (OpNum != Record.size())
  3509. return error("Invalid record");
  3510. I = ReturnInst::Create(Context, Op);
  3511. InstructionList.push_back(I);
  3512. break;
  3513. }
  3514. case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
  3515. if (Record.size() != 1 && Record.size() != 3)
  3516. return error("Invalid record");
  3517. BasicBlock *TrueDest = getBasicBlock(Record[0]);
  3518. if (!TrueDest)
  3519. return error("Invalid record");
  3520. if (Record.size() == 1) {
  3521. I = BranchInst::Create(TrueDest);
  3522. InstructionList.push_back(I);
  3523. }
  3524. else {
  3525. BasicBlock *FalseDest = getBasicBlock(Record[1]);
  3526. Value *Cond = getValue(Record, 2, NextValueNo,
  3527. Type::getInt1Ty(Context));
  3528. if (!FalseDest || !Cond)
  3529. return error("Invalid record");
  3530. I = BranchInst::Create(TrueDest, FalseDest, Cond);
  3531. InstructionList.push_back(I);
  3532. }
  3533. break;
  3534. }
  3535. case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
  3536. if (Record.size() != 1 && Record.size() != 2)
  3537. return error("Invalid record");
  3538. unsigned Idx = 0;
  3539. Value *CleanupPad =
  3540. getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
  3541. if (!CleanupPad)
  3542. return error("Invalid record");
  3543. BasicBlock *UnwindDest = nullptr;
  3544. if (Record.size() == 2) {
  3545. UnwindDest = getBasicBlock(Record[Idx++]);
  3546. if (!UnwindDest)
  3547. return error("Invalid record");
  3548. }
  3549. I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
  3550. InstructionList.push_back(I);
  3551. break;
  3552. }
  3553. case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
  3554. if (Record.size() != 2)
  3555. return error("Invalid record");
  3556. unsigned Idx = 0;
  3557. Value *CatchPad =
  3558. getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
  3559. if (!CatchPad)
  3560. return error("Invalid record");
  3561. BasicBlock *BB = getBasicBlock(Record[Idx++]);
  3562. if (!BB)
  3563. return error("Invalid record");
  3564. I = CatchReturnInst::Create(CatchPad, BB);
  3565. InstructionList.push_back(I);
  3566. break;
  3567. }
  3568. case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
  3569. // We must have, at minimum, the outer scope and the number of arguments.
  3570. if (Record.size() < 2)
  3571. return error("Invalid record");
  3572. unsigned Idx = 0;
  3573. Value *ParentPad =
  3574. getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
  3575. unsigned NumHandlers = Record[Idx++];
  3576. SmallVector<BasicBlock *, 2> Handlers;
  3577. for (unsigned Op = 0; Op != NumHandlers; ++Op) {
  3578. BasicBlock *BB = getBasicBlock(Record[Idx++]);
  3579. if (!BB)
  3580. return error("Invalid record");
  3581. Handlers.push_back(BB);
  3582. }
  3583. BasicBlock *UnwindDest = nullptr;
  3584. if (Idx + 1 == Record.size()) {
  3585. UnwindDest = getBasicBlock(Record[Idx++]);
  3586. if (!UnwindDest)
  3587. return error("Invalid record");
  3588. }
  3589. if (Record.size() != Idx)
  3590. return error("Invalid record");
  3591. auto *CatchSwitch =
  3592. CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
  3593. for (BasicBlock *Handler : Handlers)
  3594. CatchSwitch->addHandler(Handler);
  3595. I = CatchSwitch;
  3596. InstructionList.push_back(I);
  3597. break;
  3598. }
  3599. case bitc::FUNC_CODE_INST_CATCHPAD:
  3600. case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
  3601. // We must have, at minimum, the outer scope and the number of arguments.
  3602. if (Record.size() < 2)
  3603. return error("Invalid record");
  3604. unsigned Idx = 0;
  3605. Value *ParentPad =
  3606. getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
  3607. unsigned NumArgOperands = Record[Idx++];
  3608. SmallVector<Value *, 2> Args;
  3609. for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
  3610. Value *Val;
  3611. if (getValueTypePair(Record, Idx, NextValueNo, Val))
  3612. return error("Invalid record");
  3613. Args.push_back(Val);
  3614. }
  3615. if (Record.size() != Idx)
  3616. return error("Invalid record");
  3617. if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
  3618. I = CleanupPadInst::Create(ParentPad, Args);
  3619. else
  3620. I = CatchPadInst::Create(ParentPad, Args);
  3621. InstructionList.push_back(I);
  3622. break;
  3623. }
  3624. case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
  3625. // Check magic
  3626. if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
  3627. // "New" SwitchInst format with case ranges. The changes to write this
  3628. // format were reverted but we still recognize bitcode that uses it.
  3629. // Hopefully someday we will have support for case ranges and can use
  3630. // this format again.
  3631. Type *OpTy = getTypeByID(Record[1]);
  3632. unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
  3633. Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
  3634. BasicBlock *Default = getBasicBlock(Record[3]);
  3635. if (!OpTy || !Cond || !Default)
  3636. return error("Invalid record");
  3637. unsigned NumCases = Record[4];
  3638. SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
  3639. InstructionList.push_back(SI);
  3640. unsigned CurIdx = 5;
  3641. for (unsigned i = 0; i != NumCases; ++i) {
  3642. SmallVector<ConstantInt*, 1> CaseVals;
  3643. unsigned NumItems = Record[CurIdx++];
  3644. for (unsigned ci = 0; ci != NumItems; ++ci) {
  3645. bool isSingleNumber = Record[CurIdx++];
  3646. APInt Low;
  3647. unsigned ActiveWords = 1;
  3648. if (ValueBitWidth > 64)
  3649. ActiveWords = Record[CurIdx++];
  3650. Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
  3651. ValueBitWidth);
  3652. CurIdx += ActiveWords;
  3653. if (!isSingleNumber) {
  3654. ActiveWords = 1;
  3655. if (ValueBitWidth > 64)
  3656. ActiveWords = Record[CurIdx++];
  3657. APInt High = readWideAPInt(
  3658. makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
  3659. CurIdx += ActiveWords;
  3660. // FIXME: It is not clear whether values in the range should be
  3661. // compared as signed or unsigned values. The partially
  3662. // implemented changes that used this format in the past used
  3663. // unsigned comparisons.
  3664. for ( ; Low.ule(High); ++Low)
  3665. CaseVals.push_back(ConstantInt::get(Context, Low));
  3666. } else
  3667. CaseVals.push_back(ConstantInt::get(Context, Low));
  3668. }
  3669. BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
  3670. for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
  3671. cve = CaseVals.end(); cvi != cve; ++cvi)
  3672. SI->addCase(*cvi, DestBB);
  3673. }
  3674. I = SI;
  3675. break;
  3676. }
  3677. // Old SwitchInst format without case ranges.
  3678. if (Record.size() < 3 || (Record.size() & 1) == 0)
  3679. return error("Invalid record");
  3680. Type *OpTy = getTypeByID(Record[0]);
  3681. Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
  3682. BasicBlock *Default = getBasicBlock(Record[2]);
  3683. if (!OpTy || !Cond || !Default)
  3684. return error("Invalid record");
  3685. unsigned NumCases = (Record.size()-3)/2;
  3686. SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
  3687. InstructionList.push_back(SI);
  3688. for (unsigned i = 0, e = NumCases; i != e; ++i) {
  3689. ConstantInt *CaseVal =
  3690. dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
  3691. BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
  3692. if (!CaseVal || !DestBB) {
  3693. delete SI;
  3694. return error("Invalid record");
  3695. }
  3696. SI->addCase(CaseVal, DestBB);
  3697. }
  3698. I = SI;
  3699. break;
  3700. }
  3701. case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
  3702. if (Record.size() < 2)
  3703. return error("Invalid record");
  3704. Type *OpTy = getTypeByID(Record[0]);
  3705. Value *Address = getValue(Record, 1, NextValueNo, OpTy);
  3706. if (!OpTy || !Address)
  3707. return error("Invalid record");
  3708. unsigned NumDests = Record.size()-2;
  3709. IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
  3710. InstructionList.push_back(IBI);
  3711. for (unsigned i = 0, e = NumDests; i != e; ++i) {
  3712. if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
  3713. IBI->addDestination(DestBB);
  3714. } else {
  3715. delete IBI;
  3716. return error("Invalid record");
  3717. }
  3718. }
  3719. I = IBI;
  3720. break;
  3721. }
  3722. case bitc::FUNC_CODE_INST_INVOKE: {
  3723. // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
  3724. if (Record.size() < 4)
  3725. return error("Invalid record");
  3726. unsigned OpNum = 0;
  3727. AttributeList PAL = getAttributes(Record[OpNum++]);
  3728. unsigned CCInfo = Record[OpNum++];
  3729. BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
  3730. BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
  3731. FunctionType *FTy = nullptr;
  3732. if (CCInfo >> 13 & 1 &&
  3733. !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
  3734. return error("Explicit invoke type is not a function type");
  3735. Value *Callee;
  3736. if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
  3737. return error("Invalid record");
  3738. PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
  3739. if (!CalleeTy)
  3740. return error("Callee is not a pointer");
  3741. if (!FTy) {
  3742. FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
  3743. if (!FTy)
  3744. return error("Callee is not of pointer to function type");
  3745. } else if (CalleeTy->getElementType() != FTy)
  3746. return error("Explicit invoke type does not match pointee type of "
  3747. "callee operand");
  3748. if (Record.size() < FTy->getNumParams() + OpNum)
  3749. return error("Insufficient operands to call");
  3750. SmallVector<Value*, 16> Ops;
  3751. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
  3752. Ops.push_back(getValue(Record, OpNum, NextValueNo,
  3753. FTy->getParamType(i)));
  3754. if (!Ops.back())
  3755. return error("Invalid record");
  3756. }
  3757. if (!FTy->isVarArg()) {
  3758. if (Record.size() != OpNum)
  3759. return error("Invalid record");
  3760. } else {
  3761. // Read type/value pairs for varargs params.
  3762. while (OpNum != Record.size()) {
  3763. Value *Op;
  3764. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  3765. return error("Invalid record");
  3766. Ops.push_back(Op);
  3767. }
  3768. }
  3769. I = InvokeInst::Create(FTy, Callee, NormalBB, UnwindBB, Ops,
  3770. OperandBundles);
  3771. OperandBundles.clear();
  3772. InstructionList.push_back(I);
  3773. cast<InvokeInst>(I)->setCallingConv(
  3774. static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
  3775. cast<InvokeInst>(I)->setAttributes(PAL);
  3776. break;
  3777. }
  3778. case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
  3779. unsigned Idx = 0;
  3780. Value *Val = nullptr;
  3781. if (getValueTypePair(Record, Idx, NextValueNo, Val))
  3782. return error("Invalid record");
  3783. I = ResumeInst::Create(Val);
  3784. InstructionList.push_back(I);
  3785. break;
  3786. }
  3787. case bitc::FUNC_CODE_INST_CALLBR: {
  3788. // CALLBR: [attr, cc, norm, transfs, fty, fnid, args]
  3789. unsigned OpNum = 0;
  3790. AttributeList PAL = getAttributes(Record[OpNum++]);
  3791. unsigned CCInfo = Record[OpNum++];
  3792. BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);
  3793. unsigned NumIndirectDests = Record[OpNum++];
  3794. SmallVector<BasicBlock *, 16> IndirectDests;
  3795. for (unsigned i = 0, e = NumIndirectDests; i != e; ++i)
  3796. IndirectDests.push_back(getBasicBlock(Record[OpNum++]));
  3797. FunctionType *FTy = nullptr;
  3798. if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
  3799. !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
  3800. return error("Explicit call type is not a function type");
  3801. Value *Callee;
  3802. if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
  3803. return error("Invalid record");
  3804. PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
  3805. if (!OpTy)
  3806. return error("Callee is not a pointer type");
  3807. if (!FTy) {
  3808. FTy = dyn_cast<FunctionType>(OpTy->getElementType());
  3809. if (!FTy)
  3810. return error("Callee is not of pointer to function type");
  3811. } else if (OpTy->getElementType() != FTy)
  3812. return error("Explicit call type does not match pointee type of "
  3813. "callee operand");
  3814. if (Record.size() < FTy->getNumParams() + OpNum)
  3815. return error("Insufficient operands to call");
  3816. SmallVector<Value*, 16> Args;
  3817. // Read the fixed params.
  3818. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
  3819. if (FTy->getParamType(i)->isLabelTy())
  3820. Args.push_back(getBasicBlock(Record[OpNum]));
  3821. else
  3822. Args.push_back(getValue(Record, OpNum, NextValueNo,
  3823. FTy->getParamType(i)));
  3824. if (!Args.back())
  3825. return error("Invalid record");
  3826. }
  3827. // Read type/value pairs for varargs params.
  3828. if (!FTy->isVarArg()) {
  3829. if (OpNum != Record.size())
  3830. return error("Invalid record");
  3831. } else {
  3832. while (OpNum != Record.size()) {
  3833. Value *Op;
  3834. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  3835. return error("Invalid record");
  3836. Args.push_back(Op);
  3837. }
  3838. }
  3839. I = CallBrInst::Create(FTy, Callee, DefaultDest, IndirectDests, Args,
  3840. OperandBundles);
  3841. OperandBundles.clear();
  3842. InstructionList.push_back(I);
  3843. cast<CallBrInst>(I)->setCallingConv(
  3844. static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
  3845. cast<CallBrInst>(I)->setAttributes(PAL);
  3846. break;
  3847. }
  3848. case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
  3849. I = new UnreachableInst(Context);
  3850. InstructionList.push_back(I);
  3851. break;
  3852. case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
  3853. if (Record.size() < 1 || ((Record.size()-1)&1))
  3854. return error("Invalid record");
  3855. Type *Ty = getTypeByID(Record[0]);
  3856. if (!Ty)
  3857. return error("Invalid record");
  3858. PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
  3859. InstructionList.push_back(PN);
  3860. for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
  3861. Value *V;
  3862. // With the new function encoding, it is possible that operands have
  3863. // negative IDs (for forward references). Use a signed VBR
  3864. // representation to keep the encoding small.
  3865. if (UseRelativeIDs)
  3866. V = getValueSigned(Record, 1+i, NextValueNo, Ty);
  3867. else
  3868. V = getValue(Record, 1+i, NextValueNo, Ty);
  3869. BasicBlock *BB = getBasicBlock(Record[2+i]);
  3870. if (!V || !BB)
  3871. return error("Invalid record");
  3872. PN->addIncoming(V, BB);
  3873. }
  3874. I = PN;
  3875. break;
  3876. }
  3877. case bitc::FUNC_CODE_INST_LANDINGPAD:
  3878. case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
  3879. // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
  3880. unsigned Idx = 0;
  3881. if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
  3882. if (Record.size() < 3)
  3883. return error("Invalid record");
  3884. } else {
  3885. assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
  3886. if (Record.size() < 4)
  3887. return error("Invalid record");
  3888. }
  3889. Type *Ty = getTypeByID(Record[Idx++]);
  3890. if (!Ty)
  3891. return error("Invalid record");
  3892. if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
  3893. Value *PersFn = nullptr;
  3894. if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
  3895. return error("Invalid record");
  3896. if (!F->hasPersonalityFn())
  3897. F->setPersonalityFn(cast<Constant>(PersFn));
  3898. else if (F->getPersonalityFn() != cast<Constant>(PersFn))
  3899. return error("Personality function mismatch");
  3900. }
  3901. bool IsCleanup = !!Record[Idx++];
  3902. unsigned NumClauses = Record[Idx++];
  3903. LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
  3904. LP->setCleanup(IsCleanup);
  3905. for (unsigned J = 0; J != NumClauses; ++J) {
  3906. LandingPadInst::ClauseType CT =
  3907. LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
  3908. Value *Val;
  3909. if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
  3910. delete LP;
  3911. return error("Invalid record");
  3912. }
  3913. assert((CT != LandingPadInst::Catch ||
  3914. !isa<ArrayType>(Val->getType())) &&
  3915. "Catch clause has a invalid type!");
  3916. assert((CT != LandingPadInst::Filter ||
  3917. isa<ArrayType>(Val->getType())) &&
  3918. "Filter clause has invalid type!");
  3919. LP->addClause(cast<Constant>(Val));
  3920. }
  3921. I = LP;
  3922. InstructionList.push_back(I);
  3923. break;
  3924. }
  3925. case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
  3926. if (Record.size() != 4)
  3927. return error("Invalid record");
  3928. uint64_t AlignRecord = Record[3];
  3929. const uint64_t InAllocaMask = uint64_t(1) << 5;
  3930. const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
  3931. const uint64_t SwiftErrorMask = uint64_t(1) << 7;
  3932. const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask |
  3933. SwiftErrorMask;
  3934. bool InAlloca = AlignRecord & InAllocaMask;
  3935. bool SwiftError = AlignRecord & SwiftErrorMask;
  3936. Type *Ty = getTypeByID(Record[0]);
  3937. if ((AlignRecord & ExplicitTypeMask) == 0) {
  3938. auto *PTy = dyn_cast_or_null<PointerType>(Ty);
  3939. if (!PTy)
  3940. return error("Old-style alloca with a non-pointer type");
  3941. Ty = PTy->getElementType();
  3942. }
  3943. Type *OpTy = getTypeByID(Record[1]);
  3944. Value *Size = getFnValueByID(Record[2], OpTy);
  3945. unsigned Align;
  3946. if (Error Err = parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
  3947. return Err;
  3948. }
  3949. if (!Ty || !Size)
  3950. return error("Invalid record");
  3951. // FIXME: Make this an optional field.
  3952. const DataLayout &DL = TheModule->getDataLayout();
  3953. unsigned AS = DL.getAllocaAddrSpace();
  3954. AllocaInst *AI = new AllocaInst(Ty, AS, Size, Align);
  3955. AI->setUsedWithInAlloca(InAlloca);
  3956. AI->setSwiftError(SwiftError);
  3957. I = AI;
  3958. InstructionList.push_back(I);
  3959. break;
  3960. }
  3961. case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
  3962. unsigned OpNum = 0;
  3963. Value *Op;
  3964. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  3965. (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
  3966. return error("Invalid record");
  3967. Type *Ty = nullptr;
  3968. if (OpNum + 3 == Record.size())
  3969. Ty = getTypeByID(Record[OpNum++]);
  3970. if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
  3971. return Err;
  3972. if (!Ty)
  3973. Ty = cast<PointerType>(Op->getType())->getElementType();
  3974. unsigned Align;
  3975. if (Error Err = parseAlignmentValue(Record[OpNum], Align))
  3976. return Err;
  3977. I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
  3978. InstructionList.push_back(I);
  3979. break;
  3980. }
  3981. case bitc::FUNC_CODE_INST_LOADATOMIC: {
  3982. // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
  3983. unsigned OpNum = 0;
  3984. Value *Op;
  3985. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  3986. (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
  3987. return error("Invalid record");
  3988. Type *Ty = nullptr;
  3989. if (OpNum + 5 == Record.size())
  3990. Ty = getTypeByID(Record[OpNum++]);
  3991. if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
  3992. return Err;
  3993. if (!Ty)
  3994. Ty = cast<PointerType>(Op->getType())->getElementType();
  3995. AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
  3996. if (Ordering == AtomicOrdering::NotAtomic ||
  3997. Ordering == AtomicOrdering::Release ||
  3998. Ordering == AtomicOrdering::AcquireRelease)
  3999. return error("Invalid record");
  4000. if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
  4001. return error("Invalid record");
  4002. SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
  4003. unsigned Align;
  4004. if (Error Err = parseAlignmentValue(Record[OpNum], Align))
  4005. return Err;
  4006. I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align, Ordering, SSID);
  4007. InstructionList.push_back(I);
  4008. break;
  4009. }
  4010. case bitc::FUNC_CODE_INST_STORE:
  4011. case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
  4012. unsigned OpNum = 0;
  4013. Value *Val, *Ptr;
  4014. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
  4015. (BitCode == bitc::FUNC_CODE_INST_STORE
  4016. ? getValueTypePair(Record, OpNum, NextValueNo, Val)
  4017. : popValue(Record, OpNum, NextValueNo,
  4018. cast<PointerType>(Ptr->getType())->getElementType(),
  4019. Val)) ||
  4020. OpNum + 2 != Record.size())
  4021. return error("Invalid record");
  4022. if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
  4023. return Err;
  4024. unsigned Align;
  4025. if (Error Err = parseAlignmentValue(Record[OpNum], Align))
  4026. return Err;
  4027. I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
  4028. InstructionList.push_back(I);
  4029. break;
  4030. }
  4031. case bitc::FUNC_CODE_INST_STOREATOMIC:
  4032. case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
  4033. // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
  4034. unsigned OpNum = 0;
  4035. Value *Val, *Ptr;
  4036. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
  4037. !isa<PointerType>(Ptr->getType()) ||
  4038. (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
  4039. ? getValueTypePair(Record, OpNum, NextValueNo, Val)
  4040. : popValue(Record, OpNum, NextValueNo,
  4041. cast<PointerType>(Ptr->getType())->getElementType(),
  4042. Val)) ||
  4043. OpNum + 4 != Record.size())
  4044. return error("Invalid record");
  4045. if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
  4046. return Err;
  4047. AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
  4048. if (Ordering == AtomicOrdering::NotAtomic ||
  4049. Ordering == AtomicOrdering::Acquire ||
  4050. Ordering == AtomicOrdering::AcquireRelease)
  4051. return error("Invalid record");
  4052. SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
  4053. if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
  4054. return error("Invalid record");
  4055. unsigned Align;
  4056. if (Error Err = parseAlignmentValue(Record[OpNum], Align))
  4057. return Err;
  4058. I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SSID);
  4059. InstructionList.push_back(I);
  4060. break;
  4061. }
  4062. case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
  4063. case bitc::FUNC_CODE_INST_CMPXCHG: {
  4064. // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, ssid,
  4065. // failureordering?, isweak?]
  4066. unsigned OpNum = 0;
  4067. Value *Ptr, *Cmp, *New;
  4068. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
  4069. (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
  4070. ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
  4071. : popValue(Record, OpNum, NextValueNo,
  4072. cast<PointerType>(Ptr->getType())->getElementType(),
  4073. Cmp)) ||
  4074. popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
  4075. Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
  4076. return error("Invalid record");
  4077. AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
  4078. if (SuccessOrdering == AtomicOrdering::NotAtomic ||
  4079. SuccessOrdering == AtomicOrdering::Unordered)
  4080. return error("Invalid record");
  4081. SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
  4082. if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
  4083. return Err;
  4084. AtomicOrdering FailureOrdering;
  4085. if (Record.size() < 7)
  4086. FailureOrdering =
  4087. AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
  4088. else
  4089. FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
  4090. I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
  4091. SSID);
  4092. cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
  4093. if (Record.size() < 8) {
  4094. // Before weak cmpxchgs existed, the instruction simply returned the
  4095. // value loaded from memory, so bitcode files from that era will be
  4096. // expecting the first component of a modern cmpxchg.
  4097. CurBB->getInstList().push_back(I);
  4098. I = ExtractValueInst::Create(I, 0);
  4099. } else {
  4100. cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
  4101. }
  4102. InstructionList.push_back(I);
  4103. break;
  4104. }
  4105. case bitc::FUNC_CODE_INST_ATOMICRMW: {
  4106. // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, ssid]
  4107. unsigned OpNum = 0;
  4108. Value *Ptr, *Val;
  4109. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
  4110. !isa<PointerType>(Ptr->getType()) ||
  4111. popValue(Record, OpNum, NextValueNo,
  4112. cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
  4113. OpNum+4 != Record.size())
  4114. return error("Invalid record");
  4115. AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
  4116. if (Operation < AtomicRMWInst::FIRST_BINOP ||
  4117. Operation > AtomicRMWInst::LAST_BINOP)
  4118. return error("Invalid record");
  4119. AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
  4120. if (Ordering == AtomicOrdering::NotAtomic ||
  4121. Ordering == AtomicOrdering::Unordered)
  4122. return error("Invalid record");
  4123. SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
  4124. I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
  4125. cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
  4126. InstructionList.push_back(I);
  4127. break;
  4128. }
  4129. case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid]
  4130. if (2 != Record.size())
  4131. return error("Invalid record");
  4132. AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
  4133. if (Ordering == AtomicOrdering::NotAtomic ||
  4134. Ordering == AtomicOrdering::Unordered ||
  4135. Ordering == AtomicOrdering::Monotonic)
  4136. return error("Invalid record");
  4137. SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]);
  4138. I = new FenceInst(Context, Ordering, SSID);
  4139. InstructionList.push_back(I);
  4140. break;
  4141. }
  4142. case bitc::FUNC_CODE_INST_CALL: {
  4143. // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
  4144. if (Record.size() < 3)
  4145. return error("Invalid record");
  4146. unsigned OpNum = 0;
  4147. AttributeList PAL = getAttributes(Record[OpNum++]);
  4148. unsigned CCInfo = Record[OpNum++];
  4149. FastMathFlags FMF;
  4150. if ((CCInfo >> bitc::CALL_FMF) & 1) {
  4151. FMF = getDecodedFastMathFlags(Record[OpNum++]);
  4152. if (!FMF.any())
  4153. return error("Fast math flags indicator set for call with no FMF");
  4154. }
  4155. FunctionType *FTy = nullptr;
  4156. if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
  4157. !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
  4158. return error("Explicit call type is not a function type");
  4159. Value *Callee;
  4160. if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
  4161. return error("Invalid record");
  4162. PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
  4163. if (!OpTy)
  4164. return error("Callee is not a pointer type");
  4165. if (!FTy) {
  4166. FTy = dyn_cast<FunctionType>(OpTy->getElementType());
  4167. if (!FTy)
  4168. return error("Callee is not of pointer to function type");
  4169. } else if (OpTy->getElementType() != FTy)
  4170. return error("Explicit call type does not match pointee type of "
  4171. "callee operand");
  4172. if (Record.size() < FTy->getNumParams() + OpNum)
  4173. return error("Insufficient operands to call");
  4174. SmallVector<Value*, 16> Args;
  4175. // Read the fixed params.
  4176. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
  4177. if (FTy->getParamType(i)->isLabelTy())
  4178. Args.push_back(getBasicBlock(Record[OpNum]));
  4179. else
  4180. Args.push_back(getValue(Record, OpNum, NextValueNo,
  4181. FTy->getParamType(i)));
  4182. if (!Args.back())
  4183. return error("Invalid record");
  4184. }
  4185. // Read type/value pairs for varargs params.
  4186. if (!FTy->isVarArg()) {
  4187. if (OpNum != Record.size())
  4188. return error("Invalid record");
  4189. } else {
  4190. while (OpNum != Record.size()) {
  4191. Value *Op;
  4192. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  4193. return error("Invalid record");
  4194. Args.push_back(Op);
  4195. }
  4196. }
  4197. I = CallInst::Create(FTy, Callee, Args, OperandBundles);
  4198. OperandBundles.clear();
  4199. InstructionList.push_back(I);
  4200. cast<CallInst>(I)->setCallingConv(
  4201. static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
  4202. CallInst::TailCallKind TCK = CallInst::TCK_None;
  4203. if (CCInfo & 1 << bitc::CALL_TAIL)
  4204. TCK = CallInst::TCK_Tail;
  4205. if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
  4206. TCK = CallInst::TCK_MustTail;
  4207. if (CCInfo & (1 << bitc::CALL_NOTAIL))
  4208. TCK = CallInst::TCK_NoTail;
  4209. cast<CallInst>(I)->setTailCallKind(TCK);
  4210. cast<CallInst>(I)->setAttributes(PAL);
  4211. if (FMF.any()) {
  4212. if (!isa<FPMathOperator>(I))
  4213. return error("Fast-math-flags specified for call without "
  4214. "floating-point scalar or vector return type");
  4215. I->setFastMathFlags(FMF);
  4216. }
  4217. break;
  4218. }
  4219. case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
  4220. if (Record.size() < 3)
  4221. return error("Invalid record");
  4222. Type *OpTy = getTypeByID(Record[0]);
  4223. Value *Op = getValue(Record, 1, NextValueNo, OpTy);
  4224. Type *ResTy = getTypeByID(Record[2]);
  4225. if (!OpTy || !Op || !ResTy)
  4226. return error("Invalid record");
  4227. I = new VAArgInst(Op, ResTy);
  4228. InstructionList.push_back(I);
  4229. break;
  4230. }
  4231. case bitc::FUNC_CODE_OPERAND_BUNDLE: {
  4232. // A call or an invoke can be optionally prefixed with some variable
  4233. // number of operand bundle blocks. These blocks are read into
  4234. // OperandBundles and consumed at the next call or invoke instruction.
  4235. if (Record.size() < 1 || Record[0] >= BundleTags.size())
  4236. return error("Invalid record");
  4237. std::vector<Value *> Inputs;
  4238. unsigned OpNum = 1;
  4239. while (OpNum != Record.size()) {
  4240. Value *Op;
  4241. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  4242. return error("Invalid record");
  4243. Inputs.push_back(Op);
  4244. }
  4245. OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
  4246. continue;
  4247. }
  4248. }
  4249. // Add instruction to end of current BB. If there is no current BB, reject
  4250. // this file.
  4251. if (!CurBB) {
  4252. I->deleteValue();
  4253. return error("Invalid instruction with no BB");
  4254. }
  4255. if (!OperandBundles.empty()) {
  4256. I->deleteValue();
  4257. return error("Operand bundles found with no consumer");
  4258. }
  4259. CurBB->getInstList().push_back(I);
  4260. // If this was a terminator instruction, move to the next block.
  4261. if (I->isTerminator()) {
  4262. ++CurBBNo;
  4263. CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
  4264. }
  4265. // Non-void values get registered in the value table for future use.
  4266. if (I && !I->getType()->isVoidTy())
  4267. ValueList.assignValue(I, NextValueNo++);
  4268. }
  4269. OutOfRecordLoop:
  4270. if (!OperandBundles.empty())
  4271. return error("Operand bundles found with no consumer");
  4272. // Check the function list for unresolved values.
  4273. if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
  4274. if (!A->getParent()) {
  4275. // We found at least one unresolved value. Nuke them all to avoid leaks.
  4276. for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
  4277. if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
  4278. A->replaceAllUsesWith(UndefValue::get(A->getType()));
  4279. delete A;
  4280. }
  4281. }
  4282. return error("Never resolved value found in function");
  4283. }
  4284. }
  4285. // Unexpected unresolved metadata about to be dropped.
  4286. if (MDLoader->hasFwdRefs())
  4287. return error("Invalid function metadata: outgoing forward refs");
  4288. // Trim the value list down to the size it was before we parsed this function.
  4289. ValueList.shrinkTo(ModuleValueListSize);
  4290. MDLoader->shrinkTo(ModuleMDLoaderSize);
  4291. std::vector<BasicBlock*>().swap(FunctionBBs);
  4292. return Error::success();
  4293. }
  4294. /// Find the function body in the bitcode stream
  4295. Error BitcodeReader::findFunctionInStream(
  4296. Function *F,
  4297. DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
  4298. while (DeferredFunctionInfoIterator->second == 0) {
  4299. // This is the fallback handling for the old format bitcode that
  4300. // didn't contain the function index in the VST, or when we have
  4301. // an anonymous function which would not have a VST entry.
  4302. // Assert that we have one of those two cases.
  4303. assert(VSTOffset == 0 || !F->hasName());
  4304. // Parse the next body in the stream and set its position in the
  4305. // DeferredFunctionInfo map.
  4306. if (Error Err = rememberAndSkipFunctionBodies())
  4307. return Err;
  4308. }
  4309. return Error::success();
  4310. }
  4311. SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) {
  4312. if (Val == SyncScope::SingleThread || Val == SyncScope::System)
  4313. return SyncScope::ID(Val);
  4314. if (Val >= SSIDs.size())
  4315. return SyncScope::System; // Map unknown synchronization scopes to system.
  4316. return SSIDs[Val];
  4317. }
  4318. //===----------------------------------------------------------------------===//
  4319. // GVMaterializer implementation
  4320. //===----------------------------------------------------------------------===//
  4321. Error BitcodeReader::materialize(GlobalValue *GV) {
  4322. Function *F = dyn_cast<Function>(GV);
  4323. // If it's not a function or is already material, ignore the request.
  4324. if (!F || !F->isMaterializable())
  4325. return Error::success();
  4326. DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
  4327. assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
  4328. // If its position is recorded as 0, its body is somewhere in the stream
  4329. // but we haven't seen it yet.
  4330. if (DFII->second == 0)
  4331. if (Error Err = findFunctionInStream(F, DFII))
  4332. return Err;
  4333. // Materialize metadata before parsing any function bodies.
  4334. if (Error Err = materializeMetadata())
  4335. return Err;
  4336. // Move the bit stream to the saved position of the deferred function body.
  4337. Stream.JumpToBit(DFII->second);
  4338. if (Error Err = parseFunctionBody(F))
  4339. return Err;
  4340. F->setIsMaterializable(false);
  4341. if (StripDebugInfo)
  4342. stripDebugInfo(*F);
  4343. // Upgrade any old intrinsic calls in the function.
  4344. for (auto &I : UpgradedIntrinsics) {
  4345. for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
  4346. UI != UE;) {
  4347. User *U = *UI;
  4348. ++UI;
  4349. if (CallInst *CI = dyn_cast<CallInst>(U))
  4350. UpgradeIntrinsicCall(CI, I.second);
  4351. }
  4352. }
  4353. // Update calls to the remangled intrinsics
  4354. for (auto &I : RemangledIntrinsics)
  4355. for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
  4356. UI != UE;)
  4357. // Don't expect any other users than call sites
  4358. CallSite(*UI++).setCalledFunction(I.second);
  4359. // Finish fn->subprogram upgrade for materialized functions.
  4360. if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
  4361. F->setSubprogram(SP);
  4362. // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
  4363. if (!MDLoader->isStrippingTBAA()) {
  4364. for (auto &I : instructions(F)) {
  4365. MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
  4366. if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
  4367. continue;
  4368. MDLoader->setStripTBAA(true);
  4369. stripTBAA(F->getParent());
  4370. }
  4371. }
  4372. // Bring in any functions that this function forward-referenced via
  4373. // blockaddresses.
  4374. return materializeForwardReferencedFunctions();
  4375. }
  4376. Error BitcodeReader::materializeModule() {
  4377. if (Error Err = materializeMetadata())
  4378. return Err;
  4379. // Promise to materialize all forward references.
  4380. WillMaterializeAllForwardRefs = true;
  4381. // Iterate over the module, deserializing any functions that are still on
  4382. // disk.
  4383. for (Function &F : *TheModule) {
  4384. if (Error Err = materialize(&F))
  4385. return Err;
  4386. }
  4387. // At this point, if there are any function bodies, parse the rest of
  4388. // the bits in the module past the last function block we have recorded
  4389. // through either lazy scanning or the VST.
  4390. if (LastFunctionBlockBit || NextUnreadBit)
  4391. if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
  4392. ? LastFunctionBlockBit
  4393. : NextUnreadBit))
  4394. return Err;
  4395. // Check that all block address forward references got resolved (as we
  4396. // promised above).
  4397. if (!BasicBlockFwdRefs.empty())
  4398. return error("Never resolved function from blockaddress");
  4399. // Upgrade any intrinsic calls that slipped through (should not happen!) and
  4400. // delete the old functions to clean up. We can't do this unless the entire
  4401. // module is materialized because there could always be another function body
  4402. // with calls to the old function.
  4403. for (auto &I : UpgradedIntrinsics) {
  4404. for (auto *U : I.first->users()) {
  4405. if (CallInst *CI = dyn_cast<CallInst>(U))
  4406. UpgradeIntrinsicCall(CI, I.second);
  4407. }
  4408. if (!I.first->use_empty())
  4409. I.first->replaceAllUsesWith(I.second);
  4410. I.first->eraseFromParent();
  4411. }
  4412. UpgradedIntrinsics.clear();
  4413. // Do the same for remangled intrinsics
  4414. for (auto &I : RemangledIntrinsics) {
  4415. I.first->replaceAllUsesWith(I.second);
  4416. I.first->eraseFromParent();
  4417. }
  4418. RemangledIntrinsics.clear();
  4419. UpgradeDebugInfo(*TheModule);
  4420. UpgradeModuleFlags(*TheModule);
  4421. UpgradeRetainReleaseMarker(*TheModule);
  4422. return Error::success();
  4423. }
  4424. std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
  4425. return IdentifiedStructTypes;
  4426. }
  4427. ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
  4428. BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
  4429. StringRef ModulePath, unsigned ModuleId)
  4430. : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
  4431. ModulePath(ModulePath), ModuleId(ModuleId) {}
  4432. void ModuleSummaryIndexBitcodeReader::addThisModule() {
  4433. TheIndex.addModule(ModulePath, ModuleId);
  4434. }
  4435. ModuleSummaryIndex::ModuleInfo *
  4436. ModuleSummaryIndexBitcodeReader::getThisModule() {
  4437. return TheIndex.getModule(ModulePath);
  4438. }
  4439. std::pair<ValueInfo, GlobalValue::GUID>
  4440. ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
  4441. auto VGI = ValueIdToValueInfoMap[ValueId];
  4442. assert(VGI.first);
  4443. return VGI;
  4444. }
  4445. void ModuleSummaryIndexBitcodeReader::setValueGUID(
  4446. uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
  4447. StringRef SourceFileName) {
  4448. std::string GlobalId =
  4449. GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
  4450. auto ValueGUID = GlobalValue::getGUID(GlobalId);
  4451. auto OriginalNameID = ValueGUID;
  4452. if (GlobalValue::isLocalLinkage(Linkage))
  4453. OriginalNameID = GlobalValue::getGUID(ValueName);
  4454. if (PrintSummaryGUIDs)
  4455. dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
  4456. << ValueName << "\n";
  4457. // UseStrtab is false for legacy summary formats and value names are
  4458. // created on stack. In that case we save the name in a string saver in
  4459. // the index so that the value name can be recorded.
  4460. ValueIdToValueInfoMap[ValueID] = std::make_pair(
  4461. TheIndex.getOrInsertValueInfo(
  4462. ValueGUID,
  4463. UseStrtab ? ValueName : TheIndex.saveString(ValueName)),
  4464. OriginalNameID);
  4465. }
  4466. // Specialized value symbol table parser used when reading module index
  4467. // blocks where we don't actually create global values. The parsed information
  4468. // is saved in the bitcode reader for use when later parsing summaries.
  4469. Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
  4470. uint64_t Offset,
  4471. DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
  4472. // With a strtab the VST is not required to parse the summary.
  4473. if (UseStrtab)
  4474. return Error::success();
  4475. assert(Offset > 0 && "Expected non-zero VST offset");
  4476. uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream);
  4477. if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
  4478. return error("Invalid record");
  4479. SmallVector<uint64_t, 64> Record;
  4480. // Read all the records for this value table.
  4481. SmallString<128> ValueName;
  4482. while (true) {
  4483. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  4484. switch (Entry.Kind) {
  4485. case BitstreamEntry::SubBlock: // Handled for us already.
  4486. case BitstreamEntry::Error:
  4487. return error("Malformed block");
  4488. case BitstreamEntry::EndBlock:
  4489. // Done parsing VST, jump back to wherever we came from.
  4490. Stream.JumpToBit(CurrentBit);
  4491. return Error::success();
  4492. case BitstreamEntry::Record:
  4493. // The interesting case.
  4494. break;
  4495. }
  4496. // Read a record.
  4497. Record.clear();
  4498. switch (Stream.readRecord(Entry.ID, Record)) {
  4499. default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
  4500. break;
  4501. case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
  4502. if (convertToString(Record, 1, ValueName))
  4503. return error("Invalid record");
  4504. unsigned ValueID = Record[0];
  4505. assert(!SourceFileName.empty());
  4506. auto VLI = ValueIdToLinkageMap.find(ValueID);
  4507. assert(VLI != ValueIdToLinkageMap.end() &&
  4508. "No linkage found for VST entry?");
  4509. auto Linkage = VLI->second;
  4510. setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
  4511. ValueName.clear();
  4512. break;
  4513. }
  4514. case bitc::VST_CODE_FNENTRY: {
  4515. // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
  4516. if (convertToString(Record, 2, ValueName))
  4517. return error("Invalid record");
  4518. unsigned ValueID = Record[0];
  4519. assert(!SourceFileName.empty());
  4520. auto VLI = ValueIdToLinkageMap.find(ValueID);
  4521. assert(VLI != ValueIdToLinkageMap.end() &&
  4522. "No linkage found for VST entry?");
  4523. auto Linkage = VLI->second;
  4524. setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
  4525. ValueName.clear();
  4526. break;
  4527. }
  4528. case bitc::VST_CODE_COMBINED_ENTRY: {
  4529. // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
  4530. unsigned ValueID = Record[0];
  4531. GlobalValue::GUID RefGUID = Record[1];
  4532. // The "original name", which is the second value of the pair will be
  4533. // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
  4534. ValueIdToValueInfoMap[ValueID] =
  4535. std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
  4536. break;
  4537. }
  4538. }
  4539. }
  4540. }
  4541. // Parse just the blocks needed for building the index out of the module.
  4542. // At the end of this routine the module Index is populated with a map
  4543. // from global value id to GlobalValueSummary objects.
  4544. Error ModuleSummaryIndexBitcodeReader::parseModule() {
  4545. if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
  4546. return error("Invalid record");
  4547. SmallVector<uint64_t, 64> Record;
  4548. DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
  4549. unsigned ValueId = 0;
  4550. // Read the index for this module.
  4551. while (true) {
  4552. BitstreamEntry Entry = Stream.advance();
  4553. switch (Entry.Kind) {
  4554. case BitstreamEntry::Error:
  4555. return error("Malformed block");
  4556. case BitstreamEntry::EndBlock:
  4557. return Error::success();
  4558. case BitstreamEntry::SubBlock:
  4559. switch (Entry.ID) {
  4560. default: // Skip unknown content.
  4561. if (Stream.SkipBlock())
  4562. return error("Invalid record");
  4563. break;
  4564. case bitc::BLOCKINFO_BLOCK_ID:
  4565. // Need to parse these to get abbrev ids (e.g. for VST)
  4566. if (readBlockInfo())
  4567. return error("Malformed block");
  4568. break;
  4569. case bitc::VALUE_SYMTAB_BLOCK_ID:
  4570. // Should have been parsed earlier via VSTOffset, unless there
  4571. // is no summary section.
  4572. assert(((SeenValueSymbolTable && VSTOffset > 0) ||
  4573. !SeenGlobalValSummary) &&
  4574. "Expected early VST parse via VSTOffset record");
  4575. if (Stream.SkipBlock())
  4576. return error("Invalid record");
  4577. break;
  4578. case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
  4579. case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
  4580. // Add the module if it is a per-module index (has a source file name).
  4581. if (!SourceFileName.empty())
  4582. addThisModule();
  4583. assert(!SeenValueSymbolTable &&
  4584. "Already read VST when parsing summary block?");
  4585. // We might not have a VST if there were no values in the
  4586. // summary. An empty summary block generated when we are
  4587. // performing ThinLTO compiles so we don't later invoke
  4588. // the regular LTO process on them.
  4589. if (VSTOffset > 0) {
  4590. if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
  4591. return Err;
  4592. SeenValueSymbolTable = true;
  4593. }
  4594. SeenGlobalValSummary = true;
  4595. if (Error Err = parseEntireSummary(Entry.ID))
  4596. return Err;
  4597. break;
  4598. case bitc::MODULE_STRTAB_BLOCK_ID:
  4599. if (Error Err = parseModuleStringTable())
  4600. return Err;
  4601. break;
  4602. }
  4603. continue;
  4604. case BitstreamEntry::Record: {
  4605. Record.clear();
  4606. auto BitCode = Stream.readRecord(Entry.ID, Record);
  4607. switch (BitCode) {
  4608. default:
  4609. break; // Default behavior, ignore unknown content.
  4610. case bitc::MODULE_CODE_VERSION: {
  4611. if (Error Err = parseVersionRecord(Record).takeError())
  4612. return Err;
  4613. break;
  4614. }
  4615. /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
  4616. case bitc::MODULE_CODE_SOURCE_FILENAME: {
  4617. SmallString<128> ValueName;
  4618. if (convertToString(Record, 0, ValueName))
  4619. return error("Invalid record");
  4620. SourceFileName = ValueName.c_str();
  4621. break;
  4622. }
  4623. /// MODULE_CODE_HASH: [5*i32]
  4624. case bitc::MODULE_CODE_HASH: {
  4625. if (Record.size() != 5)
  4626. return error("Invalid hash length " + Twine(Record.size()).str());
  4627. auto &Hash = getThisModule()->second.second;
  4628. int Pos = 0;
  4629. for (auto &Val : Record) {
  4630. assert(!(Val >> 32) && "Unexpected high bits set");
  4631. Hash[Pos++] = Val;
  4632. }
  4633. break;
  4634. }
  4635. /// MODULE_CODE_VSTOFFSET: [offset]
  4636. case bitc::MODULE_CODE_VSTOFFSET:
  4637. if (Record.size() < 1)
  4638. return error("Invalid record");
  4639. // Note that we subtract 1 here because the offset is relative to one
  4640. // word before the start of the identification or module block, which
  4641. // was historically always the start of the regular bitcode header.
  4642. VSTOffset = Record[0] - 1;
  4643. break;
  4644. // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...]
  4645. // v1 FUNCTION: [type, callingconv, isproto, linkage, ...]
  4646. // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...]
  4647. // v2: [strtab offset, strtab size, v1]
  4648. case bitc::MODULE_CODE_GLOBALVAR:
  4649. case bitc::MODULE_CODE_FUNCTION:
  4650. case bitc::MODULE_CODE_ALIAS: {
  4651. StringRef Name;
  4652. ArrayRef<uint64_t> GVRecord;
  4653. std::tie(Name, GVRecord) = readNameFromStrtab(Record);
  4654. if (GVRecord.size() <= 3)
  4655. return error("Invalid record");
  4656. uint64_t RawLinkage = GVRecord[3];
  4657. GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
  4658. if (!UseStrtab) {
  4659. ValueIdToLinkageMap[ValueId++] = Linkage;
  4660. break;
  4661. }
  4662. setValueGUID(ValueId++, Name, Linkage, SourceFileName);
  4663. break;
  4664. }
  4665. }
  4666. }
  4667. continue;
  4668. }
  4669. }
  4670. }
  4671. std::vector<ValueInfo>
  4672. ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
  4673. std::vector<ValueInfo> Ret;
  4674. Ret.reserve(Record.size());
  4675. for (uint64_t RefValueId : Record)
  4676. Ret.push_back(getValueInfoFromValueId(RefValueId).first);
  4677. return Ret;
  4678. }
  4679. std::vector<FunctionSummary::EdgeTy>
  4680. ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
  4681. bool IsOldProfileFormat,
  4682. bool HasProfile, bool HasRelBF) {
  4683. std::vector<FunctionSummary::EdgeTy> Ret;
  4684. Ret.reserve(Record.size());
  4685. for (unsigned I = 0, E = Record.size(); I != E; ++I) {
  4686. CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
  4687. uint64_t RelBF = 0;
  4688. ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;
  4689. if (IsOldProfileFormat) {
  4690. I += 1; // Skip old callsitecount field
  4691. if (HasProfile)
  4692. I += 1; // Skip old profilecount field
  4693. } else if (HasProfile)
  4694. Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]);
  4695. else if (HasRelBF)
  4696. RelBF = Record[++I];
  4697. Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo(Hotness, RelBF)});
  4698. }
  4699. return Ret;
  4700. }
  4701. static void
  4702. parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot,
  4703. WholeProgramDevirtResolution &Wpd) {
  4704. uint64_t ArgNum = Record[Slot++];
  4705. WholeProgramDevirtResolution::ByArg &B =
  4706. Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}];
  4707. Slot += ArgNum;
  4708. B.TheKind =
  4709. static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]);
  4710. B.Info = Record[Slot++];
  4711. B.Byte = Record[Slot++];
  4712. B.Bit = Record[Slot++];
  4713. }
  4714. static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record,
  4715. StringRef Strtab, size_t &Slot,
  4716. TypeIdSummary &TypeId) {
  4717. uint64_t Id = Record[Slot++];
  4718. WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id];
  4719. Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]);
  4720. Wpd.SingleImplName = {Strtab.data() + Record[Slot],
  4721. static_cast<size_t>(Record[Slot + 1])};
  4722. Slot += 2;
  4723. uint64_t ResByArgNum = Record[Slot++];
  4724. for (uint64_t I = 0; I != ResByArgNum; ++I)
  4725. parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd);
  4726. }
  4727. static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record,
  4728. StringRef Strtab,
  4729. ModuleSummaryIndex &TheIndex) {
  4730. size_t Slot = 0;
  4731. TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary(
  4732. {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])});
  4733. Slot += 2;
  4734. TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]);
  4735. TypeId.TTRes.SizeM1BitWidth = Record[Slot++];
  4736. TypeId.TTRes.AlignLog2 = Record[Slot++];
  4737. TypeId.TTRes.SizeM1 = Record[Slot++];
  4738. TypeId.TTRes.BitMask = Record[Slot++];
  4739. TypeId.TTRes.InlineBits = Record[Slot++];
  4740. while (Slot < Record.size())
  4741. parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId);
  4742. }
  4743. static void setImmutableRefs(std::vector<ValueInfo> &Refs, unsigned Count) {
  4744. // Read-only refs are in the end of the refs list.
  4745. for (unsigned RefNo = Refs.size() - Count; RefNo < Refs.size(); ++RefNo)
  4746. Refs[RefNo].setReadOnly();
  4747. }
  4748. // Eagerly parse the entire summary block. This populates the GlobalValueSummary
  4749. // objects in the index.
  4750. Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
  4751. if (Stream.EnterSubBlock(ID))
  4752. return error("Invalid record");
  4753. SmallVector<uint64_t, 64> Record;
  4754. // Parse version
  4755. {
  4756. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  4757. if (Entry.Kind != BitstreamEntry::Record)
  4758. return error("Invalid Summary Block: record for version expected");
  4759. if (Stream.readRecord(Entry.ID, Record) != bitc::FS_VERSION)
  4760. return error("Invalid Summary Block: version expected");
  4761. }
  4762. const uint64_t Version = Record[0];
  4763. const bool IsOldProfileFormat = Version == 1;
  4764. if (Version < 1 || Version > 6)
  4765. return error("Invalid summary version " + Twine(Version) +
  4766. ". Version should be in the range [1-6].");
  4767. Record.clear();
  4768. // Keep around the last seen summary to be used when we see an optional
  4769. // "OriginalName" attachement.
  4770. GlobalValueSummary *LastSeenSummary = nullptr;
  4771. GlobalValue::GUID LastSeenGUID = 0;
  4772. // We can expect to see any number of type ID information records before
  4773. // each function summary records; these variables store the information
  4774. // collected so far so that it can be used to create the summary object.
  4775. std::vector<GlobalValue::GUID> PendingTypeTests;
  4776. std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
  4777. PendingTypeCheckedLoadVCalls;
  4778. std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
  4779. PendingTypeCheckedLoadConstVCalls;
  4780. while (true) {
  4781. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  4782. switch (Entry.Kind) {
  4783. case BitstreamEntry::SubBlock: // Handled for us already.
  4784. case BitstreamEntry::Error:
  4785. return error("Malformed block");
  4786. case BitstreamEntry::EndBlock:
  4787. return Error::success();
  4788. case BitstreamEntry::Record:
  4789. // The interesting case.
  4790. break;
  4791. }
  4792. // Read a record. The record format depends on whether this
  4793. // is a per-module index or a combined index file. In the per-module
  4794. // case the records contain the associated value's ID for correlation
  4795. // with VST entries. In the combined index the correlation is done
  4796. // via the bitcode offset of the summary records (which were saved
  4797. // in the combined index VST entries). The records also contain
  4798. // information used for ThinLTO renaming and importing.
  4799. Record.clear();
  4800. auto BitCode = Stream.readRecord(Entry.ID, Record);
  4801. switch (BitCode) {
  4802. default: // Default behavior: ignore.
  4803. break;
  4804. case bitc::FS_FLAGS: { // [flags]
  4805. uint64_t Flags = Record[0];
  4806. // Scan flags.
  4807. assert(Flags <= 0x1f && "Unexpected bits in flag");
  4808. // 1 bit: WithGlobalValueDeadStripping flag.
  4809. // Set on combined index only.
  4810. if (Flags & 0x1)
  4811. TheIndex.setWithGlobalValueDeadStripping();
  4812. // 1 bit: SkipModuleByDistributedBackend flag.
  4813. // Set on combined index only.
  4814. if (Flags & 0x2)
  4815. TheIndex.setSkipModuleByDistributedBackend();
  4816. // 1 bit: HasSyntheticEntryCounts flag.
  4817. // Set on combined index only.
  4818. if (Flags & 0x4)
  4819. TheIndex.setHasSyntheticEntryCounts();
  4820. // 1 bit: DisableSplitLTOUnit flag.
  4821. // Set on per module indexes. It is up to the client to validate
  4822. // the consistency of this flag across modules being linked.
  4823. if (Flags & 0x8)
  4824. TheIndex.setEnableSplitLTOUnit();
  4825. // 1 bit: PartiallySplitLTOUnits flag.
  4826. // Set on combined index only.
  4827. if (Flags & 0x10)
  4828. TheIndex.setPartiallySplitLTOUnits();
  4829. break;
  4830. }
  4831. case bitc::FS_VALUE_GUID: { // [valueid, refguid]
  4832. uint64_t ValueID = Record[0];
  4833. GlobalValue::GUID RefGUID = Record[1];
  4834. ValueIdToValueInfoMap[ValueID] =
  4835. std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
  4836. break;
  4837. }
  4838. // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
  4839. // numrefs x valueid, n x (valueid)]
  4840. // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
  4841. // numrefs x valueid,
  4842. // n x (valueid, hotness)]
  4843. // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs,
  4844. // numrefs x valueid,
  4845. // n x (valueid, relblockfreq)]
  4846. case bitc::FS_PERMODULE:
  4847. case bitc::FS_PERMODULE_RELBF:
  4848. case bitc::FS_PERMODULE_PROFILE: {
  4849. unsigned ValueID = Record[0];
  4850. uint64_t RawFlags = Record[1];
  4851. unsigned InstCount = Record[2];
  4852. uint64_t RawFunFlags = 0;
  4853. unsigned NumRefs = Record[3];
  4854. unsigned NumImmutableRefs = 0;
  4855. int RefListStartIndex = 4;
  4856. if (Version >= 4) {
  4857. RawFunFlags = Record[3];
  4858. NumRefs = Record[4];
  4859. RefListStartIndex = 5;
  4860. if (Version >= 5) {
  4861. NumImmutableRefs = Record[5];
  4862. RefListStartIndex = 6;
  4863. }
  4864. }
  4865. auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
  4866. // The module path string ref set in the summary must be owned by the
  4867. // index's module string table. Since we don't have a module path
  4868. // string table section in the per-module index, we create a single
  4869. // module path string table entry with an empty (0) ID to take
  4870. // ownership.
  4871. int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
  4872. assert(Record.size() >= RefListStartIndex + NumRefs &&
  4873. "Record size inconsistent with number of references");
  4874. std::vector<ValueInfo> Refs = makeRefList(
  4875. ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
  4876. bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
  4877. bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF);
  4878. std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
  4879. ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
  4880. IsOldProfileFormat, HasProfile, HasRelBF);
  4881. setImmutableRefs(Refs, NumImmutableRefs);
  4882. auto FS = llvm::make_unique<FunctionSummary>(
  4883. Flags, InstCount, getDecodedFFlags(RawFunFlags), /*EntryCount=*/0,
  4884. std::move(Refs), std::move(Calls), std::move(PendingTypeTests),
  4885. std::move(PendingTypeTestAssumeVCalls),
  4886. std::move(PendingTypeCheckedLoadVCalls),
  4887. std::move(PendingTypeTestAssumeConstVCalls),
  4888. std::move(PendingTypeCheckedLoadConstVCalls));
  4889. PendingTypeTests.clear();
  4890. PendingTypeTestAssumeVCalls.clear();
  4891. PendingTypeCheckedLoadVCalls.clear();
  4892. PendingTypeTestAssumeConstVCalls.clear();
  4893. PendingTypeCheckedLoadConstVCalls.clear();
  4894. auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
  4895. FS->setModulePath(getThisModule()->first());
  4896. FS->setOriginalName(VIAndOriginalGUID.second);
  4897. TheIndex.addGlobalValueSummary(VIAndOriginalGUID.first, std::move(FS));
  4898. break;
  4899. }
  4900. // FS_ALIAS: [valueid, flags, valueid]
  4901. // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
  4902. // they expect all aliasee summaries to be available.
  4903. case bitc::FS_ALIAS: {
  4904. unsigned ValueID = Record[0];
  4905. uint64_t RawFlags = Record[1];
  4906. unsigned AliaseeID = Record[2];
  4907. auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
  4908. auto AS = llvm::make_unique<AliasSummary>(Flags);
  4909. // The module path string ref set in the summary must be owned by the
  4910. // index's module string table. Since we don't have a module path
  4911. // string table section in the per-module index, we create a single
  4912. // module path string table entry with an empty (0) ID to take
  4913. // ownership.
  4914. AS->setModulePath(getThisModule()->first());
  4915. auto AliaseeVI = getValueInfoFromValueId(AliaseeID).first;
  4916. auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath);
  4917. if (!AliaseeInModule)
  4918. return error("Alias expects aliasee summary to be parsed");
  4919. AS->setAliasee(AliaseeVI, AliaseeInModule);
  4920. auto GUID = getValueInfoFromValueId(ValueID);
  4921. AS->setOriginalName(GUID.second);
  4922. TheIndex.addGlobalValueSummary(GUID.first, std::move(AS));
  4923. break;
  4924. }
  4925. // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid]
  4926. case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
  4927. unsigned ValueID = Record[0];
  4928. uint64_t RawFlags = Record[1];
  4929. unsigned RefArrayStart = 2;
  4930. GlobalVarSummary::GVarFlags GVF;
  4931. auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
  4932. if (Version >= 5) {
  4933. GVF = getDecodedGVarFlags(Record[2]);
  4934. RefArrayStart = 3;
  4935. }
  4936. std::vector<ValueInfo> Refs =
  4937. makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
  4938. auto FS =
  4939. llvm::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
  4940. FS->setModulePath(getThisModule()->first());
  4941. auto GUID = getValueInfoFromValueId(ValueID);
  4942. FS->setOriginalName(GUID.second);
  4943. TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));
  4944. break;
  4945. }
  4946. // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
  4947. // numrefs x valueid, n x (valueid)]
  4948. // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
  4949. // numrefs x valueid, n x (valueid, hotness)]
  4950. case bitc::FS_COMBINED:
  4951. case bitc::FS_COMBINED_PROFILE: {
  4952. unsigned ValueID = Record[0];
  4953. uint64_t ModuleId = Record[1];
  4954. uint64_t RawFlags = Record[2];
  4955. unsigned InstCount = Record[3];
  4956. uint64_t RawFunFlags = 0;
  4957. uint64_t EntryCount = 0;
  4958. unsigned NumRefs = Record[4];
  4959. unsigned NumImmutableRefs = 0;
  4960. int RefListStartIndex = 5;
  4961. if (Version >= 4) {
  4962. RawFunFlags = Record[4];
  4963. RefListStartIndex = 6;
  4964. size_t NumRefsIndex = 5;
  4965. if (Version >= 5) {
  4966. RefListStartIndex = 7;
  4967. if (Version >= 6) {
  4968. NumRefsIndex = 6;
  4969. EntryCount = Record[5];
  4970. RefListStartIndex = 8;
  4971. }
  4972. NumImmutableRefs = Record[RefListStartIndex - 1];
  4973. }
  4974. NumRefs = Record[NumRefsIndex];
  4975. }
  4976. auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
  4977. int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
  4978. assert(Record.size() >= RefListStartIndex + NumRefs &&
  4979. "Record size inconsistent with number of references");
  4980. std::vector<ValueInfo> Refs = makeRefList(
  4981. ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
  4982. bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
  4983. std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
  4984. ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
  4985. IsOldProfileFormat, HasProfile, false);
  4986. ValueInfo VI = getValueInfoFromValueId(ValueID).first;
  4987. setImmutableRefs(Refs, NumImmutableRefs);
  4988. auto FS = llvm::make_unique<FunctionSummary>(
  4989. Flags, InstCount, getDecodedFFlags(RawFunFlags), EntryCount,
  4990. std::move(Refs), std::move(Edges), std::move(PendingTypeTests),
  4991. std::move(PendingTypeTestAssumeVCalls),
  4992. std::move(PendingTypeCheckedLoadVCalls),
  4993. std::move(PendingTypeTestAssumeConstVCalls),
  4994. std::move(PendingTypeCheckedLoadConstVCalls));
  4995. PendingTypeTests.clear();
  4996. PendingTypeTestAssumeVCalls.clear();
  4997. PendingTypeCheckedLoadVCalls.clear();
  4998. PendingTypeTestAssumeConstVCalls.clear();
  4999. PendingTypeCheckedLoadConstVCalls.clear();
  5000. LastSeenSummary = FS.get();
  5001. LastSeenGUID = VI.getGUID();
  5002. FS->setModulePath(ModuleIdMap[ModuleId]);
  5003. TheIndex.addGlobalValueSummary(VI, std::move(FS));
  5004. break;
  5005. }
  5006. // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
  5007. // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
  5008. // they expect all aliasee summaries to be available.
  5009. case bitc::FS_COMBINED_ALIAS: {
  5010. unsigned ValueID = Record[0];
  5011. uint64_t ModuleId = Record[1];
  5012. uint64_t RawFlags = Record[2];
  5013. unsigned AliaseeValueId = Record[3];
  5014. auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
  5015. auto AS = llvm::make_unique<AliasSummary>(Flags);
  5016. LastSeenSummary = AS.get();
  5017. AS->setModulePath(ModuleIdMap[ModuleId]);
  5018. auto AliaseeVI = getValueInfoFromValueId(AliaseeValueId).first;
  5019. auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath());
  5020. AS->setAliasee(AliaseeVI, AliaseeInModule);
  5021. ValueInfo VI = getValueInfoFromValueId(ValueID).first;
  5022. LastSeenGUID = VI.getGUID();
  5023. TheIndex.addGlobalValueSummary(VI, std::move(AS));
  5024. break;
  5025. }
  5026. // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
  5027. case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
  5028. unsigned ValueID = Record[0];
  5029. uint64_t ModuleId = Record[1];
  5030. uint64_t RawFlags = Record[2];
  5031. unsigned RefArrayStart = 3;
  5032. GlobalVarSummary::GVarFlags GVF;
  5033. auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
  5034. if (Version >= 5) {
  5035. GVF = getDecodedGVarFlags(Record[3]);
  5036. RefArrayStart = 4;
  5037. }
  5038. std::vector<ValueInfo> Refs =
  5039. makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
  5040. auto FS =
  5041. llvm::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
  5042. LastSeenSummary = FS.get();
  5043. FS->setModulePath(ModuleIdMap[ModuleId]);
  5044. ValueInfo VI = getValueInfoFromValueId(ValueID).first;
  5045. LastSeenGUID = VI.getGUID();
  5046. TheIndex.addGlobalValueSummary(VI, std::move(FS));
  5047. break;
  5048. }
  5049. // FS_COMBINED_ORIGINAL_NAME: [original_name]
  5050. case bitc::FS_COMBINED_ORIGINAL_NAME: {
  5051. uint64_t OriginalName = Record[0];
  5052. if (!LastSeenSummary)
  5053. return error("Name attachment that does not follow a combined record");
  5054. LastSeenSummary->setOriginalName(OriginalName);
  5055. TheIndex.addOriginalName(LastSeenGUID, OriginalName);
  5056. // Reset the LastSeenSummary
  5057. LastSeenSummary = nullptr;
  5058. LastSeenGUID = 0;
  5059. break;
  5060. }
  5061. case bitc::FS_TYPE_TESTS:
  5062. assert(PendingTypeTests.empty());
  5063. PendingTypeTests.insert(PendingTypeTests.end(), Record.begin(),
  5064. Record.end());
  5065. break;
  5066. case bitc::FS_TYPE_TEST_ASSUME_VCALLS:
  5067. assert(PendingTypeTestAssumeVCalls.empty());
  5068. for (unsigned I = 0; I != Record.size(); I += 2)
  5069. PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
  5070. break;
  5071. case bitc::FS_TYPE_CHECKED_LOAD_VCALLS:
  5072. assert(PendingTypeCheckedLoadVCalls.empty());
  5073. for (unsigned I = 0; I != Record.size(); I += 2)
  5074. PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
  5075. break;
  5076. case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL:
  5077. PendingTypeTestAssumeConstVCalls.push_back(
  5078. {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
  5079. break;
  5080. case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL:
  5081. PendingTypeCheckedLoadConstVCalls.push_back(
  5082. {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
  5083. break;
  5084. case bitc::FS_CFI_FUNCTION_DEFS: {
  5085. std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs();
  5086. for (unsigned I = 0; I != Record.size(); I += 2)
  5087. CfiFunctionDefs.insert(
  5088. {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
  5089. break;
  5090. }
  5091. case bitc::FS_CFI_FUNCTION_DECLS: {
  5092. std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls();
  5093. for (unsigned I = 0; I != Record.size(); I += 2)
  5094. CfiFunctionDecls.insert(
  5095. {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
  5096. break;
  5097. }
  5098. case bitc::FS_TYPE_ID:
  5099. parseTypeIdSummaryRecord(Record, Strtab, TheIndex);
  5100. break;
  5101. }
  5102. }
  5103. llvm_unreachable("Exit infinite loop");
  5104. }
  5105. // Parse the module string table block into the Index.
  5106. // This populates the ModulePathStringTable map in the index.
  5107. Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
  5108. if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
  5109. return error("Invalid record");
  5110. SmallVector<uint64_t, 64> Record;
  5111. SmallString<128> ModulePath;
  5112. ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;
  5113. while (true) {
  5114. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  5115. switch (Entry.Kind) {
  5116. case BitstreamEntry::SubBlock: // Handled for us already.
  5117. case BitstreamEntry::Error:
  5118. return error("Malformed block");
  5119. case BitstreamEntry::EndBlock:
  5120. return Error::success();
  5121. case BitstreamEntry::Record:
  5122. // The interesting case.
  5123. break;
  5124. }
  5125. Record.clear();
  5126. switch (Stream.readRecord(Entry.ID, Record)) {
  5127. default: // Default behavior: ignore.
  5128. break;
  5129. case bitc::MST_CODE_ENTRY: {
  5130. // MST_ENTRY: [modid, namechar x N]
  5131. uint64_t ModuleId = Record[0];
  5132. if (convertToString(Record, 1, ModulePath))
  5133. return error("Invalid record");
  5134. LastSeenModule = TheIndex.addModule(ModulePath, ModuleId);
  5135. ModuleIdMap[ModuleId] = LastSeenModule->first();
  5136. ModulePath.clear();
  5137. break;
  5138. }
  5139. /// MST_CODE_HASH: [5*i32]
  5140. case bitc::MST_CODE_HASH: {
  5141. if (Record.size() != 5)
  5142. return error("Invalid hash length " + Twine(Record.size()).str());
  5143. if (!LastSeenModule)
  5144. return error("Invalid hash that does not follow a module path");
  5145. int Pos = 0;
  5146. for (auto &Val : Record) {
  5147. assert(!(Val >> 32) && "Unexpected high bits set");
  5148. LastSeenModule->second.second[Pos++] = Val;
  5149. }
  5150. // Reset LastSeenModule to avoid overriding the hash unexpectedly.
  5151. LastSeenModule = nullptr;
  5152. break;
  5153. }
  5154. }
  5155. }
  5156. llvm_unreachable("Exit infinite loop");
  5157. }
  5158. namespace {
  5159. // FIXME: This class is only here to support the transition to llvm::Error. It
  5160. // will be removed once this transition is complete. Clients should prefer to
  5161. // deal with the Error value directly, rather than converting to error_code.
  5162. class BitcodeErrorCategoryType : public std::error_category {
  5163. const char *name() const noexcept override {
  5164. return "llvm.bitcode";
  5165. }
  5166. std::string message(int IE) const override {
  5167. BitcodeError E = static_cast<BitcodeError>(IE);
  5168. switch (E) {
  5169. case BitcodeError::CorruptedBitcode:
  5170. return "Corrupted bitcode";
  5171. }
  5172. llvm_unreachable("Unknown error type!");
  5173. }
  5174. };
  5175. } // end anonymous namespace
  5176. static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
  5177. const std::error_category &llvm::BitcodeErrorCategory() {
  5178. return *ErrorCategory;
  5179. }
  5180. static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream,
  5181. unsigned Block, unsigned RecordID) {
  5182. if (Stream.EnterSubBlock(Block))
  5183. return error("Invalid record");
  5184. StringRef Strtab;
  5185. while (true) {
  5186. BitstreamEntry Entry = Stream.advance();
  5187. switch (Entry.Kind) {
  5188. case BitstreamEntry::EndBlock:
  5189. return Strtab;
  5190. case BitstreamEntry::Error:
  5191. return error("Malformed block");
  5192. case BitstreamEntry::SubBlock:
  5193. if (Stream.SkipBlock())
  5194. return error("Malformed block");
  5195. break;
  5196. case BitstreamEntry::Record:
  5197. StringRef Blob;
  5198. SmallVector<uint64_t, 1> Record;
  5199. if (Stream.readRecord(Entry.ID, Record, &Blob) == RecordID)
  5200. Strtab = Blob;
  5201. break;
  5202. }
  5203. }
  5204. }
  5205. //===----------------------------------------------------------------------===//
  5206. // External interface
  5207. //===----------------------------------------------------------------------===//
  5208. Expected<std::vector<BitcodeModule>>
  5209. llvm::getBitcodeModuleList(MemoryBufferRef Buffer) {
  5210. auto FOrErr = getBitcodeFileContents(Buffer);
  5211. if (!FOrErr)
  5212. return FOrErr.takeError();
  5213. return std::move(FOrErr->Mods);
  5214. }
  5215. Expected<BitcodeFileContents>
  5216. llvm::getBitcodeFileContents(MemoryBufferRef Buffer) {
  5217. Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
  5218. if (!StreamOrErr)
  5219. return StreamOrErr.takeError();
  5220. BitstreamCursor &Stream = *StreamOrErr;
  5221. BitcodeFileContents F;
  5222. while (true) {
  5223. uint64_t BCBegin = Stream.getCurrentByteNo();
  5224. // We may be consuming bitcode from a client that leaves garbage at the end
  5225. // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
  5226. // the end that there cannot possibly be another module, stop looking.
  5227. if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
  5228. return F;
  5229. BitstreamEntry Entry = Stream.advance();
  5230. switch (Entry.Kind) {
  5231. case BitstreamEntry::EndBlock:
  5232. case BitstreamEntry::Error:
  5233. return error("Malformed block");
  5234. case BitstreamEntry::SubBlock: {
  5235. uint64_t IdentificationBit = -1ull;
  5236. if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
  5237. IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
  5238. if (Stream.SkipBlock())
  5239. return error("Malformed block");
  5240. Entry = Stream.advance();
  5241. if (Entry.Kind != BitstreamEntry::SubBlock ||
  5242. Entry.ID != bitc::MODULE_BLOCK_ID)
  5243. return error("Malformed block");
  5244. }
  5245. if (Entry.ID == bitc::MODULE_BLOCK_ID) {
  5246. uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
  5247. if (Stream.SkipBlock())
  5248. return error("Malformed block");
  5249. F.Mods.push_back({Stream.getBitcodeBytes().slice(
  5250. BCBegin, Stream.getCurrentByteNo() - BCBegin),
  5251. Buffer.getBufferIdentifier(), IdentificationBit,
  5252. ModuleBit});
  5253. continue;
  5254. }
  5255. if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
  5256. Expected<StringRef> Strtab =
  5257. readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB);
  5258. if (!Strtab)
  5259. return Strtab.takeError();
  5260. // This string table is used by every preceding bitcode module that does
  5261. // not have its own string table. A bitcode file may have multiple
  5262. // string tables if it was created by binary concatenation, for example
  5263. // with "llvm-cat -b".
  5264. for (auto I = F.Mods.rbegin(), E = F.Mods.rend(); I != E; ++I) {
  5265. if (!I->Strtab.empty())
  5266. break;
  5267. I->Strtab = *Strtab;
  5268. }
  5269. // Similarly, the string table is used by every preceding symbol table;
  5270. // normally there will be just one unless the bitcode file was created
  5271. // by binary concatenation.
  5272. if (!F.Symtab.empty() && F.StrtabForSymtab.empty())
  5273. F.StrtabForSymtab = *Strtab;
  5274. continue;
  5275. }
  5276. if (Entry.ID == bitc::SYMTAB_BLOCK_ID) {
  5277. Expected<StringRef> SymtabOrErr =
  5278. readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB);
  5279. if (!SymtabOrErr)
  5280. return SymtabOrErr.takeError();
  5281. // We can expect the bitcode file to have multiple symbol tables if it
  5282. // was created by binary concatenation. In that case we silently
  5283. // ignore any subsequent symbol tables, which is fine because this is a
  5284. // low level function. The client is expected to notice that the number
  5285. // of modules in the symbol table does not match the number of modules
  5286. // in the input file and regenerate the symbol table.
  5287. if (F.Symtab.empty())
  5288. F.Symtab = *SymtabOrErr;
  5289. continue;
  5290. }
  5291. if (Stream.SkipBlock())
  5292. return error("Malformed block");
  5293. continue;
  5294. }
  5295. case BitstreamEntry::Record:
  5296. Stream.skipRecord(Entry.ID);
  5297. continue;
  5298. }
  5299. }
  5300. }
  5301. /// Get a lazy one-at-time loading module from bitcode.
  5302. ///
  5303. /// This isn't always used in a lazy context. In particular, it's also used by
  5304. /// \a parseModule(). If this is truly lazy, then we need to eagerly pull
  5305. /// in forward-referenced functions from block address references.
  5306. ///
  5307. /// \param[in] MaterializeAll Set to \c true if we should materialize
  5308. /// everything.
  5309. Expected<std::unique_ptr<Module>>
  5310. BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
  5311. bool ShouldLazyLoadMetadata, bool IsImporting) {
  5312. BitstreamCursor Stream(Buffer);
  5313. std::string ProducerIdentification;
  5314. if (IdentificationBit != -1ull) {
  5315. Stream.JumpToBit(IdentificationBit);
  5316. Expected<std::string> ProducerIdentificationOrErr =
  5317. readIdentificationBlock(Stream);
  5318. if (!ProducerIdentificationOrErr)
  5319. return ProducerIdentificationOrErr.takeError();
  5320. ProducerIdentification = *ProducerIdentificationOrErr;
  5321. }
  5322. Stream.JumpToBit(ModuleBit);
  5323. auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
  5324. Context);
  5325. std::unique_ptr<Module> M =
  5326. llvm::make_unique<Module>(ModuleIdentifier, Context);
  5327. M->setMaterializer(R);
  5328. // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
  5329. if (Error Err =
  5330. R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata, IsImporting))
  5331. return std::move(Err);
  5332. if (MaterializeAll) {
  5333. // Read in the entire module, and destroy the BitcodeReader.
  5334. if (Error Err = M->materializeAll())
  5335. return std::move(Err);
  5336. } else {
  5337. // Resolve forward references from blockaddresses.
  5338. if (Error Err = R->materializeForwardReferencedFunctions())
  5339. return std::move(Err);
  5340. }
  5341. return std::move(M);
  5342. }
  5343. Expected<std::unique_ptr<Module>>
  5344. BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
  5345. bool IsImporting) {
  5346. return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting);
  5347. }
  5348. // Parse the specified bitcode buffer and merge the index into CombinedIndex.
  5349. // We don't use ModuleIdentifier here because the client may need to control the
  5350. // module path used in the combined summary (e.g. when reading summaries for
  5351. // regular LTO modules).
  5352. Error BitcodeModule::readSummary(ModuleSummaryIndex &CombinedIndex,
  5353. StringRef ModulePath, uint64_t ModuleId) {
  5354. BitstreamCursor Stream(Buffer);
  5355. Stream.JumpToBit(ModuleBit);
  5356. ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
  5357. ModulePath, ModuleId);
  5358. return R.parseModule();
  5359. }
  5360. // Parse the specified bitcode buffer, returning the function info index.
  5361. Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() {
  5362. BitstreamCursor Stream(Buffer);
  5363. Stream.JumpToBit(ModuleBit);
  5364. auto Index = llvm::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
  5365. ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
  5366. ModuleIdentifier, 0);
  5367. if (Error Err = R.parseModule())
  5368. return std::move(Err);
  5369. return std::move(Index);
  5370. }
  5371. static Expected<bool> getEnableSplitLTOUnitFlag(BitstreamCursor &Stream,
  5372. unsigned ID) {
  5373. if (Stream.EnterSubBlock(ID))
  5374. return error("Invalid record");
  5375. SmallVector<uint64_t, 64> Record;
  5376. while (true) {
  5377. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  5378. switch (Entry.Kind) {
  5379. case BitstreamEntry::SubBlock: // Handled for us already.
  5380. case BitstreamEntry::Error:
  5381. return error("Malformed block");
  5382. case BitstreamEntry::EndBlock:
  5383. // If no flags record found, conservatively return true to mimic
  5384. // behavior before this flag was added.
  5385. return true;
  5386. case BitstreamEntry::Record:
  5387. // The interesting case.
  5388. break;
  5389. }
  5390. // Look for the FS_FLAGS record.
  5391. Record.clear();
  5392. auto BitCode = Stream.readRecord(Entry.ID, Record);
  5393. switch (BitCode) {
  5394. default: // Default behavior: ignore.
  5395. break;
  5396. case bitc::FS_FLAGS: { // [flags]
  5397. uint64_t Flags = Record[0];
  5398. // Scan flags.
  5399. assert(Flags <= 0x1f && "Unexpected bits in flag");
  5400. return Flags & 0x8;
  5401. }
  5402. }
  5403. }
  5404. llvm_unreachable("Exit infinite loop");
  5405. }
  5406. // Check if the given bitcode buffer contains a global value summary block.
  5407. Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() {
  5408. BitstreamCursor Stream(Buffer);
  5409. Stream.JumpToBit(ModuleBit);
  5410. if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
  5411. return error("Invalid record");
  5412. while (true) {
  5413. BitstreamEntry Entry = Stream.advance();
  5414. switch (Entry.Kind) {
  5415. case BitstreamEntry::Error:
  5416. return error("Malformed block");
  5417. case BitstreamEntry::EndBlock:
  5418. return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false,
  5419. /*EnableSplitLTOUnit=*/false};
  5420. case BitstreamEntry::SubBlock:
  5421. if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
  5422. Expected<bool> EnableSplitLTOUnit =
  5423. getEnableSplitLTOUnitFlag(Stream, Entry.ID);
  5424. if (!EnableSplitLTOUnit)
  5425. return EnableSplitLTOUnit.takeError();
  5426. return BitcodeLTOInfo{/*IsThinLTO=*/true, /*HasSummary=*/true,
  5427. *EnableSplitLTOUnit};
  5428. }
  5429. if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) {
  5430. Expected<bool> EnableSplitLTOUnit =
  5431. getEnableSplitLTOUnitFlag(Stream, Entry.ID);
  5432. if (!EnableSplitLTOUnit)
  5433. return EnableSplitLTOUnit.takeError();
  5434. return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/true,
  5435. *EnableSplitLTOUnit};
  5436. }
  5437. // Ignore other sub-blocks.
  5438. if (Stream.SkipBlock())
  5439. return error("Malformed block");
  5440. continue;
  5441. case BitstreamEntry::Record:
  5442. Stream.skipRecord(Entry.ID);
  5443. continue;
  5444. }
  5445. }
  5446. }
  5447. static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) {
  5448. Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer);
  5449. if (!MsOrErr)
  5450. return MsOrErr.takeError();
  5451. if (MsOrErr->size() != 1)
  5452. return error("Expected a single module");
  5453. return (*MsOrErr)[0];
  5454. }
  5455. Expected<std::unique_ptr<Module>>
  5456. llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context,
  5457. bool ShouldLazyLoadMetadata, bool IsImporting) {
  5458. Expected<BitcodeModule> BM = getSingleModule(Buffer);
  5459. if (!BM)
  5460. return BM.takeError();
  5461. return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting);
  5462. }
  5463. Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule(
  5464. std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
  5465. bool ShouldLazyLoadMetadata, bool IsImporting) {
  5466. auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
  5467. IsImporting);
  5468. if (MOrErr)
  5469. (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
  5470. return MOrErr;
  5471. }
  5472. Expected<std::unique_ptr<Module>>
  5473. BitcodeModule::parseModule(LLVMContext &Context) {
  5474. return getModuleImpl(Context, true, false, false);
  5475. // TODO: Restore the use-lists to the in-memory state when the bitcode was
  5476. // written. We must defer until the Module has been fully materialized.
  5477. }
  5478. Expected<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
  5479. LLVMContext &Context) {
  5480. Expected<BitcodeModule> BM = getSingleModule(Buffer);
  5481. if (!BM)
  5482. return BM.takeError();
  5483. return BM->parseModule(Context);
  5484. }
  5485. Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {
  5486. Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
  5487. if (!StreamOrErr)
  5488. return StreamOrErr.takeError();
  5489. return readTriple(*StreamOrErr);
  5490. }
  5491. Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {
  5492. Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
  5493. if (!StreamOrErr)
  5494. return StreamOrErr.takeError();
  5495. return hasObjCCategory(*StreamOrErr);
  5496. }
  5497. Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {
  5498. Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
  5499. if (!StreamOrErr)
  5500. return StreamOrErr.takeError();
  5501. return readIdentificationCode(*StreamOrErr);
  5502. }
  5503. Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer,
  5504. ModuleSummaryIndex &CombinedIndex,
  5505. uint64_t ModuleId) {
  5506. Expected<BitcodeModule> BM = getSingleModule(Buffer);
  5507. if (!BM)
  5508. return BM.takeError();
  5509. return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId);
  5510. }
  5511. Expected<std::unique_ptr<ModuleSummaryIndex>>
  5512. llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) {
  5513. Expected<BitcodeModule> BM = getSingleModule(Buffer);
  5514. if (!BM)
  5515. return BM.takeError();
  5516. return BM->getSummary();
  5517. }
  5518. Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) {
  5519. Expected<BitcodeModule> BM = getSingleModule(Buffer);
  5520. if (!BM)
  5521. return BM.takeError();
  5522. return BM->getLTOInfo();
  5523. }
  5524. Expected<std::unique_ptr<ModuleSummaryIndex>>
  5525. llvm::getModuleSummaryIndexForFile(StringRef Path,
  5526. bool IgnoreEmptyThinLTOIndexFile) {
  5527. ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
  5528. MemoryBuffer::getFileOrSTDIN(Path);
  5529. if (!FileOrErr)
  5530. return errorCodeToError(FileOrErr.getError());
  5531. if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
  5532. return nullptr;
  5533. return getModuleSummaryIndex(**FileOrErr);
  5534. }