BitcodeReader.cpp 238 KB

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