BitcodeReader.cpp 222 KB

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