BitcodeReader.cpp 240 KB

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