BitcodeReader.cpp 212 KB

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