BitcodeReader.cpp 222 KB

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