SelectionDAGBuilder.cpp 309 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893
  1. //===-- SelectionDAGBuilder.cpp - Selection-DAG building ------------------===//
  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. //
  10. // This implements routines for translating from LLVM IR into SelectionDAG IR.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "SelectionDAGBuilder.h"
  14. #include "SDNodeDbgValue.h"
  15. #include "llvm/ADT/BitVector.h"
  16. #include "llvm/ADT/Optional.h"
  17. #include "llvm/ADT/SmallSet.h"
  18. #include "llvm/ADT/Statistic.h"
  19. #include "llvm/Analysis/AliasAnalysis.h"
  20. #include "llvm/Analysis/BranchProbabilityInfo.h"
  21. #include "llvm/Analysis/ConstantFolding.h"
  22. #include "llvm/Analysis/ValueTracking.h"
  23. #include "llvm/CodeGen/Analysis.h"
  24. #include "llvm/CodeGen/FastISel.h"
  25. #include "llvm/CodeGen/FunctionLoweringInfo.h"
  26. #include "llvm/CodeGen/GCMetadata.h"
  27. #include "llvm/CodeGen/GCStrategy.h"
  28. #include "llvm/CodeGen/MachineFrameInfo.h"
  29. #include "llvm/CodeGen/MachineFunction.h"
  30. #include "llvm/CodeGen/MachineInstrBuilder.h"
  31. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  32. #include "llvm/CodeGen/MachineModuleInfo.h"
  33. #include "llvm/CodeGen/MachineRegisterInfo.h"
  34. #include "llvm/CodeGen/SelectionDAG.h"
  35. #include "llvm/CodeGen/StackMaps.h"
  36. #include "llvm/IR/CallingConv.h"
  37. #include "llvm/IR/Constants.h"
  38. #include "llvm/IR/DataLayout.h"
  39. #include "llvm/IR/DebugInfo.h"
  40. #include "llvm/IR/DerivedTypes.h"
  41. #include "llvm/IR/Function.h"
  42. #include "llvm/IR/GlobalVariable.h"
  43. #include "llvm/IR/InlineAsm.h"
  44. #include "llvm/IR/Instructions.h"
  45. #include "llvm/IR/IntrinsicInst.h"
  46. #include "llvm/IR/Intrinsics.h"
  47. #include "llvm/IR/LLVMContext.h"
  48. #include "llvm/IR/Module.h"
  49. #include "llvm/IR/Statepoint.h"
  50. #include "llvm/Support/CommandLine.h"
  51. #include "llvm/Support/Debug.h"
  52. #include "llvm/Support/ErrorHandling.h"
  53. #include "llvm/Support/MathExtras.h"
  54. #include "llvm/Support/raw_ostream.h"
  55. #include "llvm/Target/TargetFrameLowering.h"
  56. #include "llvm/Target/TargetInstrInfo.h"
  57. #include "llvm/Target/TargetIntrinsicInfo.h"
  58. #include "llvm/Target/TargetLibraryInfo.h"
  59. #include "llvm/Target/TargetLowering.h"
  60. #include "llvm/Target/TargetOptions.h"
  61. #include "llvm/Target/TargetSelectionDAGInfo.h"
  62. #include "llvm/Target/TargetSubtargetInfo.h"
  63. #include <algorithm>
  64. using namespace llvm;
  65. #define DEBUG_TYPE "isel"
  66. /// LimitFloatPrecision - Generate low-precision inline sequences for
  67. /// some float libcalls (6, 8 or 12 bits).
  68. static unsigned LimitFloatPrecision;
  69. static cl::opt<unsigned, true>
  70. LimitFPPrecision("limit-float-precision",
  71. cl::desc("Generate low-precision inline sequences "
  72. "for some float libcalls"),
  73. cl::location(LimitFloatPrecision),
  74. cl::init(0));
  75. // Limit the width of DAG chains. This is important in general to prevent
  76. // prevent DAG-based analysis from blowing up. For example, alias analysis and
  77. // load clustering may not complete in reasonable time. It is difficult to
  78. // recognize and avoid this situation within each individual analysis, and
  79. // future analyses are likely to have the same behavior. Limiting DAG width is
  80. // the safe approach, and will be especially important with global DAGs.
  81. //
  82. // MaxParallelChains default is arbitrarily high to avoid affecting
  83. // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
  84. // sequence over this should have been converted to llvm.memcpy by the
  85. // frontend. It easy to induce this behavior with .ll code such as:
  86. // %buffer = alloca [4096 x i8]
  87. // %data = load [4096 x i8]* %argPtr
  88. // store [4096 x i8] %data, [4096 x i8]* %buffer
  89. static const unsigned MaxParallelChains = 64;
  90. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
  91. const SDValue *Parts, unsigned NumParts,
  92. MVT PartVT, EVT ValueVT, const Value *V);
  93. /// getCopyFromParts - Create a value that contains the specified legal parts
  94. /// combined into the value they represent. If the parts combine to a type
  95. /// larger then ValueVT then AssertOp can be used to specify whether the extra
  96. /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
  97. /// (ISD::AssertSext).
  98. static SDValue getCopyFromParts(SelectionDAG &DAG, SDLoc DL,
  99. const SDValue *Parts,
  100. unsigned NumParts, MVT PartVT, EVT ValueVT,
  101. const Value *V,
  102. ISD::NodeType AssertOp = ISD::DELETED_NODE) {
  103. if (ValueVT.isVector())
  104. return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
  105. PartVT, ValueVT, V);
  106. assert(NumParts > 0 && "No parts to assemble!");
  107. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  108. SDValue Val = Parts[0];
  109. if (NumParts > 1) {
  110. // Assemble the value from multiple parts.
  111. if (ValueVT.isInteger()) {
  112. unsigned PartBits = PartVT.getSizeInBits();
  113. unsigned ValueBits = ValueVT.getSizeInBits();
  114. // Assemble the power of 2 part.
  115. unsigned RoundParts = NumParts & (NumParts - 1) ?
  116. 1 << Log2_32(NumParts) : NumParts;
  117. unsigned RoundBits = PartBits * RoundParts;
  118. EVT RoundVT = RoundBits == ValueBits ?
  119. ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
  120. SDValue Lo, Hi;
  121. EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
  122. if (RoundParts > 2) {
  123. Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
  124. PartVT, HalfVT, V);
  125. Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
  126. RoundParts / 2, PartVT, HalfVT, V);
  127. } else {
  128. Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
  129. Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
  130. }
  131. if (TLI.isBigEndian())
  132. std::swap(Lo, Hi);
  133. Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
  134. if (RoundParts < NumParts) {
  135. // Assemble the trailing non-power-of-2 part.
  136. unsigned OddParts = NumParts - RoundParts;
  137. EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
  138. Hi = getCopyFromParts(DAG, DL,
  139. Parts + RoundParts, OddParts, PartVT, OddVT, V);
  140. // Combine the round and odd parts.
  141. Lo = Val;
  142. if (TLI.isBigEndian())
  143. std::swap(Lo, Hi);
  144. EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  145. Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
  146. Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
  147. DAG.getConstant(Lo.getValueType().getSizeInBits(),
  148. TLI.getPointerTy()));
  149. Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
  150. Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
  151. }
  152. } else if (PartVT.isFloatingPoint()) {
  153. // FP split into multiple FP parts (for ppcf128)
  154. assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
  155. "Unexpected split");
  156. SDValue Lo, Hi;
  157. Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
  158. Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
  159. if (TLI.hasBigEndianPartOrdering(ValueVT))
  160. std::swap(Lo, Hi);
  161. Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
  162. } else {
  163. // FP split into integer parts (soft fp)
  164. assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
  165. !PartVT.isVector() && "Unexpected split");
  166. EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  167. Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
  168. }
  169. }
  170. // There is now one part, held in Val. Correct it to match ValueVT.
  171. EVT PartEVT = Val.getValueType();
  172. if (PartEVT == ValueVT)
  173. return Val;
  174. if (PartEVT.isInteger() && ValueVT.isInteger()) {
  175. if (ValueVT.bitsLT(PartEVT)) {
  176. // For a truncate, see if we have any information to
  177. // indicate whether the truncated bits will always be
  178. // zero or sign-extension.
  179. if (AssertOp != ISD::DELETED_NODE)
  180. Val = DAG.getNode(AssertOp, DL, PartEVT, Val,
  181. DAG.getValueType(ValueVT));
  182. return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  183. }
  184. return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
  185. }
  186. if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  187. // FP_ROUND's are always exact here.
  188. if (ValueVT.bitsLT(Val.getValueType()))
  189. return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val,
  190. DAG.getTargetConstant(1, TLI.getPointerTy()));
  191. return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
  192. }
  193. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
  194. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  195. llvm_unreachable("Unknown mismatch!");
  196. }
  197. static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
  198. const Twine &ErrMsg) {
  199. const Instruction *I = dyn_cast_or_null<Instruction>(V);
  200. if (!V)
  201. return Ctx.emitError(ErrMsg);
  202. const char *AsmError = ", possible invalid constraint for vector type";
  203. if (const CallInst *CI = dyn_cast<CallInst>(I))
  204. if (isa<InlineAsm>(CI->getCalledValue()))
  205. return Ctx.emitError(I, ErrMsg + AsmError);
  206. return Ctx.emitError(I, ErrMsg);
  207. }
  208. /// getCopyFromPartsVector - Create a value that contains the specified legal
  209. /// parts combined into the value they represent. If the parts combine to a
  210. /// type larger then ValueVT then AssertOp can be used to specify whether the
  211. /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
  212. /// ValueVT (ISD::AssertSext).
  213. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
  214. const SDValue *Parts, unsigned NumParts,
  215. MVT PartVT, EVT ValueVT, const Value *V) {
  216. assert(ValueVT.isVector() && "Not a vector value");
  217. assert(NumParts > 0 && "No parts to assemble!");
  218. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  219. SDValue Val = Parts[0];
  220. // Handle a multi-element vector.
  221. if (NumParts > 1) {
  222. EVT IntermediateVT;
  223. MVT RegisterVT;
  224. unsigned NumIntermediates;
  225. unsigned NumRegs =
  226. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  227. NumIntermediates, RegisterVT);
  228. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  229. NumParts = NumRegs; // Silence a compiler warning.
  230. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  231. assert(RegisterVT == Parts[0].getSimpleValueType() &&
  232. "Part type doesn't match part!");
  233. // Assemble the parts into intermediate operands.
  234. SmallVector<SDValue, 8> Ops(NumIntermediates);
  235. if (NumIntermediates == NumParts) {
  236. // If the register was not expanded, truncate or copy the value,
  237. // as appropriate.
  238. for (unsigned i = 0; i != NumParts; ++i)
  239. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
  240. PartVT, IntermediateVT, V);
  241. } else if (NumParts > 0) {
  242. // If the intermediate type was expanded, build the intermediate
  243. // operands from the parts.
  244. assert(NumParts % NumIntermediates == 0 &&
  245. "Must expand into a divisible number of parts!");
  246. unsigned Factor = NumParts / NumIntermediates;
  247. for (unsigned i = 0; i != NumIntermediates; ++i)
  248. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
  249. PartVT, IntermediateVT, V);
  250. }
  251. // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
  252. // intermediate operands.
  253. Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
  254. : ISD::BUILD_VECTOR,
  255. DL, ValueVT, Ops);
  256. }
  257. // There is now one part, held in Val. Correct it to match ValueVT.
  258. EVT PartEVT = Val.getValueType();
  259. if (PartEVT == ValueVT)
  260. return Val;
  261. if (PartEVT.isVector()) {
  262. // If the element type of the source/dest vectors are the same, but the
  263. // parts vector has more elements than the value vector, then we have a
  264. // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
  265. // elements we want.
  266. if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
  267. assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
  268. "Cannot narrow, it would be a lossy transformation");
  269. return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
  270. DAG.getConstant(0, TLI.getVectorIdxTy()));
  271. }
  272. // Vector/Vector bitcast.
  273. if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
  274. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  275. assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
  276. "Cannot handle this kind of promotion");
  277. // Promoted vector extract
  278. bool Smaller = ValueVT.bitsLE(PartEVT);
  279. return DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
  280. DL, ValueVT, Val);
  281. }
  282. // Trivial bitcast if the types are the same size and the destination
  283. // vector type is legal.
  284. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
  285. TLI.isTypeLegal(ValueVT))
  286. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  287. // Handle cases such as i8 -> <1 x i1>
  288. if (ValueVT.getVectorNumElements() != 1) {
  289. diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
  290. "non-trivial scalar-to-vector conversion");
  291. return DAG.getUNDEF(ValueVT);
  292. }
  293. if (ValueVT.getVectorNumElements() == 1 &&
  294. ValueVT.getVectorElementType() != PartEVT) {
  295. bool Smaller = ValueVT.bitsLE(PartEVT);
  296. Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
  297. DL, ValueVT.getScalarType(), Val);
  298. }
  299. return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
  300. }
  301. static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc dl,
  302. SDValue Val, SDValue *Parts, unsigned NumParts,
  303. MVT PartVT, const Value *V);
  304. /// getCopyToParts - Create a series of nodes that contain the specified value
  305. /// split into legal parts. If the parts contain more bits than Val, then, for
  306. /// integers, ExtendKind can be used to specify how to generate the extra bits.
  307. static void getCopyToParts(SelectionDAG &DAG, SDLoc DL,
  308. SDValue Val, SDValue *Parts, unsigned NumParts,
  309. MVT PartVT, const Value *V,
  310. ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
  311. EVT ValueVT = Val.getValueType();
  312. // Handle the vector case separately.
  313. if (ValueVT.isVector())
  314. return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V);
  315. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  316. unsigned PartBits = PartVT.getSizeInBits();
  317. unsigned OrigNumParts = NumParts;
  318. assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
  319. if (NumParts == 0)
  320. return;
  321. assert(!ValueVT.isVector() && "Vector case handled elsewhere");
  322. EVT PartEVT = PartVT;
  323. if (PartEVT == ValueVT) {
  324. assert(NumParts == 1 && "No-op copy with multiple parts!");
  325. Parts[0] = Val;
  326. return;
  327. }
  328. if (NumParts * PartBits > ValueVT.getSizeInBits()) {
  329. // If the parts cover more bits than the value has, promote the value.
  330. if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  331. assert(NumParts == 1 && "Do not know what to promote to!");
  332. Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
  333. } else {
  334. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  335. ValueVT.isInteger() &&
  336. "Unknown mismatch!");
  337. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  338. Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
  339. if (PartVT == MVT::x86mmx)
  340. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  341. }
  342. } else if (PartBits == ValueVT.getSizeInBits()) {
  343. // Different types of the same size.
  344. assert(NumParts == 1 && PartEVT != ValueVT);
  345. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  346. } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
  347. // If the parts cover less bits than value has, truncate the value.
  348. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  349. ValueVT.isInteger() &&
  350. "Unknown mismatch!");
  351. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  352. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  353. if (PartVT == MVT::x86mmx)
  354. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  355. }
  356. // The value may have changed - recompute ValueVT.
  357. ValueVT = Val.getValueType();
  358. assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
  359. "Failed to tile the value with PartVT!");
  360. if (NumParts == 1) {
  361. if (PartEVT != ValueVT)
  362. diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
  363. "scalar-to-vector conversion failed");
  364. Parts[0] = Val;
  365. return;
  366. }
  367. // Expand the value into multiple parts.
  368. if (NumParts & (NumParts - 1)) {
  369. // The number of parts is not a power of 2. Split off and copy the tail.
  370. assert(PartVT.isInteger() && ValueVT.isInteger() &&
  371. "Do not know what to expand to!");
  372. unsigned RoundParts = 1 << Log2_32(NumParts);
  373. unsigned RoundBits = RoundParts * PartBits;
  374. unsigned OddParts = NumParts - RoundParts;
  375. SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
  376. DAG.getIntPtrConstant(RoundBits));
  377. getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
  378. if (TLI.isBigEndian())
  379. // The odd parts were reversed by getCopyToParts - unreverse them.
  380. std::reverse(Parts + RoundParts, Parts + NumParts);
  381. NumParts = RoundParts;
  382. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  383. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  384. }
  385. // The number of parts is a power of 2. Repeatedly bisect the value using
  386. // EXTRACT_ELEMENT.
  387. Parts[0] = DAG.getNode(ISD::BITCAST, DL,
  388. EVT::getIntegerVT(*DAG.getContext(),
  389. ValueVT.getSizeInBits()),
  390. Val);
  391. for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
  392. for (unsigned i = 0; i < NumParts; i += StepSize) {
  393. unsigned ThisBits = StepSize * PartBits / 2;
  394. EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
  395. SDValue &Part0 = Parts[i];
  396. SDValue &Part1 = Parts[i+StepSize/2];
  397. Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  398. ThisVT, Part0, DAG.getIntPtrConstant(1));
  399. Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  400. ThisVT, Part0, DAG.getIntPtrConstant(0));
  401. if (ThisBits == PartBits && ThisVT != PartVT) {
  402. Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
  403. Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
  404. }
  405. }
  406. }
  407. if (TLI.isBigEndian())
  408. std::reverse(Parts, Parts + OrigNumParts);
  409. }
  410. /// getCopyToPartsVector - Create a series of nodes that contain the specified
  411. /// value split into legal parts.
  412. static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc DL,
  413. SDValue Val, SDValue *Parts, unsigned NumParts,
  414. MVT PartVT, const Value *V) {
  415. EVT ValueVT = Val.getValueType();
  416. assert(ValueVT.isVector() && "Not a vector");
  417. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  418. if (NumParts == 1) {
  419. EVT PartEVT = PartVT;
  420. if (PartEVT == ValueVT) {
  421. // Nothing to do.
  422. } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
  423. // Bitconvert vector->vector case.
  424. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  425. } else if (PartVT.isVector() &&
  426. PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
  427. PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
  428. EVT ElementVT = PartVT.getVectorElementType();
  429. // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
  430. // undef elements.
  431. SmallVector<SDValue, 16> Ops;
  432. for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
  433. Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
  434. ElementVT, Val, DAG.getConstant(i,
  435. TLI.getVectorIdxTy())));
  436. for (unsigned i = ValueVT.getVectorNumElements(),
  437. e = PartVT.getVectorNumElements(); i != e; ++i)
  438. Ops.push_back(DAG.getUNDEF(ElementVT));
  439. Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, Ops);
  440. // FIXME: Use CONCAT for 2x -> 4x.
  441. //SDValue UndefElts = DAG.getUNDEF(VectorTy);
  442. //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
  443. } else if (PartVT.isVector() &&
  444. PartEVT.getVectorElementType().bitsGE(
  445. ValueVT.getVectorElementType()) &&
  446. PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
  447. // Promoted vector extract
  448. bool Smaller = PartEVT.bitsLE(ValueVT);
  449. Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
  450. DL, PartVT, Val);
  451. } else{
  452. // Vector -> scalar conversion.
  453. assert(ValueVT.getVectorNumElements() == 1 &&
  454. "Only trivial vector-to-scalar conversions should get here!");
  455. Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
  456. PartVT, Val, DAG.getConstant(0, TLI.getVectorIdxTy()));
  457. bool Smaller = ValueVT.bitsLE(PartVT);
  458. Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
  459. DL, PartVT, Val);
  460. }
  461. Parts[0] = Val;
  462. return;
  463. }
  464. // Handle a multi-element vector.
  465. EVT IntermediateVT;
  466. MVT RegisterVT;
  467. unsigned NumIntermediates;
  468. unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
  469. IntermediateVT,
  470. NumIntermediates, RegisterVT);
  471. unsigned NumElements = ValueVT.getVectorNumElements();
  472. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  473. NumParts = NumRegs; // Silence a compiler warning.
  474. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  475. // Split the vector into intermediate operands.
  476. SmallVector<SDValue, 8> Ops(NumIntermediates);
  477. for (unsigned i = 0; i != NumIntermediates; ++i) {
  478. if (IntermediateVT.isVector())
  479. Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
  480. IntermediateVT, Val,
  481. DAG.getConstant(i * (NumElements / NumIntermediates),
  482. TLI.getVectorIdxTy()));
  483. else
  484. Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
  485. IntermediateVT, Val,
  486. DAG.getConstant(i, TLI.getVectorIdxTy()));
  487. }
  488. // Split the intermediate operands into legal parts.
  489. if (NumParts == NumIntermediates) {
  490. // If the register was not expanded, promote or copy the value,
  491. // as appropriate.
  492. for (unsigned i = 0; i != NumParts; ++i)
  493. getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
  494. } else if (NumParts > 0) {
  495. // If the intermediate type was expanded, split each the value into
  496. // legal parts.
  497. assert(NumParts % NumIntermediates == 0 &&
  498. "Must expand into a divisible number of parts!");
  499. unsigned Factor = NumParts / NumIntermediates;
  500. for (unsigned i = 0; i != NumIntermediates; ++i)
  501. getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
  502. }
  503. }
  504. namespace {
  505. /// RegsForValue - This struct represents the registers (physical or virtual)
  506. /// that a particular set of values is assigned, and the type information
  507. /// about the value. The most common situation is to represent one value at a
  508. /// time, but struct or array values are handled element-wise as multiple
  509. /// values. The splitting of aggregates is performed recursively, so that we
  510. /// never have aggregate-typed registers. The values at this point do not
  511. /// necessarily have legal types, so each value may require one or more
  512. /// registers of some legal type.
  513. ///
  514. struct RegsForValue {
  515. /// ValueVTs - The value types of the values, which may not be legal, and
  516. /// may need be promoted or synthesized from one or more registers.
  517. ///
  518. SmallVector<EVT, 4> ValueVTs;
  519. /// RegVTs - The value types of the registers. This is the same size as
  520. /// ValueVTs and it records, for each value, what the type of the assigned
  521. /// register or registers are. (Individual values are never synthesized
  522. /// from more than one type of register.)
  523. ///
  524. /// With virtual registers, the contents of RegVTs is redundant with TLI's
  525. /// getRegisterType member function, however when with physical registers
  526. /// it is necessary to have a separate record of the types.
  527. ///
  528. SmallVector<MVT, 4> RegVTs;
  529. /// Regs - This list holds the registers assigned to the values.
  530. /// Each legal or promoted value requires one register, and each
  531. /// expanded value requires multiple registers.
  532. ///
  533. SmallVector<unsigned, 4> Regs;
  534. RegsForValue() {}
  535. RegsForValue(const SmallVector<unsigned, 4> &regs,
  536. MVT regvt, EVT valuevt)
  537. : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
  538. RegsForValue(LLVMContext &Context, const TargetLowering &tli,
  539. unsigned Reg, Type *Ty) {
  540. ComputeValueVTs(tli, Ty, ValueVTs);
  541. for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
  542. EVT ValueVT = ValueVTs[Value];
  543. unsigned NumRegs = tli.getNumRegisters(Context, ValueVT);
  544. MVT RegisterVT = tli.getRegisterType(Context, ValueVT);
  545. for (unsigned i = 0; i != NumRegs; ++i)
  546. Regs.push_back(Reg + i);
  547. RegVTs.push_back(RegisterVT);
  548. Reg += NumRegs;
  549. }
  550. }
  551. /// append - Add the specified values to this one.
  552. void append(const RegsForValue &RHS) {
  553. ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
  554. RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
  555. Regs.append(RHS.Regs.begin(), RHS.Regs.end());
  556. }
  557. /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
  558. /// this value and returns the result as a ValueVTs value. This uses
  559. /// Chain/Flag as the input and updates them for the output Chain/Flag.
  560. /// If the Flag pointer is NULL, no flag is used.
  561. SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo,
  562. SDLoc dl,
  563. SDValue &Chain, SDValue *Flag,
  564. const Value *V = nullptr) const;
  565. /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
  566. /// specified value into the registers specified by this object. This uses
  567. /// Chain/Flag as the input and updates them for the output Chain/Flag.
  568. /// If the Flag pointer is NULL, no flag is used.
  569. void
  570. getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl, SDValue &Chain,
  571. SDValue *Flag, const Value *V,
  572. ISD::NodeType PreferredExtendType = ISD::ANY_EXTEND) const;
  573. /// AddInlineAsmOperands - Add this value to the specified inlineasm node
  574. /// operand list. This adds the code marker, matching input operand index
  575. /// (if applicable), and includes the number of values added into it.
  576. void AddInlineAsmOperands(unsigned Kind,
  577. bool HasMatching, unsigned MatchingIdx,
  578. SelectionDAG &DAG,
  579. std::vector<SDValue> &Ops) const;
  580. };
  581. }
  582. /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
  583. /// this value and returns the result as a ValueVT value. This uses
  584. /// Chain/Flag as the input and updates them for the output Chain/Flag.
  585. /// If the Flag pointer is NULL, no flag is used.
  586. SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
  587. FunctionLoweringInfo &FuncInfo,
  588. SDLoc dl,
  589. SDValue &Chain, SDValue *Flag,
  590. const Value *V) const {
  591. // A Value with type {} or [0 x %t] needs no registers.
  592. if (ValueVTs.empty())
  593. return SDValue();
  594. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  595. // Assemble the legal parts into the final values.
  596. SmallVector<SDValue, 4> Values(ValueVTs.size());
  597. SmallVector<SDValue, 8> Parts;
  598. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  599. // Copy the legal parts from the registers.
  600. EVT ValueVT = ValueVTs[Value];
  601. unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
  602. MVT RegisterVT = RegVTs[Value];
  603. Parts.resize(NumRegs);
  604. for (unsigned i = 0; i != NumRegs; ++i) {
  605. SDValue P;
  606. if (!Flag) {
  607. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
  608. } else {
  609. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
  610. *Flag = P.getValue(2);
  611. }
  612. Chain = P.getValue(1);
  613. Parts[i] = P;
  614. // If the source register was virtual and if we know something about it,
  615. // add an assert node.
  616. if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
  617. !RegisterVT.isInteger() || RegisterVT.isVector())
  618. continue;
  619. const FunctionLoweringInfo::LiveOutInfo *LOI =
  620. FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
  621. if (!LOI)
  622. continue;
  623. unsigned RegSize = RegisterVT.getSizeInBits();
  624. unsigned NumSignBits = LOI->NumSignBits;
  625. unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
  626. if (NumZeroBits == RegSize) {
  627. // The current value is a zero.
  628. // Explicitly express that as it would be easier for
  629. // optimizations to kick in.
  630. Parts[i] = DAG.getConstant(0, RegisterVT);
  631. continue;
  632. }
  633. // FIXME: We capture more information than the dag can represent. For
  634. // now, just use the tightest assertzext/assertsext possible.
  635. bool isSExt = true;
  636. EVT FromVT(MVT::Other);
  637. if (NumSignBits == RegSize)
  638. isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
  639. else if (NumZeroBits >= RegSize-1)
  640. isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
  641. else if (NumSignBits > RegSize-8)
  642. isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
  643. else if (NumZeroBits >= RegSize-8)
  644. isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
  645. else if (NumSignBits > RegSize-16)
  646. isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
  647. else if (NumZeroBits >= RegSize-16)
  648. isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
  649. else if (NumSignBits > RegSize-32)
  650. isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
  651. else if (NumZeroBits >= RegSize-32)
  652. isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
  653. else
  654. continue;
  655. // Add an assertion node.
  656. assert(FromVT != MVT::Other);
  657. Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
  658. RegisterVT, P, DAG.getValueType(FromVT));
  659. }
  660. Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
  661. NumRegs, RegisterVT, ValueVT, V);
  662. Part += NumRegs;
  663. Parts.clear();
  664. }
  665. return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
  666. }
  667. /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
  668. /// specified value into the registers specified by this object. This uses
  669. /// Chain/Flag as the input and updates them for the output Chain/Flag.
  670. /// If the Flag pointer is NULL, no flag is used.
  671. void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
  672. SDValue &Chain, SDValue *Flag, const Value *V,
  673. ISD::NodeType PreferredExtendType) const {
  674. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  675. ISD::NodeType ExtendKind = PreferredExtendType;
  676. // Get the list of the values's legal parts.
  677. unsigned NumRegs = Regs.size();
  678. SmallVector<SDValue, 8> Parts(NumRegs);
  679. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  680. EVT ValueVT = ValueVTs[Value];
  681. unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
  682. MVT RegisterVT = RegVTs[Value];
  683. if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
  684. ExtendKind = ISD::ZERO_EXTEND;
  685. getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
  686. &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
  687. Part += NumParts;
  688. }
  689. // Copy the parts into the registers.
  690. SmallVector<SDValue, 8> Chains(NumRegs);
  691. for (unsigned i = 0; i != NumRegs; ++i) {
  692. SDValue Part;
  693. if (!Flag) {
  694. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
  695. } else {
  696. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
  697. *Flag = Part.getValue(1);
  698. }
  699. Chains[i] = Part.getValue(0);
  700. }
  701. if (NumRegs == 1 || Flag)
  702. // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
  703. // flagged to it. That is the CopyToReg nodes and the user are considered
  704. // a single scheduling unit. If we create a TokenFactor and return it as
  705. // chain, then the TokenFactor is both a predecessor (operand) of the
  706. // user as well as a successor (the TF operands are flagged to the user).
  707. // c1, f1 = CopyToReg
  708. // c2, f2 = CopyToReg
  709. // c3 = TokenFactor c1, c2
  710. // ...
  711. // = op c3, ..., f2
  712. Chain = Chains[NumRegs-1];
  713. else
  714. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  715. }
  716. /// AddInlineAsmOperands - Add this value to the specified inlineasm node
  717. /// operand list. This adds the code marker and includes the number of
  718. /// values added into it.
  719. void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
  720. unsigned MatchingIdx,
  721. SelectionDAG &DAG,
  722. std::vector<SDValue> &Ops) const {
  723. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  724. unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
  725. if (HasMatching)
  726. Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
  727. else if (!Regs.empty() &&
  728. TargetRegisterInfo::isVirtualRegister(Regs.front())) {
  729. // Put the register class of the virtual registers in the flag word. That
  730. // way, later passes can recompute register class constraints for inline
  731. // assembly as well as normal instructions.
  732. // Don't do this for tied operands that can use the regclass information
  733. // from the def.
  734. const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
  735. const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
  736. Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
  737. }
  738. SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
  739. Ops.push_back(Res);
  740. unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
  741. for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
  742. unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
  743. MVT RegisterVT = RegVTs[Value];
  744. for (unsigned i = 0; i != NumRegs; ++i) {
  745. assert(Reg < Regs.size() && "Mismatch in # registers expected");
  746. unsigned TheReg = Regs[Reg++];
  747. Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
  748. if (TheReg == SP && Code == InlineAsm::Kind_Clobber) {
  749. // If we clobbered the stack pointer, MFI should know about it.
  750. assert(DAG.getMachineFunction().getFrameInfo()->
  751. hasInlineAsmWithSPAdjust());
  752. }
  753. }
  754. }
  755. }
  756. void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa,
  757. const TargetLibraryInfo *li) {
  758. AA = &aa;
  759. GFI = gfi;
  760. LibInfo = li;
  761. DL = DAG.getSubtarget().getDataLayout();
  762. Context = DAG.getContext();
  763. LPadToCallSiteMap.clear();
  764. }
  765. /// clear - Clear out the current SelectionDAG and the associated
  766. /// state and prepare this SelectionDAGBuilder object to be used
  767. /// for a new block. This doesn't clear out information about
  768. /// additional blocks that are needed to complete switch lowering
  769. /// or PHI node updating; that information is cleared out as it is
  770. /// consumed.
  771. void SelectionDAGBuilder::clear() {
  772. NodeMap.clear();
  773. UnusedArgNodeMap.clear();
  774. PendingLoads.clear();
  775. PendingExports.clear();
  776. CurInst = nullptr;
  777. HasTailCall = false;
  778. SDNodeOrder = LowestSDNodeOrder;
  779. StatepointLowering.clear();
  780. }
  781. /// clearDanglingDebugInfo - Clear the dangling debug information
  782. /// map. This function is separated from the clear so that debug
  783. /// information that is dangling in a basic block can be properly
  784. /// resolved in a different basic block. This allows the
  785. /// SelectionDAG to resolve dangling debug information attached
  786. /// to PHI nodes.
  787. void SelectionDAGBuilder::clearDanglingDebugInfo() {
  788. DanglingDebugInfoMap.clear();
  789. }
  790. /// getRoot - Return the current virtual root of the Selection DAG,
  791. /// flushing any PendingLoad items. This must be done before emitting
  792. /// a store or any other node that may need to be ordered after any
  793. /// prior load instructions.
  794. ///
  795. SDValue SelectionDAGBuilder::getRoot() {
  796. if (PendingLoads.empty())
  797. return DAG.getRoot();
  798. if (PendingLoads.size() == 1) {
  799. SDValue Root = PendingLoads[0];
  800. DAG.setRoot(Root);
  801. PendingLoads.clear();
  802. return Root;
  803. }
  804. // Otherwise, we have to make a token factor node.
  805. SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  806. PendingLoads);
  807. PendingLoads.clear();
  808. DAG.setRoot(Root);
  809. return Root;
  810. }
  811. /// getControlRoot - Similar to getRoot, but instead of flushing all the
  812. /// PendingLoad items, flush all the PendingExports items. It is necessary
  813. /// to do this before emitting a terminator instruction.
  814. ///
  815. SDValue SelectionDAGBuilder::getControlRoot() {
  816. SDValue Root = DAG.getRoot();
  817. if (PendingExports.empty())
  818. return Root;
  819. // Turn all of the CopyToReg chains into one factored node.
  820. if (Root.getOpcode() != ISD::EntryToken) {
  821. unsigned i = 0, e = PendingExports.size();
  822. for (; i != e; ++i) {
  823. assert(PendingExports[i].getNode()->getNumOperands() > 1);
  824. if (PendingExports[i].getNode()->getOperand(0) == Root)
  825. break; // Don't add the root if we already indirectly depend on it.
  826. }
  827. if (i == e)
  828. PendingExports.push_back(Root);
  829. }
  830. Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  831. PendingExports);
  832. PendingExports.clear();
  833. DAG.setRoot(Root);
  834. return Root;
  835. }
  836. void SelectionDAGBuilder::visit(const Instruction &I) {
  837. // Set up outgoing PHI node register values before emitting the terminator.
  838. if (isa<TerminatorInst>(&I))
  839. HandlePHINodesInSuccessorBlocks(I.getParent());
  840. ++SDNodeOrder;
  841. CurInst = &I;
  842. visit(I.getOpcode(), I);
  843. if (!isa<TerminatorInst>(&I) && !HasTailCall)
  844. CopyToExportRegsIfNeeded(&I);
  845. CurInst = nullptr;
  846. }
  847. void SelectionDAGBuilder::visitPHI(const PHINode &) {
  848. llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
  849. }
  850. void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
  851. // Note: this doesn't use InstVisitor, because it has to work with
  852. // ConstantExpr's in addition to instructions.
  853. switch (Opcode) {
  854. default: llvm_unreachable("Unknown instruction type encountered!");
  855. // Build the switch statement using the Instruction.def file.
  856. #define HANDLE_INST(NUM, OPCODE, CLASS) \
  857. case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
  858. #include "llvm/IR/Instruction.def"
  859. }
  860. }
  861. // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
  862. // generate the debug data structures now that we've seen its definition.
  863. void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
  864. SDValue Val) {
  865. DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
  866. if (DDI.getDI()) {
  867. const DbgValueInst *DI = DDI.getDI();
  868. DebugLoc dl = DDI.getdl();
  869. unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
  870. MDNode *Variable = DI->getVariable();
  871. MDNode *Expr = DI->getExpression();
  872. uint64_t Offset = DI->getOffset();
  873. // A dbg.value for an alloca is always indirect.
  874. bool IsIndirect = isa<AllocaInst>(V) || Offset != 0;
  875. SDDbgValue *SDV;
  876. if (Val.getNode()) {
  877. if (!EmitFuncArgumentDbgValue(V, Variable, Expr, Offset, IsIndirect,
  878. Val)) {
  879. SDV = DAG.getDbgValue(Variable, Expr, Val.getNode(), Val.getResNo(),
  880. IsIndirect, Offset, dl, DbgSDNodeOrder);
  881. DAG.AddDbgValue(SDV, Val.getNode(), false);
  882. }
  883. } else
  884. DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
  885. DanglingDebugInfoMap[V] = DanglingDebugInfo();
  886. }
  887. }
  888. /// getValue - Return an SDValue for the given Value.
  889. SDValue SelectionDAGBuilder::getValue(const Value *V) {
  890. // If we already have an SDValue for this value, use it. It's important
  891. // to do this first, so that we don't create a CopyFromReg if we already
  892. // have a regular SDValue.
  893. SDValue &N = NodeMap[V];
  894. if (N.getNode()) return N;
  895. // If there's a virtual register allocated and initialized for this
  896. // value, use it.
  897. DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
  898. if (It != FuncInfo.ValueMap.end()) {
  899. unsigned InReg = It->second;
  900. RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), InReg,
  901. V->getType());
  902. SDValue Chain = DAG.getEntryNode();
  903. N = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
  904. resolveDanglingDebugInfo(V, N);
  905. return N;
  906. }
  907. // Otherwise create a new SDValue and remember it.
  908. SDValue Val = getValueImpl(V);
  909. NodeMap[V] = Val;
  910. resolveDanglingDebugInfo(V, Val);
  911. return Val;
  912. }
  913. /// getNonRegisterValue - Return an SDValue for the given Value, but
  914. /// don't look in FuncInfo.ValueMap for a virtual register.
  915. SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
  916. // If we already have an SDValue for this value, use it.
  917. SDValue &N = NodeMap[V];
  918. if (N.getNode()) return N;
  919. // Otherwise create a new SDValue and remember it.
  920. SDValue Val = getValueImpl(V);
  921. NodeMap[V] = Val;
  922. resolveDanglingDebugInfo(V, Val);
  923. return Val;
  924. }
  925. /// getValueImpl - Helper function for getValue and getNonRegisterValue.
  926. /// Create an SDValue for the given value.
  927. SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
  928. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  929. if (const Constant *C = dyn_cast<Constant>(V)) {
  930. EVT VT = TLI.getValueType(V->getType(), true);
  931. if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
  932. return DAG.getConstant(*CI, VT);
  933. if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
  934. return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
  935. if (isa<ConstantPointerNull>(C)) {
  936. unsigned AS = V->getType()->getPointerAddressSpace();
  937. return DAG.getConstant(0, TLI.getPointerTy(AS));
  938. }
  939. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
  940. return DAG.getConstantFP(*CFP, VT);
  941. if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
  942. return DAG.getUNDEF(VT);
  943. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  944. visit(CE->getOpcode(), *CE);
  945. SDValue N1 = NodeMap[V];
  946. assert(N1.getNode() && "visit didn't populate the NodeMap!");
  947. return N1;
  948. }
  949. if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
  950. SmallVector<SDValue, 4> Constants;
  951. for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
  952. OI != OE; ++OI) {
  953. SDNode *Val = getValue(*OI).getNode();
  954. // If the operand is an empty aggregate, there are no values.
  955. if (!Val) continue;
  956. // Add each leaf value from the operand to the Constants list
  957. // to form a flattened list of all the values.
  958. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  959. Constants.push_back(SDValue(Val, i));
  960. }
  961. return DAG.getMergeValues(Constants, getCurSDLoc());
  962. }
  963. if (const ConstantDataSequential *CDS =
  964. dyn_cast<ConstantDataSequential>(C)) {
  965. SmallVector<SDValue, 4> Ops;
  966. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  967. SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
  968. // Add each leaf value from the operand to the Constants list
  969. // to form a flattened list of all the values.
  970. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  971. Ops.push_back(SDValue(Val, i));
  972. }
  973. if (isa<ArrayType>(CDS->getType()))
  974. return DAG.getMergeValues(Ops, getCurSDLoc());
  975. return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
  976. VT, Ops);
  977. }
  978. if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
  979. assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
  980. "Unknown struct or array constant!");
  981. SmallVector<EVT, 4> ValueVTs;
  982. ComputeValueVTs(TLI, C->getType(), ValueVTs);
  983. unsigned NumElts = ValueVTs.size();
  984. if (NumElts == 0)
  985. return SDValue(); // empty struct
  986. SmallVector<SDValue, 4> Constants(NumElts);
  987. for (unsigned i = 0; i != NumElts; ++i) {
  988. EVT EltVT = ValueVTs[i];
  989. if (isa<UndefValue>(C))
  990. Constants[i] = DAG.getUNDEF(EltVT);
  991. else if (EltVT.isFloatingPoint())
  992. Constants[i] = DAG.getConstantFP(0, EltVT);
  993. else
  994. Constants[i] = DAG.getConstant(0, EltVT);
  995. }
  996. return DAG.getMergeValues(Constants, getCurSDLoc());
  997. }
  998. if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
  999. return DAG.getBlockAddress(BA, VT);
  1000. VectorType *VecTy = cast<VectorType>(V->getType());
  1001. unsigned NumElements = VecTy->getNumElements();
  1002. // Now that we know the number and type of the elements, get that number of
  1003. // elements into the Ops array based on what kind of constant it is.
  1004. SmallVector<SDValue, 16> Ops;
  1005. if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
  1006. for (unsigned i = 0; i != NumElements; ++i)
  1007. Ops.push_back(getValue(CV->getOperand(i)));
  1008. } else {
  1009. assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
  1010. EVT EltVT = TLI.getValueType(VecTy->getElementType());
  1011. SDValue Op;
  1012. if (EltVT.isFloatingPoint())
  1013. Op = DAG.getConstantFP(0, EltVT);
  1014. else
  1015. Op = DAG.getConstant(0, EltVT);
  1016. Ops.assign(NumElements, Op);
  1017. }
  1018. // Create a BUILD_VECTOR node.
  1019. return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops);
  1020. }
  1021. // If this is a static alloca, generate it as the frameindex instead of
  1022. // computation.
  1023. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  1024. DenseMap<const AllocaInst*, int>::iterator SI =
  1025. FuncInfo.StaticAllocaMap.find(AI);
  1026. if (SI != FuncInfo.StaticAllocaMap.end())
  1027. return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
  1028. }
  1029. // If this is an instruction which fast-isel has deferred, select it now.
  1030. if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
  1031. unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
  1032. RegsForValue RFV(*DAG.getContext(), TLI, InReg, Inst->getType());
  1033. SDValue Chain = DAG.getEntryNode();
  1034. return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
  1035. }
  1036. llvm_unreachable("Can't get register for value!");
  1037. }
  1038. void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
  1039. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1040. SDValue Chain = getControlRoot();
  1041. SmallVector<ISD::OutputArg, 8> Outs;
  1042. SmallVector<SDValue, 8> OutVals;
  1043. if (!FuncInfo.CanLowerReturn) {
  1044. unsigned DemoteReg = FuncInfo.DemoteRegister;
  1045. const Function *F = I.getParent()->getParent();
  1046. // Emit a store of the return value through the virtual register.
  1047. // Leave Outs empty so that LowerReturn won't try to load return
  1048. // registers the usual way.
  1049. SmallVector<EVT, 1> PtrValueVTs;
  1050. ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
  1051. PtrValueVTs);
  1052. SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
  1053. SDValue RetOp = getValue(I.getOperand(0));
  1054. SmallVector<EVT, 4> ValueVTs;
  1055. SmallVector<uint64_t, 4> Offsets;
  1056. ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
  1057. unsigned NumValues = ValueVTs.size();
  1058. SmallVector<SDValue, 4> Chains(NumValues);
  1059. for (unsigned i = 0; i != NumValues; ++i) {
  1060. SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(),
  1061. RetPtr.getValueType(), RetPtr,
  1062. DAG.getIntPtrConstant(Offsets[i]));
  1063. Chains[i] =
  1064. DAG.getStore(Chain, getCurSDLoc(),
  1065. SDValue(RetOp.getNode(), RetOp.getResNo() + i),
  1066. // FIXME: better loc info would be nice.
  1067. Add, MachinePointerInfo(), false, false, 0);
  1068. }
  1069. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
  1070. MVT::Other, Chains);
  1071. } else if (I.getNumOperands() != 0) {
  1072. SmallVector<EVT, 4> ValueVTs;
  1073. ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs);
  1074. unsigned NumValues = ValueVTs.size();
  1075. if (NumValues) {
  1076. SDValue RetOp = getValue(I.getOperand(0));
  1077. for (unsigned j = 0, f = NumValues; j != f; ++j) {
  1078. EVT VT = ValueVTs[j];
  1079. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  1080. const Function *F = I.getParent()->getParent();
  1081. if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
  1082. Attribute::SExt))
  1083. ExtendKind = ISD::SIGN_EXTEND;
  1084. else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
  1085. Attribute::ZExt))
  1086. ExtendKind = ISD::ZERO_EXTEND;
  1087. if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
  1088. VT = TLI.getTypeForExtArgOrReturn(*DAG.getContext(), VT, ExtendKind);
  1089. unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
  1090. MVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
  1091. SmallVector<SDValue, 4> Parts(NumParts);
  1092. getCopyToParts(DAG, getCurSDLoc(),
  1093. SDValue(RetOp.getNode(), RetOp.getResNo() + j),
  1094. &Parts[0], NumParts, PartVT, &I, ExtendKind);
  1095. // 'inreg' on function refers to return value
  1096. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1097. if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
  1098. Attribute::InReg))
  1099. Flags.setInReg();
  1100. // Propagate extension type if any
  1101. if (ExtendKind == ISD::SIGN_EXTEND)
  1102. Flags.setSExt();
  1103. else if (ExtendKind == ISD::ZERO_EXTEND)
  1104. Flags.setZExt();
  1105. for (unsigned i = 0; i < NumParts; ++i) {
  1106. Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
  1107. VT, /*isfixed=*/true, 0, 0));
  1108. OutVals.push_back(Parts[i]);
  1109. }
  1110. }
  1111. }
  1112. }
  1113. bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
  1114. CallingConv::ID CallConv =
  1115. DAG.getMachineFunction().getFunction()->getCallingConv();
  1116. Chain = DAG.getTargetLoweringInfo().LowerReturn(
  1117. Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
  1118. // Verify that the target's LowerReturn behaved as expected.
  1119. assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
  1120. "LowerReturn didn't return a valid chain!");
  1121. // Update the DAG with the new chain value resulting from return lowering.
  1122. DAG.setRoot(Chain);
  1123. }
  1124. /// CopyToExportRegsIfNeeded - If the given value has virtual registers
  1125. /// created for it, emit nodes to copy the value into the virtual
  1126. /// registers.
  1127. void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
  1128. // Skip empty types
  1129. if (V->getType()->isEmptyTy())
  1130. return;
  1131. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  1132. if (VMI != FuncInfo.ValueMap.end()) {
  1133. assert(!V->use_empty() && "Unused value assigned virtual registers!");
  1134. CopyValueToVirtualRegister(V, VMI->second);
  1135. }
  1136. }
  1137. /// ExportFromCurrentBlock - If this condition isn't known to be exported from
  1138. /// the current basic block, add it to ValueMap now so that we'll get a
  1139. /// CopyTo/FromReg.
  1140. void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
  1141. // No need to export constants.
  1142. if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
  1143. // Already exported?
  1144. if (FuncInfo.isExportedInst(V)) return;
  1145. unsigned Reg = FuncInfo.InitializeRegForValue(V);
  1146. CopyValueToVirtualRegister(V, Reg);
  1147. }
  1148. bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
  1149. const BasicBlock *FromBB) {
  1150. // The operands of the setcc have to be in this block. We don't know
  1151. // how to export them from some other block.
  1152. if (const Instruction *VI = dyn_cast<Instruction>(V)) {
  1153. // Can export from current BB.
  1154. if (VI->getParent() == FromBB)
  1155. return true;
  1156. // Is already exported, noop.
  1157. return FuncInfo.isExportedInst(V);
  1158. }
  1159. // If this is an argument, we can export it if the BB is the entry block or
  1160. // if it is already exported.
  1161. if (isa<Argument>(V)) {
  1162. if (FromBB == &FromBB->getParent()->getEntryBlock())
  1163. return true;
  1164. // Otherwise, can only export this if it is already exported.
  1165. return FuncInfo.isExportedInst(V);
  1166. }
  1167. // Otherwise, constants can always be exported.
  1168. return true;
  1169. }
  1170. /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
  1171. uint32_t SelectionDAGBuilder::getEdgeWeight(const MachineBasicBlock *Src,
  1172. const MachineBasicBlock *Dst) const {
  1173. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1174. if (!BPI)
  1175. return 0;
  1176. const BasicBlock *SrcBB = Src->getBasicBlock();
  1177. const BasicBlock *DstBB = Dst->getBasicBlock();
  1178. return BPI->getEdgeWeight(SrcBB, DstBB);
  1179. }
  1180. void SelectionDAGBuilder::
  1181. addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
  1182. uint32_t Weight /* = 0 */) {
  1183. if (!Weight)
  1184. Weight = getEdgeWeight(Src, Dst);
  1185. Src->addSuccessor(Dst, Weight);
  1186. }
  1187. static bool InBlock(const Value *V, const BasicBlock *BB) {
  1188. if (const Instruction *I = dyn_cast<Instruction>(V))
  1189. return I->getParent() == BB;
  1190. return true;
  1191. }
  1192. /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
  1193. /// This function emits a branch and is used at the leaves of an OR or an
  1194. /// AND operator tree.
  1195. ///
  1196. void
  1197. SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
  1198. MachineBasicBlock *TBB,
  1199. MachineBasicBlock *FBB,
  1200. MachineBasicBlock *CurBB,
  1201. MachineBasicBlock *SwitchBB,
  1202. uint32_t TWeight,
  1203. uint32_t FWeight) {
  1204. const BasicBlock *BB = CurBB->getBasicBlock();
  1205. // If the leaf of the tree is a comparison, merge the condition into
  1206. // the caseblock.
  1207. if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
  1208. // The operands of the cmp have to be in this block. We don't know
  1209. // how to export them from some other block. If this is the first block
  1210. // of the sequence, no exporting is needed.
  1211. if (CurBB == SwitchBB ||
  1212. (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
  1213. isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
  1214. ISD::CondCode Condition;
  1215. if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
  1216. Condition = getICmpCondCode(IC->getPredicate());
  1217. } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
  1218. Condition = getFCmpCondCode(FC->getPredicate());
  1219. if (TM.Options.NoNaNsFPMath)
  1220. Condition = getFCmpCodeWithoutNaN(Condition);
  1221. } else {
  1222. Condition = ISD::SETEQ; // silence warning.
  1223. llvm_unreachable("Unknown compare instruction");
  1224. }
  1225. CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
  1226. TBB, FBB, CurBB, TWeight, FWeight);
  1227. SwitchCases.push_back(CB);
  1228. return;
  1229. }
  1230. }
  1231. // Create a CaseBlock record representing this branch.
  1232. CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
  1233. nullptr, TBB, FBB, CurBB, TWeight, FWeight);
  1234. SwitchCases.push_back(CB);
  1235. }
  1236. /// Scale down both weights to fit into uint32_t.
  1237. static void ScaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
  1238. uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
  1239. uint32_t Scale = (NewMax / UINT32_MAX) + 1;
  1240. NewTrue = NewTrue / Scale;
  1241. NewFalse = NewFalse / Scale;
  1242. }
  1243. /// FindMergedConditions - If Cond is an expression like
  1244. void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
  1245. MachineBasicBlock *TBB,
  1246. MachineBasicBlock *FBB,
  1247. MachineBasicBlock *CurBB,
  1248. MachineBasicBlock *SwitchBB,
  1249. unsigned Opc, uint32_t TWeight,
  1250. uint32_t FWeight) {
  1251. // If this node is not part of the or/and tree, emit it as a branch.
  1252. const Instruction *BOp = dyn_cast<Instruction>(Cond);
  1253. if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
  1254. (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
  1255. BOp->getParent() != CurBB->getBasicBlock() ||
  1256. !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
  1257. !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
  1258. EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
  1259. TWeight, FWeight);
  1260. return;
  1261. }
  1262. // Create TmpBB after CurBB.
  1263. MachineFunction::iterator BBI = CurBB;
  1264. MachineFunction &MF = DAG.getMachineFunction();
  1265. MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
  1266. CurBB->getParent()->insert(++BBI, TmpBB);
  1267. if (Opc == Instruction::Or) {
  1268. // Codegen X | Y as:
  1269. // BB1:
  1270. // jmp_if_X TBB
  1271. // jmp TmpBB
  1272. // TmpBB:
  1273. // jmp_if_Y TBB
  1274. // jmp FBB
  1275. //
  1276. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1277. // The requirement is that
  1278. // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
  1279. // = TrueProb for orignal BB.
  1280. // Assuming the orignal weights are A and B, one choice is to set BB1's
  1281. // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
  1282. // assumes that
  1283. // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
  1284. // Another choice is to assume TrueProb for BB1 equals to TrueProb for
  1285. // TmpBB, but the math is more complicated.
  1286. uint64_t NewTrueWeight = TWeight;
  1287. uint64_t NewFalseWeight = (uint64_t)TWeight + 2 * (uint64_t)FWeight;
  1288. ScaleWeights(NewTrueWeight, NewFalseWeight);
  1289. // Emit the LHS condition.
  1290. FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
  1291. NewTrueWeight, NewFalseWeight);
  1292. NewTrueWeight = TWeight;
  1293. NewFalseWeight = 2 * (uint64_t)FWeight;
  1294. ScaleWeights(NewTrueWeight, NewFalseWeight);
  1295. // Emit the RHS condition into TmpBB.
  1296. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
  1297. NewTrueWeight, NewFalseWeight);
  1298. } else {
  1299. assert(Opc == Instruction::And && "Unknown merge op!");
  1300. // Codegen X & Y as:
  1301. // BB1:
  1302. // jmp_if_X TmpBB
  1303. // jmp FBB
  1304. // TmpBB:
  1305. // jmp_if_Y TBB
  1306. // jmp FBB
  1307. //
  1308. // This requires creation of TmpBB after CurBB.
  1309. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1310. // The requirement is that
  1311. // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
  1312. // = FalseProb for orignal BB.
  1313. // Assuming the orignal weights are A and B, one choice is to set BB1's
  1314. // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
  1315. // assumes that
  1316. // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
  1317. uint64_t NewTrueWeight = 2 * (uint64_t)TWeight + (uint64_t)FWeight;
  1318. uint64_t NewFalseWeight = FWeight;
  1319. ScaleWeights(NewTrueWeight, NewFalseWeight);
  1320. // Emit the LHS condition.
  1321. FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
  1322. NewTrueWeight, NewFalseWeight);
  1323. NewTrueWeight = 2 * (uint64_t)TWeight;
  1324. NewFalseWeight = FWeight;
  1325. ScaleWeights(NewTrueWeight, NewFalseWeight);
  1326. // Emit the RHS condition into TmpBB.
  1327. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
  1328. NewTrueWeight, NewFalseWeight);
  1329. }
  1330. }
  1331. /// If the set of cases should be emitted as a series of branches, return true.
  1332. /// If we should emit this as a bunch of and/or'd together conditions, return
  1333. /// false.
  1334. bool
  1335. SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
  1336. if (Cases.size() != 2) return true;
  1337. // If this is two comparisons of the same values or'd or and'd together, they
  1338. // will get folded into a single comparison, so don't emit two blocks.
  1339. if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
  1340. Cases[0].CmpRHS == Cases[1].CmpRHS) ||
  1341. (Cases[0].CmpRHS == Cases[1].CmpLHS &&
  1342. Cases[0].CmpLHS == Cases[1].CmpRHS)) {
  1343. return false;
  1344. }
  1345. // Handle: (X != null) | (Y != null) --> (X|Y) != 0
  1346. // Handle: (X == null) & (Y == null) --> (X|Y) == 0
  1347. if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
  1348. Cases[0].CC == Cases[1].CC &&
  1349. isa<Constant>(Cases[0].CmpRHS) &&
  1350. cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
  1351. if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
  1352. return false;
  1353. if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
  1354. return false;
  1355. }
  1356. return true;
  1357. }
  1358. void SelectionDAGBuilder::visitBr(const BranchInst &I) {
  1359. MachineBasicBlock *BrMBB = FuncInfo.MBB;
  1360. // Update machine-CFG edges.
  1361. MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
  1362. // Figure out which block is immediately after the current one.
  1363. MachineBasicBlock *NextBlock = nullptr;
  1364. MachineFunction::iterator BBI = BrMBB;
  1365. if (++BBI != FuncInfo.MF->end())
  1366. NextBlock = BBI;
  1367. if (I.isUnconditional()) {
  1368. // Update machine-CFG edges.
  1369. BrMBB->addSuccessor(Succ0MBB);
  1370. // If this is not a fall-through branch or optimizations are switched off,
  1371. // emit the branch.
  1372. if (Succ0MBB != NextBlock || TM.getOptLevel() == CodeGenOpt::None)
  1373. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  1374. MVT::Other, getControlRoot(),
  1375. DAG.getBasicBlock(Succ0MBB)));
  1376. return;
  1377. }
  1378. // If this condition is one of the special cases we handle, do special stuff
  1379. // now.
  1380. const Value *CondVal = I.getCondition();
  1381. MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
  1382. // If this is a series of conditions that are or'd or and'd together, emit
  1383. // this as a sequence of branches instead of setcc's with and/or operations.
  1384. // As long as jumps are not expensive, this should improve performance.
  1385. // For example, instead of something like:
  1386. // cmp A, B
  1387. // C = seteq
  1388. // cmp D, E
  1389. // F = setle
  1390. // or C, F
  1391. // jnz foo
  1392. // Emit:
  1393. // cmp A, B
  1394. // je foo
  1395. // cmp D, E
  1396. // jle foo
  1397. //
  1398. if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
  1399. if (!DAG.getTargetLoweringInfo().isJumpExpensive() &&
  1400. BOp->hasOneUse() && (BOp->getOpcode() == Instruction::And ||
  1401. BOp->getOpcode() == Instruction::Or)) {
  1402. FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
  1403. BOp->getOpcode(), getEdgeWeight(BrMBB, Succ0MBB),
  1404. getEdgeWeight(BrMBB, Succ1MBB));
  1405. // If the compares in later blocks need to use values not currently
  1406. // exported from this block, export them now. This block should always
  1407. // be the first entry.
  1408. assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
  1409. // Allow some cases to be rejected.
  1410. if (ShouldEmitAsBranches(SwitchCases)) {
  1411. for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
  1412. ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
  1413. ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
  1414. }
  1415. // Emit the branch for this block.
  1416. visitSwitchCase(SwitchCases[0], BrMBB);
  1417. SwitchCases.erase(SwitchCases.begin());
  1418. return;
  1419. }
  1420. // Okay, we decided not to do this, remove any inserted MBB's and clear
  1421. // SwitchCases.
  1422. for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
  1423. FuncInfo.MF->erase(SwitchCases[i].ThisBB);
  1424. SwitchCases.clear();
  1425. }
  1426. }
  1427. // Create a CaseBlock record representing this branch.
  1428. CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
  1429. nullptr, Succ0MBB, Succ1MBB, BrMBB);
  1430. // Use visitSwitchCase to actually insert the fast branch sequence for this
  1431. // cond branch.
  1432. visitSwitchCase(CB, BrMBB);
  1433. }
  1434. /// visitSwitchCase - Emits the necessary code to represent a single node in
  1435. /// the binary search tree resulting from lowering a switch instruction.
  1436. void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
  1437. MachineBasicBlock *SwitchBB) {
  1438. SDValue Cond;
  1439. SDValue CondLHS = getValue(CB.CmpLHS);
  1440. SDLoc dl = getCurSDLoc();
  1441. // Build the setcc now.
  1442. if (!CB.CmpMHS) {
  1443. // Fold "(X == true)" to X and "(X == false)" to !X to
  1444. // handle common cases produced by branch lowering.
  1445. if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
  1446. CB.CC == ISD::SETEQ)
  1447. Cond = CondLHS;
  1448. else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
  1449. CB.CC == ISD::SETEQ) {
  1450. SDValue True = DAG.getConstant(1, CondLHS.getValueType());
  1451. Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
  1452. } else
  1453. Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
  1454. } else {
  1455. assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
  1456. const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
  1457. const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
  1458. SDValue CmpOp = getValue(CB.CmpMHS);
  1459. EVT VT = CmpOp.getValueType();
  1460. if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
  1461. Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
  1462. ISD::SETLE);
  1463. } else {
  1464. SDValue SUB = DAG.getNode(ISD::SUB, dl,
  1465. VT, CmpOp, DAG.getConstant(Low, VT));
  1466. Cond = DAG.getSetCC(dl, MVT::i1, SUB,
  1467. DAG.getConstant(High-Low, VT), ISD::SETULE);
  1468. }
  1469. }
  1470. // Update successor info
  1471. addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight);
  1472. // TrueBB and FalseBB are always different unless the incoming IR is
  1473. // degenerate. This only happens when running llc on weird IR.
  1474. if (CB.TrueBB != CB.FalseBB)
  1475. addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight);
  1476. // Set NextBlock to be the MBB immediately after the current one, if any.
  1477. // This is used to avoid emitting unnecessary branches to the next block.
  1478. MachineBasicBlock *NextBlock = nullptr;
  1479. MachineFunction::iterator BBI = SwitchBB;
  1480. if (++BBI != FuncInfo.MF->end())
  1481. NextBlock = BBI;
  1482. // If the lhs block is the next block, invert the condition so that we can
  1483. // fall through to the lhs instead of the rhs block.
  1484. if (CB.TrueBB == NextBlock) {
  1485. std::swap(CB.TrueBB, CB.FalseBB);
  1486. SDValue True = DAG.getConstant(1, Cond.getValueType());
  1487. Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
  1488. }
  1489. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  1490. MVT::Other, getControlRoot(), Cond,
  1491. DAG.getBasicBlock(CB.TrueBB));
  1492. // Insert the false branch. Do this even if it's a fall through branch,
  1493. // this makes it easier to do DAG optimizations which require inverting
  1494. // the branch condition.
  1495. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  1496. DAG.getBasicBlock(CB.FalseBB));
  1497. DAG.setRoot(BrCond);
  1498. }
  1499. /// visitJumpTable - Emit JumpTable node in the current MBB
  1500. void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
  1501. // Emit the code for the jump table
  1502. assert(JT.Reg != -1U && "Should lower JT Header first!");
  1503. EVT PTy = DAG.getTargetLoweringInfo().getPointerTy();
  1504. SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
  1505. JT.Reg, PTy);
  1506. SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
  1507. SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
  1508. MVT::Other, Index.getValue(1),
  1509. Table, Index);
  1510. DAG.setRoot(BrJumpTable);
  1511. }
  1512. /// visitJumpTableHeader - This function emits necessary code to produce index
  1513. /// in the JumpTable from switch case.
  1514. void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
  1515. JumpTableHeader &JTH,
  1516. MachineBasicBlock *SwitchBB) {
  1517. // Subtract the lowest switch case value from the value being switched on and
  1518. // conditional branch to default mbb if the result is greater than the
  1519. // difference between smallest and largest cases.
  1520. SDValue SwitchOp = getValue(JTH.SValue);
  1521. EVT VT = SwitchOp.getValueType();
  1522. SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
  1523. DAG.getConstant(JTH.First, VT));
  1524. // The SDNode we just created, which holds the value being switched on minus
  1525. // the smallest case value, needs to be copied to a virtual register so it
  1526. // can be used as an index into the jump table in a subsequent basic block.
  1527. // This value may be smaller or larger than the target's pointer type, and
  1528. // therefore require extension or truncating.
  1529. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1530. SwitchOp = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), TLI.getPointerTy());
  1531. unsigned JumpTableReg = FuncInfo.CreateReg(TLI.getPointerTy());
  1532. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
  1533. JumpTableReg, SwitchOp);
  1534. JT.Reg = JumpTableReg;
  1535. // Emit the range check for the jump table, and branch to the default block
  1536. // for the switch statement if the value being switched on exceeds the largest
  1537. // case in the switch.
  1538. SDValue CMP =
  1539. DAG.getSetCC(getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(),
  1540. Sub.getValueType()),
  1541. Sub, DAG.getConstant(JTH.Last - JTH.First, VT), ISD::SETUGT);
  1542. // Set NextBlock to be the MBB immediately after the current one, if any.
  1543. // This is used to avoid emitting unnecessary branches to the next block.
  1544. MachineBasicBlock *NextBlock = nullptr;
  1545. MachineFunction::iterator BBI = SwitchBB;
  1546. if (++BBI != FuncInfo.MF->end())
  1547. NextBlock = BBI;
  1548. SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
  1549. MVT::Other, CopyTo, CMP,
  1550. DAG.getBasicBlock(JT.Default));
  1551. if (JT.MBB != NextBlock)
  1552. BrCond = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrCond,
  1553. DAG.getBasicBlock(JT.MBB));
  1554. DAG.setRoot(BrCond);
  1555. }
  1556. /// Codegen a new tail for a stack protector check ParentMBB which has had its
  1557. /// tail spliced into a stack protector check success bb.
  1558. ///
  1559. /// For a high level explanation of how this fits into the stack protector
  1560. /// generation see the comment on the declaration of class
  1561. /// StackProtectorDescriptor.
  1562. void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
  1563. MachineBasicBlock *ParentBB) {
  1564. // First create the loads to the guard/stack slot for the comparison.
  1565. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1566. EVT PtrTy = TLI.getPointerTy();
  1567. MachineFrameInfo *MFI = ParentBB->getParent()->getFrameInfo();
  1568. int FI = MFI->getStackProtectorIndex();
  1569. const Value *IRGuard = SPD.getGuard();
  1570. SDValue GuardPtr = getValue(IRGuard);
  1571. SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
  1572. unsigned Align =
  1573. TLI.getDataLayout()->getPrefTypeAlignment(IRGuard->getType());
  1574. SDValue Guard;
  1575. // If GuardReg is set and useLoadStackGuardNode returns true, retrieve the
  1576. // guard value from the virtual register holding the value. Otherwise, emit a
  1577. // volatile load to retrieve the stack guard value.
  1578. unsigned GuardReg = SPD.getGuardReg();
  1579. if (GuardReg && TLI.useLoadStackGuardNode())
  1580. Guard = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), GuardReg,
  1581. PtrTy);
  1582. else
  1583. Guard = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
  1584. GuardPtr, MachinePointerInfo(IRGuard, 0),
  1585. true, false, false, Align);
  1586. SDValue StackSlot = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
  1587. StackSlotPtr,
  1588. MachinePointerInfo::getFixedStack(FI),
  1589. true, false, false, Align);
  1590. // Perform the comparison via a subtract/getsetcc.
  1591. EVT VT = Guard.getValueType();
  1592. SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, Guard, StackSlot);
  1593. SDValue Cmp =
  1594. DAG.getSetCC(getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(),
  1595. Sub.getValueType()),
  1596. Sub, DAG.getConstant(0, VT), ISD::SETNE);
  1597. // If the sub is not 0, then we know the guard/stackslot do not equal, so
  1598. // branch to failure MBB.
  1599. SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
  1600. MVT::Other, StackSlot.getOperand(0),
  1601. Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
  1602. // Otherwise branch to success MBB.
  1603. SDValue Br = DAG.getNode(ISD::BR, getCurSDLoc(),
  1604. MVT::Other, BrCond,
  1605. DAG.getBasicBlock(SPD.getSuccessMBB()));
  1606. DAG.setRoot(Br);
  1607. }
  1608. /// Codegen the failure basic block for a stack protector check.
  1609. ///
  1610. /// A failure stack protector machine basic block consists simply of a call to
  1611. /// __stack_chk_fail().
  1612. ///
  1613. /// For a high level explanation of how this fits into the stack protector
  1614. /// generation see the comment on the declaration of class
  1615. /// StackProtectorDescriptor.
  1616. void
  1617. SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
  1618. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1619. SDValue Chain =
  1620. TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
  1621. nullptr, 0, false, getCurSDLoc(), false, false).second;
  1622. DAG.setRoot(Chain);
  1623. }
  1624. /// visitBitTestHeader - This function emits necessary code to produce value
  1625. /// suitable for "bit tests"
  1626. void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
  1627. MachineBasicBlock *SwitchBB) {
  1628. // Subtract the minimum value
  1629. SDValue SwitchOp = getValue(B.SValue);
  1630. EVT VT = SwitchOp.getValueType();
  1631. SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
  1632. DAG.getConstant(B.First, VT));
  1633. // Check range
  1634. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1635. SDValue RangeCmp =
  1636. DAG.getSetCC(getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(),
  1637. Sub.getValueType()),
  1638. Sub, DAG.getConstant(B.Range, VT), ISD::SETUGT);
  1639. // Determine the type of the test operands.
  1640. bool UsePtrType = false;
  1641. if (!TLI.isTypeLegal(VT))
  1642. UsePtrType = true;
  1643. else {
  1644. for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
  1645. if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
  1646. // Switch table case range are encoded into series of masks.
  1647. // Just use pointer type, it's guaranteed to fit.
  1648. UsePtrType = true;
  1649. break;
  1650. }
  1651. }
  1652. if (UsePtrType) {
  1653. VT = TLI.getPointerTy();
  1654. Sub = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), VT);
  1655. }
  1656. B.RegVT = VT.getSimpleVT();
  1657. B.Reg = FuncInfo.CreateReg(B.RegVT);
  1658. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
  1659. B.Reg, Sub);
  1660. // Set NextBlock to be the MBB immediately after the current one, if any.
  1661. // This is used to avoid emitting unnecessary branches to the next block.
  1662. MachineBasicBlock *NextBlock = nullptr;
  1663. MachineFunction::iterator BBI = SwitchBB;
  1664. if (++BBI != FuncInfo.MF->end())
  1665. NextBlock = BBI;
  1666. MachineBasicBlock* MBB = B.Cases[0].ThisBB;
  1667. addSuccessorWithWeight(SwitchBB, B.Default);
  1668. addSuccessorWithWeight(SwitchBB, MBB);
  1669. SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
  1670. MVT::Other, CopyTo, RangeCmp,
  1671. DAG.getBasicBlock(B.Default));
  1672. if (MBB != NextBlock)
  1673. BrRange = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, CopyTo,
  1674. DAG.getBasicBlock(MBB));
  1675. DAG.setRoot(BrRange);
  1676. }
  1677. /// visitBitTestCase - this function produces one "bit test"
  1678. void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
  1679. MachineBasicBlock* NextMBB,
  1680. uint32_t BranchWeightToNext,
  1681. unsigned Reg,
  1682. BitTestCase &B,
  1683. MachineBasicBlock *SwitchBB) {
  1684. MVT VT = BB.RegVT;
  1685. SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
  1686. Reg, VT);
  1687. SDValue Cmp;
  1688. unsigned PopCount = CountPopulation_64(B.Mask);
  1689. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1690. if (PopCount == 1) {
  1691. // Testing for a single bit; just compare the shift count with what it
  1692. // would need to be to shift a 1 bit in that position.
  1693. Cmp = DAG.getSetCC(
  1694. getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(), VT), ShiftOp,
  1695. DAG.getConstant(countTrailingZeros(B.Mask), VT), ISD::SETEQ);
  1696. } else if (PopCount == BB.Range) {
  1697. // There is only one zero bit in the range, test for it directly.
  1698. Cmp = DAG.getSetCC(
  1699. getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(), VT), ShiftOp,
  1700. DAG.getConstant(CountTrailingOnes_64(B.Mask), VT), ISD::SETNE);
  1701. } else {
  1702. // Make desired shift
  1703. SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurSDLoc(), VT,
  1704. DAG.getConstant(1, VT), ShiftOp);
  1705. // Emit bit tests and jumps
  1706. SDValue AndOp = DAG.getNode(ISD::AND, getCurSDLoc(),
  1707. VT, SwitchVal, DAG.getConstant(B.Mask, VT));
  1708. Cmp = DAG.getSetCC(getCurSDLoc(),
  1709. TLI.getSetCCResultType(*DAG.getContext(), VT), AndOp,
  1710. DAG.getConstant(0, VT), ISD::SETNE);
  1711. }
  1712. // The branch weight from SwitchBB to B.TargetBB is B.ExtraWeight.
  1713. addSuccessorWithWeight(SwitchBB, B.TargetBB, B.ExtraWeight);
  1714. // The branch weight from SwitchBB to NextMBB is BranchWeightToNext.
  1715. addSuccessorWithWeight(SwitchBB, NextMBB, BranchWeightToNext);
  1716. SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
  1717. MVT::Other, getControlRoot(),
  1718. Cmp, DAG.getBasicBlock(B.TargetBB));
  1719. // Set NextBlock to be the MBB immediately after the current one, if any.
  1720. // This is used to avoid emitting unnecessary branches to the next block.
  1721. MachineBasicBlock *NextBlock = nullptr;
  1722. MachineFunction::iterator BBI = SwitchBB;
  1723. if (++BBI != FuncInfo.MF->end())
  1724. NextBlock = BBI;
  1725. if (NextMBB != NextBlock)
  1726. BrAnd = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrAnd,
  1727. DAG.getBasicBlock(NextMBB));
  1728. DAG.setRoot(BrAnd);
  1729. }
  1730. void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
  1731. MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
  1732. // Retrieve successors.
  1733. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
  1734. MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
  1735. const Value *Callee(I.getCalledValue());
  1736. const Function *Fn = dyn_cast<Function>(Callee);
  1737. if (isa<InlineAsm>(Callee))
  1738. visitInlineAsm(&I);
  1739. else if (Fn && Fn->isIntrinsic()) {
  1740. switch (Fn->getIntrinsicID()) {
  1741. default:
  1742. llvm_unreachable("Cannot invoke this intrinsic");
  1743. case Intrinsic::donothing:
  1744. // Ignore invokes to @llvm.donothing: jump directly to the next BB.
  1745. break;
  1746. case Intrinsic::experimental_patchpoint_void:
  1747. case Intrinsic::experimental_patchpoint_i64:
  1748. visitPatchpoint(&I, LandingPad);
  1749. break;
  1750. }
  1751. } else
  1752. LowerCallTo(&I, getValue(Callee), false, LandingPad);
  1753. // If the value of the invoke is used outside of its defining block, make it
  1754. // available as a virtual register.
  1755. CopyToExportRegsIfNeeded(&I);
  1756. // Update successor info
  1757. addSuccessorWithWeight(InvokeMBB, Return);
  1758. addSuccessorWithWeight(InvokeMBB, LandingPad);
  1759. // Drop into normal successor.
  1760. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  1761. MVT::Other, getControlRoot(),
  1762. DAG.getBasicBlock(Return)));
  1763. }
  1764. void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
  1765. llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
  1766. }
  1767. void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
  1768. assert(FuncInfo.MBB->isLandingPad() &&
  1769. "Call to landingpad not in landing pad!");
  1770. MachineBasicBlock *MBB = FuncInfo.MBB;
  1771. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  1772. AddLandingPadInfo(LP, MMI, MBB);
  1773. // If there aren't registers to copy the values into (e.g., during SjLj
  1774. // exceptions), then don't bother to create these DAG nodes.
  1775. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1776. if (TLI.getExceptionPointerRegister() == 0 &&
  1777. TLI.getExceptionSelectorRegister() == 0)
  1778. return;
  1779. SmallVector<EVT, 2> ValueVTs;
  1780. ComputeValueVTs(TLI, LP.getType(), ValueVTs);
  1781. assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
  1782. // Get the two live-in registers as SDValues. The physregs have already been
  1783. // copied into virtual registers.
  1784. SDValue Ops[2];
  1785. Ops[0] = DAG.getZExtOrTrunc(
  1786. DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
  1787. FuncInfo.ExceptionPointerVirtReg, TLI.getPointerTy()),
  1788. getCurSDLoc(), ValueVTs[0]);
  1789. Ops[1] = DAG.getZExtOrTrunc(
  1790. DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
  1791. FuncInfo.ExceptionSelectorVirtReg, TLI.getPointerTy()),
  1792. getCurSDLoc(), ValueVTs[1]);
  1793. // Merge into one.
  1794. SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  1795. DAG.getVTList(ValueVTs), Ops);
  1796. setValue(&LP, Res);
  1797. }
  1798. /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
  1799. /// small case ranges).
  1800. bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
  1801. CaseRecVector& WorkList,
  1802. const Value* SV,
  1803. MachineBasicBlock *Default,
  1804. MachineBasicBlock *SwitchBB) {
  1805. // Size is the number of Cases represented by this range.
  1806. size_t Size = CR.Range.second - CR.Range.first;
  1807. if (Size > 3)
  1808. return false;
  1809. // Get the MachineFunction which holds the current MBB. This is used when
  1810. // inserting any additional MBBs necessary to represent the switch.
  1811. MachineFunction *CurMF = FuncInfo.MF;
  1812. // Figure out which block is immediately after the current one.
  1813. MachineBasicBlock *NextBlock = nullptr;
  1814. MachineFunction::iterator BBI = CR.CaseBB;
  1815. if (++BBI != FuncInfo.MF->end())
  1816. NextBlock = BBI;
  1817. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1818. // If any two of the cases has the same destination, and if one value
  1819. // is the same as the other, but has one bit unset that the other has set,
  1820. // use bit manipulation to do two compares at once. For example:
  1821. // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
  1822. // TODO: This could be extended to merge any 2 cases in switches with 3 cases.
  1823. // TODO: Handle cases where CR.CaseBB != SwitchBB.
  1824. if (Size == 2 && CR.CaseBB == SwitchBB) {
  1825. Case &Small = *CR.Range.first;
  1826. Case &Big = *(CR.Range.second-1);
  1827. if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) {
  1828. const APInt& SmallValue = cast<ConstantInt>(Small.Low)->getValue();
  1829. const APInt& BigValue = cast<ConstantInt>(Big.Low)->getValue();
  1830. // Check that there is only one bit different.
  1831. if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 &&
  1832. (SmallValue | BigValue) == BigValue) {
  1833. // Isolate the common bit.
  1834. APInt CommonBit = BigValue & ~SmallValue;
  1835. assert((SmallValue | CommonBit) == BigValue &&
  1836. CommonBit.countPopulation() == 1 && "Not a common bit?");
  1837. SDValue CondLHS = getValue(SV);
  1838. EVT VT = CondLHS.getValueType();
  1839. SDLoc DL = getCurSDLoc();
  1840. SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
  1841. DAG.getConstant(CommonBit, VT));
  1842. SDValue Cond = DAG.getSetCC(DL, MVT::i1,
  1843. Or, DAG.getConstant(BigValue, VT),
  1844. ISD::SETEQ);
  1845. // Update successor info.
  1846. // Both Small and Big will jump to Small.BB, so we sum up the weights.
  1847. addSuccessorWithWeight(SwitchBB, Small.BB,
  1848. Small.ExtraWeight + Big.ExtraWeight);
  1849. addSuccessorWithWeight(SwitchBB, Default,
  1850. // The default destination is the first successor in IR.
  1851. BPI ? BPI->getEdgeWeight(SwitchBB->getBasicBlock(), (unsigned)0) : 0);
  1852. // Insert the true branch.
  1853. SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other,
  1854. getControlRoot(), Cond,
  1855. DAG.getBasicBlock(Small.BB));
  1856. // Insert the false branch.
  1857. BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
  1858. DAG.getBasicBlock(Default));
  1859. DAG.setRoot(BrCond);
  1860. return true;
  1861. }
  1862. }
  1863. }
  1864. // Order cases by weight so the most likely case will be checked first.
  1865. uint32_t UnhandledWeights = 0;
  1866. if (BPI) {
  1867. for (CaseItr I = CR.Range.first, IE = CR.Range.second; I != IE; ++I) {
  1868. uint32_t IWeight = I->ExtraWeight;
  1869. UnhandledWeights += IWeight;
  1870. for (CaseItr J = CR.Range.first; J < I; ++J) {
  1871. uint32_t JWeight = J->ExtraWeight;
  1872. if (IWeight > JWeight)
  1873. std::swap(*I, *J);
  1874. }
  1875. }
  1876. }
  1877. // Rearrange the case blocks so that the last one falls through if possible.
  1878. Case &BackCase = *(CR.Range.second-1);
  1879. if (Size > 1 &&
  1880. NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
  1881. // The last case block won't fall through into 'NextBlock' if we emit the
  1882. // branches in this order. See if rearranging a case value would help.
  1883. // We start at the bottom as it's the case with the least weight.
  1884. for (Case *I = &*(CR.Range.second-2), *E = &*CR.Range.first-1; I != E; --I)
  1885. if (I->BB == NextBlock) {
  1886. std::swap(*I, BackCase);
  1887. break;
  1888. }
  1889. }
  1890. // Create a CaseBlock record representing a conditional branch to
  1891. // the Case's target mbb if the value being switched on SV is equal
  1892. // to C.
  1893. MachineBasicBlock *CurBlock = CR.CaseBB;
  1894. for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
  1895. MachineBasicBlock *FallThrough;
  1896. if (I != E-1) {
  1897. FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
  1898. CurMF->insert(BBI, FallThrough);
  1899. // Put SV in a virtual register to make it available from the new blocks.
  1900. ExportFromCurrentBlock(SV);
  1901. } else {
  1902. // If the last case doesn't match, go to the default block.
  1903. FallThrough = Default;
  1904. }
  1905. const Value *RHS, *LHS, *MHS;
  1906. ISD::CondCode CC;
  1907. if (I->High == I->Low) {
  1908. // This is just small small case range :) containing exactly 1 case
  1909. CC = ISD::SETEQ;
  1910. LHS = SV; RHS = I->High; MHS = nullptr;
  1911. } else {
  1912. CC = ISD::SETLE;
  1913. LHS = I->Low; MHS = SV; RHS = I->High;
  1914. }
  1915. // The false weight should be sum of all un-handled cases.
  1916. UnhandledWeights -= I->ExtraWeight;
  1917. CaseBlock CB(CC, LHS, RHS, MHS, /* truebb */ I->BB, /* falsebb */ FallThrough,
  1918. /* me */ CurBlock,
  1919. /* trueweight */ I->ExtraWeight,
  1920. /* falseweight */ UnhandledWeights);
  1921. // If emitting the first comparison, just call visitSwitchCase to emit the
  1922. // code into the current block. Otherwise, push the CaseBlock onto the
  1923. // vector to be later processed by SDISel, and insert the node's MBB
  1924. // before the next MBB.
  1925. if (CurBlock == SwitchBB)
  1926. visitSwitchCase(CB, SwitchBB);
  1927. else
  1928. SwitchCases.push_back(CB);
  1929. CurBlock = FallThrough;
  1930. }
  1931. return true;
  1932. }
  1933. static inline bool areJTsAllowed(const TargetLowering &TLI) {
  1934. return TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
  1935. TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
  1936. }
  1937. static APInt ComputeRange(const APInt &First, const APInt &Last) {
  1938. uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
  1939. APInt LastExt = Last.sext(BitWidth), FirstExt = First.sext(BitWidth);
  1940. return (LastExt - FirstExt + 1ULL);
  1941. }
  1942. /// handleJTSwitchCase - Emit jumptable for current switch case range
  1943. bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec &CR,
  1944. CaseRecVector &WorkList,
  1945. const Value *SV,
  1946. MachineBasicBlock *Default,
  1947. MachineBasicBlock *SwitchBB) {
  1948. Case& FrontCase = *CR.Range.first;
  1949. Case& BackCase = *(CR.Range.second-1);
  1950. const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
  1951. const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
  1952. APInt TSize(First.getBitWidth(), 0);
  1953. for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I)
  1954. TSize += I->size();
  1955. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1956. if (!areJTsAllowed(TLI) || TSize.ult(TLI.getMinimumJumpTableEntries()))
  1957. return false;
  1958. APInt Range = ComputeRange(First, Last);
  1959. // The density is TSize / Range. Require at least 40%.
  1960. // It should not be possible for IntTSize to saturate for sane code, but make
  1961. // sure we handle Range saturation correctly.
  1962. uint64_t IntRange = Range.getLimitedValue(UINT64_MAX/10);
  1963. uint64_t IntTSize = TSize.getLimitedValue(UINT64_MAX/10);
  1964. if (IntTSize * 10 < IntRange * 4)
  1965. return false;
  1966. DEBUG(dbgs() << "Lowering jump table\n"
  1967. << "First entry: " << First << ". Last entry: " << Last << '\n'
  1968. << "Range: " << Range << ". Size: " << TSize << ".\n\n");
  1969. // Get the MachineFunction which holds the current MBB. This is used when
  1970. // inserting any additional MBBs necessary to represent the switch.
  1971. MachineFunction *CurMF = FuncInfo.MF;
  1972. // Figure out which block is immediately after the current one.
  1973. MachineFunction::iterator BBI = CR.CaseBB;
  1974. ++BBI;
  1975. const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
  1976. // Create a new basic block to hold the code for loading the address
  1977. // of the jump table, and jumping to it. Update successor information;
  1978. // we will either branch to the default case for the switch, or the jump
  1979. // table.
  1980. MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
  1981. CurMF->insert(BBI, JumpTableBB);
  1982. addSuccessorWithWeight(CR.CaseBB, Default);
  1983. addSuccessorWithWeight(CR.CaseBB, JumpTableBB);
  1984. // Build a vector of destination BBs, corresponding to each target
  1985. // of the jump table. If the value of the jump table slot corresponds to
  1986. // a case statement, push the case's BB onto the vector, otherwise, push
  1987. // the default BB.
  1988. std::vector<MachineBasicBlock*> DestBBs;
  1989. APInt TEI = First;
  1990. for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
  1991. const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
  1992. const APInt &High = cast<ConstantInt>(I->High)->getValue();
  1993. if (Low.sle(TEI) && TEI.sle(High)) {
  1994. DestBBs.push_back(I->BB);
  1995. if (TEI==High)
  1996. ++I;
  1997. } else {
  1998. DestBBs.push_back(Default);
  1999. }
  2000. }
  2001. // Calculate weight for each unique destination in CR.
  2002. DenseMap<MachineBasicBlock*, uint32_t> DestWeights;
  2003. if (FuncInfo.BPI)
  2004. for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
  2005. DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
  2006. DestWeights.find(I->BB);
  2007. if (Itr != DestWeights.end())
  2008. Itr->second += I->ExtraWeight;
  2009. else
  2010. DestWeights[I->BB] = I->ExtraWeight;
  2011. }
  2012. // Update successor info. Add one edge to each unique successor.
  2013. BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
  2014. for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
  2015. E = DestBBs.end(); I != E; ++I) {
  2016. if (!SuccsHandled[(*I)->getNumber()]) {
  2017. SuccsHandled[(*I)->getNumber()] = true;
  2018. DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
  2019. DestWeights.find(*I);
  2020. addSuccessorWithWeight(JumpTableBB, *I,
  2021. Itr != DestWeights.end() ? Itr->second : 0);
  2022. }
  2023. }
  2024. // Create a jump table index for this jump table.
  2025. unsigned JTEncoding = TLI.getJumpTableEncoding();
  2026. unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
  2027. ->createJumpTableIndex(DestBBs);
  2028. // Set the jump table information so that we can codegen it as a second
  2029. // MachineBasicBlock
  2030. JumpTable JT(-1U, JTI, JumpTableBB, Default);
  2031. JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB));
  2032. if (CR.CaseBB == SwitchBB)
  2033. visitJumpTableHeader(JT, JTH, SwitchBB);
  2034. JTCases.push_back(JumpTableBlock(JTH, JT));
  2035. return true;
  2036. }
  2037. /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
  2038. /// 2 subtrees.
  2039. bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
  2040. CaseRecVector& WorkList,
  2041. const Value* SV,
  2042. MachineBasicBlock* SwitchBB) {
  2043. // Get the MachineFunction which holds the current MBB. This is used when
  2044. // inserting any additional MBBs necessary to represent the switch.
  2045. MachineFunction *CurMF = FuncInfo.MF;
  2046. // Figure out which block is immediately after the current one.
  2047. MachineFunction::iterator BBI = CR.CaseBB;
  2048. ++BBI;
  2049. Case& FrontCase = *CR.Range.first;
  2050. Case& BackCase = *(CR.Range.second-1);
  2051. const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
  2052. // Size is the number of Cases represented by this range.
  2053. unsigned Size = CR.Range.second - CR.Range.first;
  2054. const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
  2055. const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
  2056. double FMetric = 0;
  2057. CaseItr Pivot = CR.Range.first + Size/2;
  2058. // Select optimal pivot, maximizing sum density of LHS and RHS. This will
  2059. // (heuristically) allow us to emit JumpTable's later.
  2060. APInt TSize(First.getBitWidth(), 0);
  2061. for (CaseItr I = CR.Range.first, E = CR.Range.second;
  2062. I!=E; ++I)
  2063. TSize += I->size();
  2064. APInt LSize = FrontCase.size();
  2065. APInt RSize = TSize-LSize;
  2066. DEBUG(dbgs() << "Selecting best pivot: \n"
  2067. << "First: " << First << ", Last: " << Last <<'\n'
  2068. << "LSize: " << LSize << ", RSize: " << RSize << '\n');
  2069. for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
  2070. J!=E; ++I, ++J) {
  2071. const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
  2072. const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
  2073. APInt Range = ComputeRange(LEnd, RBegin);
  2074. assert((Range - 2ULL).isNonNegative() &&
  2075. "Invalid case distance");
  2076. // Use volatile double here to avoid excess precision issues on some hosts,
  2077. // e.g. that use 80-bit X87 registers.
  2078. volatile double LDensity =
  2079. (double)LSize.roundToDouble() /
  2080. (LEnd - First + 1ULL).roundToDouble();
  2081. volatile double RDensity =
  2082. (double)RSize.roundToDouble() /
  2083. (Last - RBegin + 1ULL).roundToDouble();
  2084. volatile double Metric = Range.logBase2()*(LDensity+RDensity);
  2085. // Should always split in some non-trivial place
  2086. DEBUG(dbgs() <<"=>Step\n"
  2087. << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
  2088. << "LDensity: " << LDensity
  2089. << ", RDensity: " << RDensity << '\n'
  2090. << "Metric: " << Metric << '\n');
  2091. if (FMetric < Metric) {
  2092. Pivot = J;
  2093. FMetric = Metric;
  2094. DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
  2095. }
  2096. LSize += J->size();
  2097. RSize -= J->size();
  2098. }
  2099. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2100. if (areJTsAllowed(TLI)) {
  2101. // If our case is dense we *really* should handle it earlier!
  2102. assert((FMetric > 0) && "Should handle dense range earlier!");
  2103. } else {
  2104. Pivot = CR.Range.first + Size/2;
  2105. }
  2106. CaseRange LHSR(CR.Range.first, Pivot);
  2107. CaseRange RHSR(Pivot, CR.Range.second);
  2108. const Constant *C = Pivot->Low;
  2109. MachineBasicBlock *FalseBB = nullptr, *TrueBB = nullptr;
  2110. // We know that we branch to the LHS if the Value being switched on is
  2111. // less than the Pivot value, C. We use this to optimize our binary
  2112. // tree a bit, by recognizing that if SV is greater than or equal to the
  2113. // LHS's Case Value, and that Case Value is exactly one less than the
  2114. // Pivot's Value, then we can branch directly to the LHS's Target,
  2115. // rather than creating a leaf node for it.
  2116. if ((LHSR.second - LHSR.first) == 1 &&
  2117. LHSR.first->High == CR.GE &&
  2118. cast<ConstantInt>(C)->getValue() ==
  2119. (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
  2120. TrueBB = LHSR.first->BB;
  2121. } else {
  2122. TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
  2123. CurMF->insert(BBI, TrueBB);
  2124. WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
  2125. // Put SV in a virtual register to make it available from the new blocks.
  2126. ExportFromCurrentBlock(SV);
  2127. }
  2128. // Similar to the optimization above, if the Value being switched on is
  2129. // known to be less than the Constant CR.LT, and the current Case Value
  2130. // is CR.LT - 1, then we can branch directly to the target block for
  2131. // the current Case Value, rather than emitting a RHS leaf node for it.
  2132. if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
  2133. cast<ConstantInt>(RHSR.first->Low)->getValue() ==
  2134. (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
  2135. FalseBB = RHSR.first->BB;
  2136. } else {
  2137. FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
  2138. CurMF->insert(BBI, FalseBB);
  2139. WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
  2140. // Put SV in a virtual register to make it available from the new blocks.
  2141. ExportFromCurrentBlock(SV);
  2142. }
  2143. // Create a CaseBlock record representing a conditional branch to
  2144. // the LHS node if the value being switched on SV is less than C.
  2145. // Otherwise, branch to LHS.
  2146. CaseBlock CB(ISD::SETLT, SV, C, nullptr, TrueBB, FalseBB, CR.CaseBB);
  2147. if (CR.CaseBB == SwitchBB)
  2148. visitSwitchCase(CB, SwitchBB);
  2149. else
  2150. SwitchCases.push_back(CB);
  2151. return true;
  2152. }
  2153. /// handleBitTestsSwitchCase - if current case range has few destination and
  2154. /// range span less, than machine word bitwidth, encode case range into series
  2155. /// of masks and emit bit tests with these masks.
  2156. bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
  2157. CaseRecVector& WorkList,
  2158. const Value* SV,
  2159. MachineBasicBlock* Default,
  2160. MachineBasicBlock* SwitchBB) {
  2161. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2162. EVT PTy = TLI.getPointerTy();
  2163. unsigned IntPtrBits = PTy.getSizeInBits();
  2164. Case& FrontCase = *CR.Range.first;
  2165. Case& BackCase = *(CR.Range.second-1);
  2166. // Get the MachineFunction which holds the current MBB. This is used when
  2167. // inserting any additional MBBs necessary to represent the switch.
  2168. MachineFunction *CurMF = FuncInfo.MF;
  2169. // If target does not have legal shift left, do not emit bit tests at all.
  2170. if (!TLI.isOperationLegal(ISD::SHL, PTy))
  2171. return false;
  2172. size_t numCmps = 0;
  2173. for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
  2174. // Single case counts one, case range - two.
  2175. numCmps += (I->Low == I->High ? 1 : 2);
  2176. }
  2177. // Count unique destinations
  2178. SmallSet<MachineBasicBlock*, 4> Dests;
  2179. for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
  2180. Dests.insert(I->BB);
  2181. if (Dests.size() > 3)
  2182. // Don't bother the code below, if there are too much unique destinations
  2183. return false;
  2184. }
  2185. DEBUG(dbgs() << "Total number of unique destinations: "
  2186. << Dests.size() << '\n'
  2187. << "Total number of comparisons: " << numCmps << '\n');
  2188. // Compute span of values.
  2189. const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
  2190. const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
  2191. APInt cmpRange = maxValue - minValue;
  2192. DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
  2193. << "Low bound: " << minValue << '\n'
  2194. << "High bound: " << maxValue << '\n');
  2195. if (cmpRange.uge(IntPtrBits) ||
  2196. (!(Dests.size() == 1 && numCmps >= 3) &&
  2197. !(Dests.size() == 2 && numCmps >= 5) &&
  2198. !(Dests.size() >= 3 && numCmps >= 6)))
  2199. return false;
  2200. DEBUG(dbgs() << "Emitting bit tests\n");
  2201. APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
  2202. // Optimize the case where all the case values fit in a
  2203. // word without having to subtract minValue. In this case,
  2204. // we can optimize away the subtraction.
  2205. if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) {
  2206. cmpRange = maxValue;
  2207. } else {
  2208. lowBound = minValue;
  2209. }
  2210. CaseBitsVector CasesBits;
  2211. unsigned i, count = 0;
  2212. for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
  2213. MachineBasicBlock* Dest = I->BB;
  2214. for (i = 0; i < count; ++i)
  2215. if (Dest == CasesBits[i].BB)
  2216. break;
  2217. if (i == count) {
  2218. assert((count < 3) && "Too much destinations to test!");
  2219. CasesBits.push_back(CaseBits(0, Dest, 0, 0/*Weight*/));
  2220. count++;
  2221. }
  2222. const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
  2223. const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
  2224. uint64_t lo = (lowValue - lowBound).getZExtValue();
  2225. uint64_t hi = (highValue - lowBound).getZExtValue();
  2226. CasesBits[i].ExtraWeight += I->ExtraWeight;
  2227. for (uint64_t j = lo; j <= hi; j++) {
  2228. CasesBits[i].Mask |= 1ULL << j;
  2229. CasesBits[i].Bits++;
  2230. }
  2231. }
  2232. std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
  2233. BitTestInfo BTC;
  2234. // Figure out which block is immediately after the current one.
  2235. MachineFunction::iterator BBI = CR.CaseBB;
  2236. ++BBI;
  2237. const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
  2238. DEBUG(dbgs() << "Cases:\n");
  2239. for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
  2240. DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
  2241. << ", Bits: " << CasesBits[i].Bits
  2242. << ", BB: " << CasesBits[i].BB << '\n');
  2243. MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
  2244. CurMF->insert(BBI, CaseBB);
  2245. BTC.push_back(BitTestCase(CasesBits[i].Mask,
  2246. CaseBB,
  2247. CasesBits[i].BB, CasesBits[i].ExtraWeight));
  2248. // Put SV in a virtual register to make it available from the new blocks.
  2249. ExportFromCurrentBlock(SV);
  2250. }
  2251. BitTestBlock BTB(lowBound, cmpRange, SV,
  2252. -1U, MVT::Other, (CR.CaseBB == SwitchBB),
  2253. CR.CaseBB, Default, std::move(BTC));
  2254. if (CR.CaseBB == SwitchBB)
  2255. visitBitTestHeader(BTB, SwitchBB);
  2256. BitTestCases.push_back(std::move(BTB));
  2257. return true;
  2258. }
  2259. /// Clusterify - Transform simple list of Cases into list of CaseRange's
  2260. void SelectionDAGBuilder::Clusterify(CaseVector& Cases,
  2261. const SwitchInst& SI) {
  2262. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  2263. // Start with "simple" cases.
  2264. for (SwitchInst::ConstCaseIt i : SI.cases()) {
  2265. const BasicBlock *SuccBB = i.getCaseSuccessor();
  2266. MachineBasicBlock *SMBB = FuncInfo.MBBMap[SuccBB];
  2267. uint32_t ExtraWeight =
  2268. BPI ? BPI->getEdgeWeight(SI.getParent(), i.getSuccessorIndex()) : 0;
  2269. Cases.push_back(Case(i.getCaseValue(), i.getCaseValue(),
  2270. SMBB, ExtraWeight));
  2271. }
  2272. std::sort(Cases.begin(), Cases.end(), CaseCmp());
  2273. // Merge case into clusters
  2274. if (Cases.size() >= 2)
  2275. // Must recompute end() each iteration because it may be
  2276. // invalidated by erase if we hold on to it
  2277. for (CaseItr I = Cases.begin(), J = std::next(Cases.begin());
  2278. J != Cases.end(); ) {
  2279. const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
  2280. const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
  2281. MachineBasicBlock* nextBB = J->BB;
  2282. MachineBasicBlock* currentBB = I->BB;
  2283. // If the two neighboring cases go to the same destination, merge them
  2284. // into a single case.
  2285. if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
  2286. I->High = J->High;
  2287. I->ExtraWeight += J->ExtraWeight;
  2288. J = Cases.erase(J);
  2289. } else {
  2290. I = J++;
  2291. }
  2292. }
  2293. DEBUG({
  2294. size_t numCmps = 0;
  2295. for (auto &I : Cases)
  2296. // A range counts double, since it requires two compares.
  2297. numCmps += I.Low != I.High ? 2 : 1;
  2298. dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
  2299. << ". Total compares: " << numCmps << '\n';
  2300. });
  2301. }
  2302. void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
  2303. MachineBasicBlock *Last) {
  2304. // Update JTCases.
  2305. for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
  2306. if (JTCases[i].first.HeaderBB == First)
  2307. JTCases[i].first.HeaderBB = Last;
  2308. // Update BitTestCases.
  2309. for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
  2310. if (BitTestCases[i].Parent == First)
  2311. BitTestCases[i].Parent = Last;
  2312. }
  2313. void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
  2314. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  2315. // Figure out which block is immediately after the current one.
  2316. MachineBasicBlock *NextBlock = nullptr;
  2317. if (SwitchMBB + 1 != FuncInfo.MF->end())
  2318. NextBlock = SwitchMBB + 1;
  2319. // Create a vector of Cases, sorted so that we can efficiently create a binary
  2320. // search tree from them.
  2321. CaseVector Cases;
  2322. Clusterify(Cases, SI);
  2323. // Get the default destination MBB.
  2324. MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
  2325. if (isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg()) &&
  2326. !Cases.empty()) {
  2327. // Replace an unreachable default destination with the most popular case
  2328. // destination.
  2329. DenseMap<const BasicBlock *, uint64_t> Popularity;
  2330. uint64_t MaxPop = 0;
  2331. const BasicBlock *MaxBB = nullptr;
  2332. for (auto I : SI.cases()) {
  2333. const BasicBlock *BB = I.getCaseSuccessor();
  2334. if (++Popularity[BB] > MaxPop) {
  2335. MaxPop = Popularity[BB];
  2336. MaxBB = BB;
  2337. }
  2338. }
  2339. // Set new default.
  2340. assert(MaxPop > 0);
  2341. assert(MaxBB);
  2342. Default = FuncInfo.MBBMap[MaxBB];
  2343. // Remove cases that were pointing to the destination that is now the default.
  2344. Cases.erase(std::remove_if(Cases.begin(), Cases.end(),
  2345. [&](const Case &C) { return C.BB == Default; }),
  2346. Cases.end());
  2347. }
  2348. // If there is only the default destination, go there directly.
  2349. if (Cases.empty()) {
  2350. // Update machine-CFG edges.
  2351. SwitchMBB->addSuccessor(Default);
  2352. // If this is not a fall-through branch, emit the branch.
  2353. if (Default != NextBlock) {
  2354. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  2355. getControlRoot(), DAG.getBasicBlock(Default)));
  2356. }
  2357. return;
  2358. }
  2359. // Get the Value to be switched on.
  2360. const Value *SV = SI.getCondition();
  2361. // Push the initial CaseRec onto the worklist
  2362. CaseRecVector WorkList;
  2363. WorkList.push_back(CaseRec(SwitchMBB,nullptr,nullptr,
  2364. CaseRange(Cases.begin(),Cases.end())));
  2365. while (!WorkList.empty()) {
  2366. // Grab a record representing a case range to process off the worklist
  2367. CaseRec CR = WorkList.back();
  2368. WorkList.pop_back();
  2369. if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
  2370. continue;
  2371. // If the range has few cases (two or less) emit a series of specific
  2372. // tests.
  2373. if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB))
  2374. continue;
  2375. // If the switch has more than N blocks, and is at least 40% dense, and the
  2376. // target supports indirect branches, then emit a jump table rather than
  2377. // lowering the switch to a binary tree of conditional branches.
  2378. // N defaults to 4 and is controlled via TLS.getMinimumJumpTableEntries().
  2379. if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
  2380. continue;
  2381. // Emit binary tree. We need to pick a pivot, and push left and right ranges
  2382. // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
  2383. handleBTSplitSwitchCase(CR, WorkList, SV, SwitchMBB);
  2384. }
  2385. }
  2386. void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
  2387. MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
  2388. // Update machine-CFG edges with unique successors.
  2389. SmallSet<BasicBlock*, 32> Done;
  2390. for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
  2391. BasicBlock *BB = I.getSuccessor(i);
  2392. bool Inserted = Done.insert(BB).second;
  2393. if (!Inserted)
  2394. continue;
  2395. MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
  2396. addSuccessorWithWeight(IndirectBrMBB, Succ);
  2397. }
  2398. DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
  2399. MVT::Other, getControlRoot(),
  2400. getValue(I.getAddress())));
  2401. }
  2402. void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
  2403. if (DAG.getTarget().Options.TrapUnreachable)
  2404. DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
  2405. }
  2406. void SelectionDAGBuilder::visitFSub(const User &I) {
  2407. // -0.0 - X --> fneg
  2408. Type *Ty = I.getType();
  2409. if (isa<Constant>(I.getOperand(0)) &&
  2410. I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
  2411. SDValue Op2 = getValue(I.getOperand(1));
  2412. setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
  2413. Op2.getValueType(), Op2));
  2414. return;
  2415. }
  2416. visitBinary(I, ISD::FSUB);
  2417. }
  2418. void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
  2419. SDValue Op1 = getValue(I.getOperand(0));
  2420. SDValue Op2 = getValue(I.getOperand(1));
  2421. bool nuw = false;
  2422. bool nsw = false;
  2423. bool exact = false;
  2424. if (const OverflowingBinaryOperator *OFBinOp =
  2425. dyn_cast<const OverflowingBinaryOperator>(&I)) {
  2426. nuw = OFBinOp->hasNoUnsignedWrap();
  2427. nsw = OFBinOp->hasNoSignedWrap();
  2428. }
  2429. if (const PossiblyExactOperator *ExactOp =
  2430. dyn_cast<const PossiblyExactOperator>(&I))
  2431. exact = ExactOp->isExact();
  2432. SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(),
  2433. Op1, Op2, nuw, nsw, exact);
  2434. setValue(&I, BinNodeValue);
  2435. }
  2436. void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
  2437. SDValue Op1 = getValue(I.getOperand(0));
  2438. SDValue Op2 = getValue(I.getOperand(1));
  2439. EVT ShiftTy =
  2440. DAG.getTargetLoweringInfo().getShiftAmountTy(Op2.getValueType());
  2441. // Coerce the shift amount to the right type if we can.
  2442. if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
  2443. unsigned ShiftSize = ShiftTy.getSizeInBits();
  2444. unsigned Op2Size = Op2.getValueType().getSizeInBits();
  2445. SDLoc DL = getCurSDLoc();
  2446. // If the operand is smaller than the shift count type, promote it.
  2447. if (ShiftSize > Op2Size)
  2448. Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
  2449. // If the operand is larger than the shift count type but the shift
  2450. // count type has enough bits to represent any shift value, truncate
  2451. // it now. This is a common case and it exposes the truncate to
  2452. // optimization early.
  2453. else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
  2454. Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
  2455. // Otherwise we'll need to temporarily settle for some other convenient
  2456. // type. Type legalization will make adjustments once the shiftee is split.
  2457. else
  2458. Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
  2459. }
  2460. bool nuw = false;
  2461. bool nsw = false;
  2462. bool exact = false;
  2463. if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
  2464. if (const OverflowingBinaryOperator *OFBinOp =
  2465. dyn_cast<const OverflowingBinaryOperator>(&I)) {
  2466. nuw = OFBinOp->hasNoUnsignedWrap();
  2467. nsw = OFBinOp->hasNoSignedWrap();
  2468. }
  2469. if (const PossiblyExactOperator *ExactOp =
  2470. dyn_cast<const PossiblyExactOperator>(&I))
  2471. exact = ExactOp->isExact();
  2472. }
  2473. SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
  2474. nuw, nsw, exact);
  2475. setValue(&I, Res);
  2476. }
  2477. void SelectionDAGBuilder::visitSDiv(const User &I) {
  2478. SDValue Op1 = getValue(I.getOperand(0));
  2479. SDValue Op2 = getValue(I.getOperand(1));
  2480. // Turn exact SDivs into multiplications.
  2481. // FIXME: This should be in DAGCombiner, but it doesn't have access to the
  2482. // exact bit.
  2483. if (isa<BinaryOperator>(&I) && cast<BinaryOperator>(&I)->isExact() &&
  2484. !isa<ConstantSDNode>(Op1) &&
  2485. isa<ConstantSDNode>(Op2) && !cast<ConstantSDNode>(Op2)->isNullValue())
  2486. setValue(&I, DAG.getTargetLoweringInfo()
  2487. .BuildExactSDIV(Op1, Op2, getCurSDLoc(), DAG));
  2488. else
  2489. setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(),
  2490. Op1, Op2));
  2491. }
  2492. void SelectionDAGBuilder::visitICmp(const User &I) {
  2493. ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
  2494. if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
  2495. predicate = IC->getPredicate();
  2496. else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
  2497. predicate = ICmpInst::Predicate(IC->getPredicate());
  2498. SDValue Op1 = getValue(I.getOperand(0));
  2499. SDValue Op2 = getValue(I.getOperand(1));
  2500. ISD::CondCode Opcode = getICmpCondCode(predicate);
  2501. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
  2502. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
  2503. }
  2504. void SelectionDAGBuilder::visitFCmp(const User &I) {
  2505. FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
  2506. if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
  2507. predicate = FC->getPredicate();
  2508. else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
  2509. predicate = FCmpInst::Predicate(FC->getPredicate());
  2510. SDValue Op1 = getValue(I.getOperand(0));
  2511. SDValue Op2 = getValue(I.getOperand(1));
  2512. ISD::CondCode Condition = getFCmpCondCode(predicate);
  2513. if (TM.Options.NoNaNsFPMath)
  2514. Condition = getFCmpCodeWithoutNaN(Condition);
  2515. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
  2516. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
  2517. }
  2518. void SelectionDAGBuilder::visitSelect(const User &I) {
  2519. SmallVector<EVT, 4> ValueVTs;
  2520. ComputeValueVTs(DAG.getTargetLoweringInfo(), I.getType(), ValueVTs);
  2521. unsigned NumValues = ValueVTs.size();
  2522. if (NumValues == 0) return;
  2523. SmallVector<SDValue, 4> Values(NumValues);
  2524. SDValue Cond = getValue(I.getOperand(0));
  2525. SDValue TrueVal = getValue(I.getOperand(1));
  2526. SDValue FalseVal = getValue(I.getOperand(2));
  2527. ISD::NodeType OpCode = Cond.getValueType().isVector() ?
  2528. ISD::VSELECT : ISD::SELECT;
  2529. for (unsigned i = 0; i != NumValues; ++i)
  2530. Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
  2531. TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
  2532. Cond,
  2533. SDValue(TrueVal.getNode(),
  2534. TrueVal.getResNo() + i),
  2535. SDValue(FalseVal.getNode(),
  2536. FalseVal.getResNo() + i));
  2537. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2538. DAG.getVTList(ValueVTs), Values));
  2539. }
  2540. void SelectionDAGBuilder::visitTrunc(const User &I) {
  2541. // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
  2542. SDValue N = getValue(I.getOperand(0));
  2543. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
  2544. setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
  2545. }
  2546. void SelectionDAGBuilder::visitZExt(const User &I) {
  2547. // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2548. // ZExt also can't be a cast to bool for same reason. So, nothing much to do
  2549. SDValue N = getValue(I.getOperand(0));
  2550. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
  2551. setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
  2552. }
  2553. void SelectionDAGBuilder::visitSExt(const User &I) {
  2554. // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2555. // SExt also can't be a cast to bool for same reason. So, nothing much to do
  2556. SDValue N = getValue(I.getOperand(0));
  2557. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
  2558. setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
  2559. }
  2560. void SelectionDAGBuilder::visitFPTrunc(const User &I) {
  2561. // FPTrunc is never a no-op cast, no need to check
  2562. SDValue N = getValue(I.getOperand(0));
  2563. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2564. EVT DestVT = TLI.getValueType(I.getType());
  2565. setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurSDLoc(), DestVT, N,
  2566. DAG.getTargetConstant(0, TLI.getPointerTy())));
  2567. }
  2568. void SelectionDAGBuilder::visitFPExt(const User &I) {
  2569. // FPExt is never a no-op cast, no need to check
  2570. SDValue N = getValue(I.getOperand(0));
  2571. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
  2572. setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
  2573. }
  2574. void SelectionDAGBuilder::visitFPToUI(const User &I) {
  2575. // FPToUI is never a no-op cast, no need to check
  2576. SDValue N = getValue(I.getOperand(0));
  2577. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
  2578. setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
  2579. }
  2580. void SelectionDAGBuilder::visitFPToSI(const User &I) {
  2581. // FPToSI is never a no-op cast, no need to check
  2582. SDValue N = getValue(I.getOperand(0));
  2583. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
  2584. setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
  2585. }
  2586. void SelectionDAGBuilder::visitUIToFP(const User &I) {
  2587. // UIToFP is never a no-op cast, no need to check
  2588. SDValue N = getValue(I.getOperand(0));
  2589. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
  2590. setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
  2591. }
  2592. void SelectionDAGBuilder::visitSIToFP(const User &I) {
  2593. // SIToFP is never a no-op cast, no need to check
  2594. SDValue N = getValue(I.getOperand(0));
  2595. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
  2596. setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
  2597. }
  2598. void SelectionDAGBuilder::visitPtrToInt(const User &I) {
  2599. // What to do depends on the size of the integer and the size of the pointer.
  2600. // We can either truncate, zero extend, or no-op, accordingly.
  2601. SDValue N = getValue(I.getOperand(0));
  2602. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
  2603. setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
  2604. }
  2605. void SelectionDAGBuilder::visitIntToPtr(const User &I) {
  2606. // What to do depends on the size of the integer and the size of the pointer.
  2607. // We can either truncate, zero extend, or no-op, accordingly.
  2608. SDValue N = getValue(I.getOperand(0));
  2609. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
  2610. setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
  2611. }
  2612. void SelectionDAGBuilder::visitBitCast(const User &I) {
  2613. SDValue N = getValue(I.getOperand(0));
  2614. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
  2615. // BitCast assures us that source and destination are the same size so this is
  2616. // either a BITCAST or a no-op.
  2617. if (DestVT != N.getValueType())
  2618. setValue(&I, DAG.getNode(ISD::BITCAST, getCurSDLoc(),
  2619. DestVT, N)); // convert types.
  2620. // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
  2621. // might fold any kind of constant expression to an integer constant and that
  2622. // is not what we are looking for. Only regcognize a bitcast of a genuine
  2623. // constant integer as an opaque constant.
  2624. else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
  2625. setValue(&I, DAG.getConstant(C->getValue(), DestVT, /*isTarget=*/false,
  2626. /*isOpaque*/true));
  2627. else
  2628. setValue(&I, N); // noop cast.
  2629. }
  2630. void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
  2631. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2632. const Value *SV = I.getOperand(0);
  2633. SDValue N = getValue(SV);
  2634. EVT DestVT = TLI.getValueType(I.getType());
  2635. unsigned SrcAS = SV->getType()->getPointerAddressSpace();
  2636. unsigned DestAS = I.getType()->getPointerAddressSpace();
  2637. if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
  2638. N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
  2639. setValue(&I, N);
  2640. }
  2641. void SelectionDAGBuilder::visitInsertElement(const User &I) {
  2642. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2643. SDValue InVec = getValue(I.getOperand(0));
  2644. SDValue InVal = getValue(I.getOperand(1));
  2645. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)),
  2646. getCurSDLoc(), TLI.getVectorIdxTy());
  2647. setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
  2648. TLI.getValueType(I.getType()), InVec, InVal, InIdx));
  2649. }
  2650. void SelectionDAGBuilder::visitExtractElement(const User &I) {
  2651. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2652. SDValue InVec = getValue(I.getOperand(0));
  2653. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)),
  2654. getCurSDLoc(), TLI.getVectorIdxTy());
  2655. setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
  2656. TLI.getValueType(I.getType()), InVec, InIdx));
  2657. }
  2658. // Utility for visitShuffleVector - Return true if every element in Mask,
  2659. // beginning from position Pos and ending in Pos+Size, falls within the
  2660. // specified sequential range [L, L+Pos). or is undef.
  2661. static bool isSequentialInRange(const SmallVectorImpl<int> &Mask,
  2662. unsigned Pos, unsigned Size, int Low) {
  2663. for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
  2664. if (Mask[i] >= 0 && Mask[i] != Low)
  2665. return false;
  2666. return true;
  2667. }
  2668. void SelectionDAGBuilder::visitShuffleVector(const User &I) {
  2669. SDValue Src1 = getValue(I.getOperand(0));
  2670. SDValue Src2 = getValue(I.getOperand(1));
  2671. SmallVector<int, 8> Mask;
  2672. ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
  2673. unsigned MaskNumElts = Mask.size();
  2674. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2675. EVT VT = TLI.getValueType(I.getType());
  2676. EVT SrcVT = Src1.getValueType();
  2677. unsigned SrcNumElts = SrcVT.getVectorNumElements();
  2678. if (SrcNumElts == MaskNumElts) {
  2679. setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
  2680. &Mask[0]));
  2681. return;
  2682. }
  2683. // Normalize the shuffle vector since mask and vector length don't match.
  2684. if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
  2685. // Mask is longer than the source vectors and is a multiple of the source
  2686. // vectors. We can use concatenate vector to make the mask and vectors
  2687. // lengths match.
  2688. if (SrcNumElts*2 == MaskNumElts) {
  2689. // First check for Src1 in low and Src2 in high
  2690. if (isSequentialInRange(Mask, 0, SrcNumElts, 0) &&
  2691. isSequentialInRange(Mask, SrcNumElts, SrcNumElts, SrcNumElts)) {
  2692. // The shuffle is concatenating two vectors together.
  2693. setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
  2694. VT, Src1, Src2));
  2695. return;
  2696. }
  2697. // Then check for Src2 in low and Src1 in high
  2698. if (isSequentialInRange(Mask, 0, SrcNumElts, SrcNumElts) &&
  2699. isSequentialInRange(Mask, SrcNumElts, SrcNumElts, 0)) {
  2700. // The shuffle is concatenating two vectors together.
  2701. setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
  2702. VT, Src2, Src1));
  2703. return;
  2704. }
  2705. }
  2706. // Pad both vectors with undefs to make them the same length as the mask.
  2707. unsigned NumConcat = MaskNumElts / SrcNumElts;
  2708. bool Src1U = Src1.getOpcode() == ISD::UNDEF;
  2709. bool Src2U = Src2.getOpcode() == ISD::UNDEF;
  2710. SDValue UndefVal = DAG.getUNDEF(SrcVT);
  2711. SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
  2712. SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
  2713. MOps1[0] = Src1;
  2714. MOps2[0] = Src2;
  2715. Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
  2716. getCurSDLoc(), VT, MOps1);
  2717. Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
  2718. getCurSDLoc(), VT, MOps2);
  2719. // Readjust mask for new input vector length.
  2720. SmallVector<int, 8> MappedOps;
  2721. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2722. int Idx = Mask[i];
  2723. if (Idx >= (int)SrcNumElts)
  2724. Idx -= SrcNumElts - MaskNumElts;
  2725. MappedOps.push_back(Idx);
  2726. }
  2727. setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
  2728. &MappedOps[0]));
  2729. return;
  2730. }
  2731. if (SrcNumElts > MaskNumElts) {
  2732. // Analyze the access pattern of the vector to see if we can extract
  2733. // two subvectors and do the shuffle. The analysis is done by calculating
  2734. // the range of elements the mask access on both vectors.
  2735. int MinRange[2] = { static_cast<int>(SrcNumElts),
  2736. static_cast<int>(SrcNumElts)};
  2737. int MaxRange[2] = {-1, -1};
  2738. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2739. int Idx = Mask[i];
  2740. unsigned Input = 0;
  2741. if (Idx < 0)
  2742. continue;
  2743. if (Idx >= (int)SrcNumElts) {
  2744. Input = 1;
  2745. Idx -= SrcNumElts;
  2746. }
  2747. if (Idx > MaxRange[Input])
  2748. MaxRange[Input] = Idx;
  2749. if (Idx < MinRange[Input])
  2750. MinRange[Input] = Idx;
  2751. }
  2752. // Check if the access is smaller than the vector size and can we find
  2753. // a reasonable extract index.
  2754. int RangeUse[2] = { -1, -1 }; // 0 = Unused, 1 = Extract, -1 = Can not
  2755. // Extract.
  2756. int StartIdx[2]; // StartIdx to extract from
  2757. for (unsigned Input = 0; Input < 2; ++Input) {
  2758. if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) {
  2759. RangeUse[Input] = 0; // Unused
  2760. StartIdx[Input] = 0;
  2761. continue;
  2762. }
  2763. // Find a good start index that is a multiple of the mask length. Then
  2764. // see if the rest of the elements are in range.
  2765. StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
  2766. if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
  2767. StartIdx[Input] + MaskNumElts <= SrcNumElts)
  2768. RangeUse[Input] = 1; // Extract from a multiple of the mask length.
  2769. }
  2770. if (RangeUse[0] == 0 && RangeUse[1] == 0) {
  2771. setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
  2772. return;
  2773. }
  2774. if (RangeUse[0] >= 0 && RangeUse[1] >= 0) {
  2775. // Extract appropriate subvector and generate a vector shuffle
  2776. for (unsigned Input = 0; Input < 2; ++Input) {
  2777. SDValue &Src = Input == 0 ? Src1 : Src2;
  2778. if (RangeUse[Input] == 0)
  2779. Src = DAG.getUNDEF(VT);
  2780. else
  2781. Src = DAG.getNode(
  2782. ISD::EXTRACT_SUBVECTOR, getCurSDLoc(), VT, Src,
  2783. DAG.getConstant(StartIdx[Input], TLI.getVectorIdxTy()));
  2784. }
  2785. // Calculate new mask.
  2786. SmallVector<int, 8> MappedOps;
  2787. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2788. int Idx = Mask[i];
  2789. if (Idx >= 0) {
  2790. if (Idx < (int)SrcNumElts)
  2791. Idx -= StartIdx[0];
  2792. else
  2793. Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
  2794. }
  2795. MappedOps.push_back(Idx);
  2796. }
  2797. setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
  2798. &MappedOps[0]));
  2799. return;
  2800. }
  2801. }
  2802. // We can't use either concat vectors or extract subvectors so fall back to
  2803. // replacing the shuffle with extract and build vector.
  2804. // to insert and build vector.
  2805. EVT EltVT = VT.getVectorElementType();
  2806. EVT IdxVT = TLI.getVectorIdxTy();
  2807. SmallVector<SDValue,8> Ops;
  2808. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2809. int Idx = Mask[i];
  2810. SDValue Res;
  2811. if (Idx < 0) {
  2812. Res = DAG.getUNDEF(EltVT);
  2813. } else {
  2814. SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
  2815. if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
  2816. Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
  2817. EltVT, Src, DAG.getConstant(Idx, IdxVT));
  2818. }
  2819. Ops.push_back(Res);
  2820. }
  2821. setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops));
  2822. }
  2823. void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
  2824. const Value *Op0 = I.getOperand(0);
  2825. const Value *Op1 = I.getOperand(1);
  2826. Type *AggTy = I.getType();
  2827. Type *ValTy = Op1->getType();
  2828. bool IntoUndef = isa<UndefValue>(Op0);
  2829. bool FromUndef = isa<UndefValue>(Op1);
  2830. unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
  2831. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2832. SmallVector<EVT, 4> AggValueVTs;
  2833. ComputeValueVTs(TLI, AggTy, AggValueVTs);
  2834. SmallVector<EVT, 4> ValValueVTs;
  2835. ComputeValueVTs(TLI, ValTy, ValValueVTs);
  2836. unsigned NumAggValues = AggValueVTs.size();
  2837. unsigned NumValValues = ValValueVTs.size();
  2838. SmallVector<SDValue, 4> Values(NumAggValues);
  2839. // Ignore an insertvalue that produces an empty object
  2840. if (!NumAggValues) {
  2841. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  2842. return;
  2843. }
  2844. SDValue Agg = getValue(Op0);
  2845. unsigned i = 0;
  2846. // Copy the beginning value(s) from the original aggregate.
  2847. for (; i != LinearIndex; ++i)
  2848. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2849. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2850. // Copy values from the inserted value(s).
  2851. if (NumValValues) {
  2852. SDValue Val = getValue(Op1);
  2853. for (; i != LinearIndex + NumValValues; ++i)
  2854. Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2855. SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
  2856. }
  2857. // Copy remaining value(s) from the original aggregate.
  2858. for (; i != NumAggValues; ++i)
  2859. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2860. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2861. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2862. DAG.getVTList(AggValueVTs), Values));
  2863. }
  2864. void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
  2865. const Value *Op0 = I.getOperand(0);
  2866. Type *AggTy = Op0->getType();
  2867. Type *ValTy = I.getType();
  2868. bool OutOfUndef = isa<UndefValue>(Op0);
  2869. unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
  2870. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2871. SmallVector<EVT, 4> ValValueVTs;
  2872. ComputeValueVTs(TLI, ValTy, ValValueVTs);
  2873. unsigned NumValValues = ValValueVTs.size();
  2874. // Ignore a extractvalue that produces an empty object
  2875. if (!NumValValues) {
  2876. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  2877. return;
  2878. }
  2879. SmallVector<SDValue, 4> Values(NumValValues);
  2880. SDValue Agg = getValue(Op0);
  2881. // Copy out the selected value(s).
  2882. for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
  2883. Values[i - LinearIndex] =
  2884. OutOfUndef ?
  2885. DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
  2886. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2887. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2888. DAG.getVTList(ValValueVTs), Values));
  2889. }
  2890. void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
  2891. Value *Op0 = I.getOperand(0);
  2892. // Note that the pointer operand may be a vector of pointers. Take the scalar
  2893. // element which holds a pointer.
  2894. Type *Ty = Op0->getType()->getScalarType();
  2895. unsigned AS = Ty->getPointerAddressSpace();
  2896. SDValue N = getValue(Op0);
  2897. for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
  2898. OI != E; ++OI) {
  2899. const Value *Idx = *OI;
  2900. if (StructType *StTy = dyn_cast<StructType>(Ty)) {
  2901. unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
  2902. if (Field) {
  2903. // N = N + Offset
  2904. uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
  2905. N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
  2906. DAG.getConstant(Offset, N.getValueType()));
  2907. }
  2908. Ty = StTy->getElementType(Field);
  2909. } else {
  2910. Ty = cast<SequentialType>(Ty)->getElementType();
  2911. // If this is a constant subscript, handle it quickly.
  2912. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2913. if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
  2914. if (CI->isZero()) continue;
  2915. uint64_t Offs =
  2916. DL->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
  2917. SDValue OffsVal;
  2918. EVT PTy = TLI.getPointerTy(AS);
  2919. unsigned PtrBits = PTy.getSizeInBits();
  2920. if (PtrBits < 64)
  2921. OffsVal = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), PTy,
  2922. DAG.getConstant(Offs, MVT::i64));
  2923. else
  2924. OffsVal = DAG.getConstant(Offs, PTy);
  2925. N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
  2926. OffsVal);
  2927. continue;
  2928. }
  2929. // N = N + Idx * ElementSize;
  2930. APInt ElementSize =
  2931. APInt(TLI.getPointerSizeInBits(AS), DL->getTypeAllocSize(Ty));
  2932. SDValue IdxN = getValue(Idx);
  2933. // If the index is smaller or larger than intptr_t, truncate or extend
  2934. // it.
  2935. IdxN = DAG.getSExtOrTrunc(IdxN, getCurSDLoc(), N.getValueType());
  2936. // If this is a multiply by a power of two, turn it into a shl
  2937. // immediately. This is a very common case.
  2938. if (ElementSize != 1) {
  2939. if (ElementSize.isPowerOf2()) {
  2940. unsigned Amt = ElementSize.logBase2();
  2941. IdxN = DAG.getNode(ISD::SHL, getCurSDLoc(),
  2942. N.getValueType(), IdxN,
  2943. DAG.getConstant(Amt, IdxN.getValueType()));
  2944. } else {
  2945. SDValue Scale = DAG.getConstant(ElementSize, IdxN.getValueType());
  2946. IdxN = DAG.getNode(ISD::MUL, getCurSDLoc(),
  2947. N.getValueType(), IdxN, Scale);
  2948. }
  2949. }
  2950. N = DAG.getNode(ISD::ADD, getCurSDLoc(),
  2951. N.getValueType(), N, IdxN);
  2952. }
  2953. }
  2954. setValue(&I, N);
  2955. }
  2956. void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
  2957. // If this is a fixed sized alloca in the entry block of the function,
  2958. // allocate it statically on the stack.
  2959. if (FuncInfo.StaticAllocaMap.count(&I))
  2960. return; // getValue will auto-populate this.
  2961. Type *Ty = I.getAllocatedType();
  2962. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2963. uint64_t TySize = TLI.getDataLayout()->getTypeAllocSize(Ty);
  2964. unsigned Align =
  2965. std::max((unsigned)TLI.getDataLayout()->getPrefTypeAlignment(Ty),
  2966. I.getAlignment());
  2967. SDValue AllocSize = getValue(I.getArraySize());
  2968. EVT IntPtr = TLI.getPointerTy();
  2969. if (AllocSize.getValueType() != IntPtr)
  2970. AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurSDLoc(), IntPtr);
  2971. AllocSize = DAG.getNode(ISD::MUL, getCurSDLoc(), IntPtr,
  2972. AllocSize,
  2973. DAG.getConstant(TySize, IntPtr));
  2974. // Handle alignment. If the requested alignment is less than or equal to
  2975. // the stack alignment, ignore it. If the size is greater than or equal to
  2976. // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
  2977. unsigned StackAlign =
  2978. DAG.getSubtarget().getFrameLowering()->getStackAlignment();
  2979. if (Align <= StackAlign)
  2980. Align = 0;
  2981. // Round the size of the allocation up to the stack alignment size
  2982. // by add SA-1 to the size.
  2983. AllocSize = DAG.getNode(ISD::ADD, getCurSDLoc(),
  2984. AllocSize.getValueType(), AllocSize,
  2985. DAG.getIntPtrConstant(StackAlign-1));
  2986. // Mask out the low bits for alignment purposes.
  2987. AllocSize = DAG.getNode(ISD::AND, getCurSDLoc(),
  2988. AllocSize.getValueType(), AllocSize,
  2989. DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
  2990. SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
  2991. SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
  2992. SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurSDLoc(), VTs, Ops);
  2993. setValue(&I, DSA);
  2994. DAG.setRoot(DSA.getValue(1));
  2995. assert(FuncInfo.MF->getFrameInfo()->hasVarSizedObjects());
  2996. }
  2997. void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
  2998. if (I.isAtomic())
  2999. return visitAtomicLoad(I);
  3000. const Value *SV = I.getOperand(0);
  3001. SDValue Ptr = getValue(SV);
  3002. Type *Ty = I.getType();
  3003. bool isVolatile = I.isVolatile();
  3004. bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
  3005. bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
  3006. unsigned Alignment = I.getAlignment();
  3007. AAMDNodes AAInfo;
  3008. I.getAAMetadata(AAInfo);
  3009. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3010. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3011. SmallVector<EVT, 4> ValueVTs;
  3012. SmallVector<uint64_t, 4> Offsets;
  3013. ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
  3014. unsigned NumValues = ValueVTs.size();
  3015. if (NumValues == 0)
  3016. return;
  3017. SDValue Root;
  3018. bool ConstantMemory = false;
  3019. if (isVolatile || NumValues > MaxParallelChains)
  3020. // Serialize volatile loads with other side effects.
  3021. Root = getRoot();
  3022. else if (AA->pointsToConstantMemory(
  3023. AliasAnalysis::Location(SV, AA->getTypeStoreSize(Ty), AAInfo))) {
  3024. // Do not serialize (non-volatile) loads of constant memory with anything.
  3025. Root = DAG.getEntryNode();
  3026. ConstantMemory = true;
  3027. } else {
  3028. // Do not serialize non-volatile loads against each other.
  3029. Root = DAG.getRoot();
  3030. }
  3031. if (isVolatile)
  3032. Root = TLI.prepareVolatileOrAtomicLoad(Root, getCurSDLoc(), DAG);
  3033. SmallVector<SDValue, 4> Values(NumValues);
  3034. SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
  3035. NumValues));
  3036. EVT PtrVT = Ptr.getValueType();
  3037. unsigned ChainI = 0;
  3038. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3039. // Serializing loads here may result in excessive register pressure, and
  3040. // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
  3041. // could recover a bit by hoisting nodes upward in the chain by recognizing
  3042. // they are side-effect free or do not alias. The optimizer should really
  3043. // avoid this case by converting large object/array copies to llvm.memcpy
  3044. // (MaxParallelChains should always remain as failsafe).
  3045. if (ChainI == MaxParallelChains) {
  3046. assert(PendingLoads.empty() && "PendingLoads must be serialized first");
  3047. SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  3048. makeArrayRef(Chains.data(), ChainI));
  3049. Root = Chain;
  3050. ChainI = 0;
  3051. }
  3052. SDValue A = DAG.getNode(ISD::ADD, getCurSDLoc(),
  3053. PtrVT, Ptr,
  3054. DAG.getConstant(Offsets[i], PtrVT));
  3055. SDValue L = DAG.getLoad(ValueVTs[i], getCurSDLoc(), Root,
  3056. A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
  3057. isNonTemporal, isInvariant, Alignment, AAInfo,
  3058. Ranges);
  3059. Values[i] = L;
  3060. Chains[ChainI] = L.getValue(1);
  3061. }
  3062. if (!ConstantMemory) {
  3063. SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  3064. makeArrayRef(Chains.data(), ChainI));
  3065. if (isVolatile)
  3066. DAG.setRoot(Chain);
  3067. else
  3068. PendingLoads.push_back(Chain);
  3069. }
  3070. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  3071. DAG.getVTList(ValueVTs), Values));
  3072. }
  3073. void SelectionDAGBuilder::visitStore(const StoreInst &I) {
  3074. if (I.isAtomic())
  3075. return visitAtomicStore(I);
  3076. const Value *SrcV = I.getOperand(0);
  3077. const Value *PtrV = I.getOperand(1);
  3078. SmallVector<EVT, 4> ValueVTs;
  3079. SmallVector<uint64_t, 4> Offsets;
  3080. ComputeValueVTs(DAG.getTargetLoweringInfo(), SrcV->getType(),
  3081. ValueVTs, &Offsets);
  3082. unsigned NumValues = ValueVTs.size();
  3083. if (NumValues == 0)
  3084. return;
  3085. // Get the lowered operands. Note that we do this after
  3086. // checking if NumResults is zero, because with zero results
  3087. // the operands won't have values in the map.
  3088. SDValue Src = getValue(SrcV);
  3089. SDValue Ptr = getValue(PtrV);
  3090. SDValue Root = getRoot();
  3091. SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
  3092. NumValues));
  3093. EVT PtrVT = Ptr.getValueType();
  3094. bool isVolatile = I.isVolatile();
  3095. bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
  3096. unsigned Alignment = I.getAlignment();
  3097. AAMDNodes AAInfo;
  3098. I.getAAMetadata(AAInfo);
  3099. unsigned ChainI = 0;
  3100. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3101. // See visitLoad comments.
  3102. if (ChainI == MaxParallelChains) {
  3103. SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  3104. makeArrayRef(Chains.data(), ChainI));
  3105. Root = Chain;
  3106. ChainI = 0;
  3107. }
  3108. SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(), PtrVT, Ptr,
  3109. DAG.getConstant(Offsets[i], PtrVT));
  3110. SDValue St = DAG.getStore(Root, getCurSDLoc(),
  3111. SDValue(Src.getNode(), Src.getResNo() + i),
  3112. Add, MachinePointerInfo(PtrV, Offsets[i]),
  3113. isVolatile, isNonTemporal, Alignment, AAInfo);
  3114. Chains[ChainI] = St;
  3115. }
  3116. SDValue StoreNode = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  3117. makeArrayRef(Chains.data(), ChainI));
  3118. DAG.setRoot(StoreNode);
  3119. }
  3120. void SelectionDAGBuilder::visitMaskedStore(const CallInst &I) {
  3121. SDLoc sdl = getCurSDLoc();
  3122. Value *PtrOperand = I.getArgOperand(0);
  3123. SDValue Ptr = getValue(PtrOperand);
  3124. SDValue Src0 = getValue(I.getArgOperand(1));
  3125. SDValue Mask = getValue(I.getArgOperand(3));
  3126. EVT VT = Src0.getValueType();
  3127. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
  3128. if (!Alignment)
  3129. Alignment = DAG.getEVTAlignment(VT);
  3130. AAMDNodes AAInfo;
  3131. I.getAAMetadata(AAInfo);
  3132. MachineMemOperand *MMO =
  3133. DAG.getMachineFunction().
  3134. getMachineMemOperand(MachinePointerInfo(PtrOperand),
  3135. MachineMemOperand::MOStore, VT.getStoreSize(),
  3136. Alignment, AAInfo);
  3137. SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, MMO);
  3138. DAG.setRoot(StoreNode);
  3139. setValue(&I, StoreNode);
  3140. }
  3141. void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I) {
  3142. SDLoc sdl = getCurSDLoc();
  3143. Value *PtrOperand = I.getArgOperand(0);
  3144. SDValue Ptr = getValue(PtrOperand);
  3145. SDValue Src0 = getValue(I.getArgOperand(1));
  3146. SDValue Mask = getValue(I.getArgOperand(3));
  3147. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3148. EVT VT = TLI.getValueType(I.getType());
  3149. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
  3150. if (!Alignment)
  3151. Alignment = DAG.getEVTAlignment(VT);
  3152. AAMDNodes AAInfo;
  3153. I.getAAMetadata(AAInfo);
  3154. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3155. SDValue InChain = DAG.getRoot();
  3156. if (AA->pointsToConstantMemory(
  3157. AliasAnalysis::Location(PtrOperand,
  3158. AA->getTypeStoreSize(I.getType()),
  3159. AAInfo))) {
  3160. // Do not serialize (non-volatile) loads of constant memory with anything.
  3161. InChain = DAG.getEntryNode();
  3162. }
  3163. MachineMemOperand *MMO =
  3164. DAG.getMachineFunction().
  3165. getMachineMemOperand(MachinePointerInfo(PtrOperand),
  3166. MachineMemOperand::MOLoad, VT.getStoreSize(),
  3167. Alignment, AAInfo, Ranges);
  3168. SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, MMO);
  3169. SDValue OutChain = Load.getValue(1);
  3170. DAG.setRoot(OutChain);
  3171. setValue(&I, Load);
  3172. }
  3173. void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
  3174. SDLoc dl = getCurSDLoc();
  3175. AtomicOrdering SuccessOrder = I.getSuccessOrdering();
  3176. AtomicOrdering FailureOrder = I.getFailureOrdering();
  3177. SynchronizationScope Scope = I.getSynchScope();
  3178. SDValue InChain = getRoot();
  3179. MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
  3180. SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
  3181. SDValue L = DAG.getAtomicCmpSwap(
  3182. ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
  3183. getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
  3184. getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
  3185. /*Alignment=*/ 0, SuccessOrder, FailureOrder, Scope);
  3186. SDValue OutChain = L.getValue(2);
  3187. setValue(&I, L);
  3188. DAG.setRoot(OutChain);
  3189. }
  3190. void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
  3191. SDLoc dl = getCurSDLoc();
  3192. ISD::NodeType NT;
  3193. switch (I.getOperation()) {
  3194. default: llvm_unreachable("Unknown atomicrmw operation");
  3195. case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
  3196. case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
  3197. case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
  3198. case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
  3199. case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
  3200. case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
  3201. case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
  3202. case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
  3203. case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
  3204. case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
  3205. case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
  3206. }
  3207. AtomicOrdering Order = I.getOrdering();
  3208. SynchronizationScope Scope = I.getSynchScope();
  3209. SDValue InChain = getRoot();
  3210. SDValue L =
  3211. DAG.getAtomic(NT, dl,
  3212. getValue(I.getValOperand()).getSimpleValueType(),
  3213. InChain,
  3214. getValue(I.getPointerOperand()),
  3215. getValue(I.getValOperand()),
  3216. I.getPointerOperand(),
  3217. /* Alignment=*/ 0, Order, Scope);
  3218. SDValue OutChain = L.getValue(1);
  3219. setValue(&I, L);
  3220. DAG.setRoot(OutChain);
  3221. }
  3222. void SelectionDAGBuilder::visitFence(const FenceInst &I) {
  3223. SDLoc dl = getCurSDLoc();
  3224. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3225. SDValue Ops[3];
  3226. Ops[0] = getRoot();
  3227. Ops[1] = DAG.getConstant(I.getOrdering(), TLI.getPointerTy());
  3228. Ops[2] = DAG.getConstant(I.getSynchScope(), TLI.getPointerTy());
  3229. DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
  3230. }
  3231. void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
  3232. SDLoc dl = getCurSDLoc();
  3233. AtomicOrdering Order = I.getOrdering();
  3234. SynchronizationScope Scope = I.getSynchScope();
  3235. SDValue InChain = getRoot();
  3236. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3237. EVT VT = TLI.getValueType(I.getType());
  3238. if (I.getAlignment() < VT.getSizeInBits() / 8)
  3239. report_fatal_error("Cannot generate unaligned atomic load");
  3240. MachineMemOperand *MMO =
  3241. DAG.getMachineFunction().
  3242. getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
  3243. MachineMemOperand::MOVolatile |
  3244. MachineMemOperand::MOLoad,
  3245. VT.getStoreSize(),
  3246. I.getAlignment() ? I.getAlignment() :
  3247. DAG.getEVTAlignment(VT));
  3248. InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
  3249. SDValue L =
  3250. DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
  3251. getValue(I.getPointerOperand()), MMO,
  3252. Order, Scope);
  3253. SDValue OutChain = L.getValue(1);
  3254. setValue(&I, L);
  3255. DAG.setRoot(OutChain);
  3256. }
  3257. void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
  3258. SDLoc dl = getCurSDLoc();
  3259. AtomicOrdering Order = I.getOrdering();
  3260. SynchronizationScope Scope = I.getSynchScope();
  3261. SDValue InChain = getRoot();
  3262. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3263. EVT VT = TLI.getValueType(I.getValueOperand()->getType());
  3264. if (I.getAlignment() < VT.getSizeInBits() / 8)
  3265. report_fatal_error("Cannot generate unaligned atomic store");
  3266. SDValue OutChain =
  3267. DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
  3268. InChain,
  3269. getValue(I.getPointerOperand()),
  3270. getValue(I.getValueOperand()),
  3271. I.getPointerOperand(), I.getAlignment(),
  3272. Order, Scope);
  3273. DAG.setRoot(OutChain);
  3274. }
  3275. /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
  3276. /// node.
  3277. void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
  3278. unsigned Intrinsic) {
  3279. bool HasChain = !I.doesNotAccessMemory();
  3280. bool OnlyLoad = HasChain && I.onlyReadsMemory();
  3281. // Build the operand list.
  3282. SmallVector<SDValue, 8> Ops;
  3283. if (HasChain) { // If this intrinsic has side-effects, chainify it.
  3284. if (OnlyLoad) {
  3285. // We don't need to serialize loads against other loads.
  3286. Ops.push_back(DAG.getRoot());
  3287. } else {
  3288. Ops.push_back(getRoot());
  3289. }
  3290. }
  3291. // Info is set by getTgtMemInstrinsic
  3292. TargetLowering::IntrinsicInfo Info;
  3293. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3294. bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
  3295. // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
  3296. if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
  3297. Info.opc == ISD::INTRINSIC_W_CHAIN)
  3298. Ops.push_back(DAG.getTargetConstant(Intrinsic, TLI.getPointerTy()));
  3299. // Add all operands of the call to the operand list.
  3300. for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
  3301. SDValue Op = getValue(I.getArgOperand(i));
  3302. Ops.push_back(Op);
  3303. }
  3304. SmallVector<EVT, 4> ValueVTs;
  3305. ComputeValueVTs(TLI, I.getType(), ValueVTs);
  3306. if (HasChain)
  3307. ValueVTs.push_back(MVT::Other);
  3308. SDVTList VTs = DAG.getVTList(ValueVTs);
  3309. // Create the node.
  3310. SDValue Result;
  3311. if (IsTgtIntrinsic) {
  3312. // This is target intrinsic that touches memory
  3313. Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(),
  3314. VTs, Ops, Info.memVT,
  3315. MachinePointerInfo(Info.ptrVal, Info.offset),
  3316. Info.align, Info.vol,
  3317. Info.readMem, Info.writeMem, Info.size);
  3318. } else if (!HasChain) {
  3319. Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
  3320. } else if (!I.getType()->isVoidTy()) {
  3321. Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
  3322. } else {
  3323. Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
  3324. }
  3325. if (HasChain) {
  3326. SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
  3327. if (OnlyLoad)
  3328. PendingLoads.push_back(Chain);
  3329. else
  3330. DAG.setRoot(Chain);
  3331. }
  3332. if (!I.getType()->isVoidTy()) {
  3333. if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
  3334. EVT VT = TLI.getValueType(PTy);
  3335. Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
  3336. }
  3337. setValue(&I, Result);
  3338. }
  3339. }
  3340. /// GetSignificand - Get the significand and build it into a floating-point
  3341. /// number with exponent of 1:
  3342. ///
  3343. /// Op = (Op & 0x007fffff) | 0x3f800000;
  3344. ///
  3345. /// where Op is the hexadecimal representation of floating point value.
  3346. static SDValue
  3347. GetSignificand(SelectionDAG &DAG, SDValue Op, SDLoc dl) {
  3348. SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  3349. DAG.getConstant(0x007fffff, MVT::i32));
  3350. SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
  3351. DAG.getConstant(0x3f800000, MVT::i32));
  3352. return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
  3353. }
  3354. /// GetExponent - Get the exponent:
  3355. ///
  3356. /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
  3357. ///
  3358. /// where Op is the hexadecimal representation of floating point value.
  3359. static SDValue
  3360. GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
  3361. SDLoc dl) {
  3362. SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  3363. DAG.getConstant(0x7f800000, MVT::i32));
  3364. SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
  3365. DAG.getConstant(23, TLI.getPointerTy()));
  3366. SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
  3367. DAG.getConstant(127, MVT::i32));
  3368. return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
  3369. }
  3370. /// getF32Constant - Get 32-bit floating point constant.
  3371. static SDValue
  3372. getF32Constant(SelectionDAG &DAG, unsigned Flt) {
  3373. return DAG.getConstantFP(APFloat(APFloat::IEEEsingle, APInt(32, Flt)),
  3374. MVT::f32);
  3375. }
  3376. /// expandExp - Lower an exp intrinsic. Handles the special sequences for
  3377. /// limited-precision mode.
  3378. static SDValue expandExp(SDLoc dl, SDValue Op, SelectionDAG &DAG,
  3379. const TargetLowering &TLI) {
  3380. if (Op.getValueType() == MVT::f32 &&
  3381. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3382. // Put the exponent in the right bit position for later addition to the
  3383. // final result:
  3384. //
  3385. // #define LOG2OFe 1.4426950f
  3386. // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
  3387. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
  3388. getF32Constant(DAG, 0x3fb8aa3b));
  3389. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
  3390. // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
  3391. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  3392. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
  3393. // IntegerPartOfX <<= 23;
  3394. IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  3395. DAG.getConstant(23, TLI.getPointerTy()));
  3396. SDValue TwoToFracPartOfX;
  3397. if (LimitFloatPrecision <= 6) {
  3398. // For floating-point precision of 6:
  3399. //
  3400. // TwoToFractionalPartOfX =
  3401. // 0.997535578f +
  3402. // (0.735607626f + 0.252464424f * x) * x;
  3403. //
  3404. // error 0.0144103317, which is 6 bits
  3405. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3406. getF32Constant(DAG, 0x3e814304));
  3407. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3408. getF32Constant(DAG, 0x3f3c50c8));
  3409. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3410. TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3411. getF32Constant(DAG, 0x3f7f5e7e));
  3412. } else if (LimitFloatPrecision <= 12) {
  3413. // For floating-point precision of 12:
  3414. //
  3415. // TwoToFractionalPartOfX =
  3416. // 0.999892986f +
  3417. // (0.696457318f +
  3418. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  3419. //
  3420. // 0.000107046256 error, which is 13 to 14 bits
  3421. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3422. getF32Constant(DAG, 0x3da235e3));
  3423. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3424. getF32Constant(DAG, 0x3e65b8f3));
  3425. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3426. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3427. getF32Constant(DAG, 0x3f324b07));
  3428. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3429. TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3430. getF32Constant(DAG, 0x3f7ff8fd));
  3431. } else { // LimitFloatPrecision <= 18
  3432. // For floating-point precision of 18:
  3433. //
  3434. // TwoToFractionalPartOfX =
  3435. // 0.999999982f +
  3436. // (0.693148872f +
  3437. // (0.240227044f +
  3438. // (0.554906021e-1f +
  3439. // (0.961591928e-2f +
  3440. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  3441. //
  3442. // error 2.47208000*10^(-7), which is better than 18 bits
  3443. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3444. getF32Constant(DAG, 0x3924b03e));
  3445. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3446. getF32Constant(DAG, 0x3ab24b87));
  3447. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3448. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3449. getF32Constant(DAG, 0x3c1d8c17));
  3450. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3451. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3452. getF32Constant(DAG, 0x3d634a1d));
  3453. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3454. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3455. getF32Constant(DAG, 0x3e75fe14));
  3456. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3457. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  3458. getF32Constant(DAG, 0x3f317234));
  3459. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  3460. TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  3461. getF32Constant(DAG, 0x3f800000));
  3462. }
  3463. // Add the exponent into the result in integer domain.
  3464. SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFracPartOfX);
  3465. return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
  3466. DAG.getNode(ISD::ADD, dl, MVT::i32,
  3467. t13, IntegerPartOfX));
  3468. }
  3469. // No special expansion.
  3470. return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
  3471. }
  3472. /// expandLog - Lower a log intrinsic. Handles the special sequences for
  3473. /// limited-precision mode.
  3474. static SDValue expandLog(SDLoc dl, SDValue Op, SelectionDAG &DAG,
  3475. const TargetLowering &TLI) {
  3476. if (Op.getValueType() == MVT::f32 &&
  3477. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3478. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  3479. // Scale the exponent by log(2) [0.69314718f].
  3480. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  3481. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  3482. getF32Constant(DAG, 0x3f317218));
  3483. // Get the significand and build it into a floating-point number with
  3484. // exponent of 1.
  3485. SDValue X = GetSignificand(DAG, Op1, dl);
  3486. SDValue LogOfMantissa;
  3487. if (LimitFloatPrecision <= 6) {
  3488. // For floating-point precision of 6:
  3489. //
  3490. // LogofMantissa =
  3491. // -1.1609546f +
  3492. // (1.4034025f - 0.23903021f * x) * x;
  3493. //
  3494. // error 0.0034276066, which is better than 8 bits
  3495. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3496. getF32Constant(DAG, 0xbe74c456));
  3497. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3498. getF32Constant(DAG, 0x3fb3a2b1));
  3499. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3500. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3501. getF32Constant(DAG, 0x3f949a29));
  3502. } else if (LimitFloatPrecision <= 12) {
  3503. // For floating-point precision of 12:
  3504. //
  3505. // LogOfMantissa =
  3506. // -1.7417939f +
  3507. // (2.8212026f +
  3508. // (-1.4699568f +
  3509. // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
  3510. //
  3511. // error 0.000061011436, which is 14 bits
  3512. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3513. getF32Constant(DAG, 0xbd67b6d6));
  3514. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3515. getF32Constant(DAG, 0x3ee4f4b8));
  3516. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3517. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3518. getF32Constant(DAG, 0x3fbc278b));
  3519. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3520. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3521. getF32Constant(DAG, 0x40348e95));
  3522. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3523. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3524. getF32Constant(DAG, 0x3fdef31a));
  3525. } else { // LimitFloatPrecision <= 18
  3526. // For floating-point precision of 18:
  3527. //
  3528. // LogOfMantissa =
  3529. // -2.1072184f +
  3530. // (4.2372794f +
  3531. // (-3.7029485f +
  3532. // (2.2781945f +
  3533. // (-0.87823314f +
  3534. // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
  3535. //
  3536. // error 0.0000023660568, which is better than 18 bits
  3537. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3538. getF32Constant(DAG, 0xbc91e5ac));
  3539. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3540. getF32Constant(DAG, 0x3e4350aa));
  3541. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3542. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3543. getF32Constant(DAG, 0x3f60d3e3));
  3544. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3545. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3546. getF32Constant(DAG, 0x4011cdf0));
  3547. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3548. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3549. getF32Constant(DAG, 0x406cfd1c));
  3550. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3551. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3552. getF32Constant(DAG, 0x408797cb));
  3553. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3554. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  3555. getF32Constant(DAG, 0x4006dcab));
  3556. }
  3557. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
  3558. }
  3559. // No special expansion.
  3560. return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
  3561. }
  3562. /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
  3563. /// limited-precision mode.
  3564. static SDValue expandLog2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
  3565. const TargetLowering &TLI) {
  3566. if (Op.getValueType() == MVT::f32 &&
  3567. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3568. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  3569. // Get the exponent.
  3570. SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
  3571. // Get the significand and build it into a floating-point number with
  3572. // exponent of 1.
  3573. SDValue X = GetSignificand(DAG, Op1, dl);
  3574. // Different possible minimax approximations of significand in
  3575. // floating-point for various degrees of accuracy over [1,2].
  3576. SDValue Log2ofMantissa;
  3577. if (LimitFloatPrecision <= 6) {
  3578. // For floating-point precision of 6:
  3579. //
  3580. // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
  3581. //
  3582. // error 0.0049451742, which is more than 7 bits
  3583. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3584. getF32Constant(DAG, 0xbeb08fe0));
  3585. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3586. getF32Constant(DAG, 0x40019463));
  3587. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3588. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3589. getF32Constant(DAG, 0x3fd6633d));
  3590. } else if (LimitFloatPrecision <= 12) {
  3591. // For floating-point precision of 12:
  3592. //
  3593. // Log2ofMantissa =
  3594. // -2.51285454f +
  3595. // (4.07009056f +
  3596. // (-2.12067489f +
  3597. // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
  3598. //
  3599. // error 0.0000876136000, which is better than 13 bits
  3600. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3601. getF32Constant(DAG, 0xbda7262e));
  3602. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3603. getF32Constant(DAG, 0x3f25280b));
  3604. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3605. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3606. getF32Constant(DAG, 0x4007b923));
  3607. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3608. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3609. getF32Constant(DAG, 0x40823e2f));
  3610. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3611. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3612. getF32Constant(DAG, 0x4020d29c));
  3613. } else { // LimitFloatPrecision <= 18
  3614. // For floating-point precision of 18:
  3615. //
  3616. // Log2ofMantissa =
  3617. // -3.0400495f +
  3618. // (6.1129976f +
  3619. // (-5.3420409f +
  3620. // (3.2865683f +
  3621. // (-1.2669343f +
  3622. // (0.27515199f -
  3623. // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
  3624. //
  3625. // error 0.0000018516, which is better than 18 bits
  3626. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3627. getF32Constant(DAG, 0xbcd2769e));
  3628. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3629. getF32Constant(DAG, 0x3e8ce0b9));
  3630. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3631. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3632. getF32Constant(DAG, 0x3fa22ae7));
  3633. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3634. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3635. getF32Constant(DAG, 0x40525723));
  3636. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3637. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3638. getF32Constant(DAG, 0x40aaf200));
  3639. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3640. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3641. getF32Constant(DAG, 0x40c39dad));
  3642. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3643. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  3644. getF32Constant(DAG, 0x4042902c));
  3645. }
  3646. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
  3647. }
  3648. // No special expansion.
  3649. return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
  3650. }
  3651. /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
  3652. /// limited-precision mode.
  3653. static SDValue expandLog10(SDLoc dl, SDValue Op, SelectionDAG &DAG,
  3654. const TargetLowering &TLI) {
  3655. if (Op.getValueType() == MVT::f32 &&
  3656. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3657. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  3658. // Scale the exponent by log10(2) [0.30102999f].
  3659. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  3660. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  3661. getF32Constant(DAG, 0x3e9a209a));
  3662. // Get the significand and build it into a floating-point number with
  3663. // exponent of 1.
  3664. SDValue X = GetSignificand(DAG, Op1, dl);
  3665. SDValue Log10ofMantissa;
  3666. if (LimitFloatPrecision <= 6) {
  3667. // For floating-point precision of 6:
  3668. //
  3669. // Log10ofMantissa =
  3670. // -0.50419619f +
  3671. // (0.60948995f - 0.10380950f * x) * x;
  3672. //
  3673. // error 0.0014886165, which is 6 bits
  3674. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3675. getF32Constant(DAG, 0xbdd49a13));
  3676. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3677. getF32Constant(DAG, 0x3f1c0789));
  3678. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3679. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3680. getF32Constant(DAG, 0x3f011300));
  3681. } else if (LimitFloatPrecision <= 12) {
  3682. // For floating-point precision of 12:
  3683. //
  3684. // Log10ofMantissa =
  3685. // -0.64831180f +
  3686. // (0.91751397f +
  3687. // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
  3688. //
  3689. // error 0.00019228036, which is better than 12 bits
  3690. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3691. getF32Constant(DAG, 0x3d431f31));
  3692. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  3693. getF32Constant(DAG, 0x3ea21fb2));
  3694. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3695. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3696. getF32Constant(DAG, 0x3f6ae232));
  3697. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3698. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  3699. getF32Constant(DAG, 0x3f25f7c3));
  3700. } else { // LimitFloatPrecision <= 18
  3701. // For floating-point precision of 18:
  3702. //
  3703. // Log10ofMantissa =
  3704. // -0.84299375f +
  3705. // (1.5327582f +
  3706. // (-1.0688956f +
  3707. // (0.49102474f +
  3708. // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
  3709. //
  3710. // error 0.0000037995730, which is better than 18 bits
  3711. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3712. getF32Constant(DAG, 0x3c5d51ce));
  3713. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  3714. getF32Constant(DAG, 0x3e00685a));
  3715. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3716. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3717. getF32Constant(DAG, 0x3efb6798));
  3718. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3719. SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  3720. getF32Constant(DAG, 0x3f88d192));
  3721. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3722. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3723. getF32Constant(DAG, 0x3fc4316c));
  3724. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3725. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
  3726. getF32Constant(DAG, 0x3f57ce70));
  3727. }
  3728. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
  3729. }
  3730. // No special expansion.
  3731. return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
  3732. }
  3733. /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
  3734. /// limited-precision mode.
  3735. static SDValue expandExp2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
  3736. const TargetLowering &TLI) {
  3737. if (Op.getValueType() == MVT::f32 &&
  3738. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3739. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
  3740. // FractionalPartOfX = x - (float)IntegerPartOfX;
  3741. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  3742. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
  3743. // IntegerPartOfX <<= 23;
  3744. IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  3745. DAG.getConstant(23, TLI.getPointerTy()));
  3746. SDValue TwoToFractionalPartOfX;
  3747. if (LimitFloatPrecision <= 6) {
  3748. // For floating-point precision of 6:
  3749. //
  3750. // TwoToFractionalPartOfX =
  3751. // 0.997535578f +
  3752. // (0.735607626f + 0.252464424f * x) * x;
  3753. //
  3754. // error 0.0144103317, which is 6 bits
  3755. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3756. getF32Constant(DAG, 0x3e814304));
  3757. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3758. getF32Constant(DAG, 0x3f3c50c8));
  3759. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3760. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3761. getF32Constant(DAG, 0x3f7f5e7e));
  3762. } else if (LimitFloatPrecision <= 12) {
  3763. // For floating-point precision of 12:
  3764. //
  3765. // TwoToFractionalPartOfX =
  3766. // 0.999892986f +
  3767. // (0.696457318f +
  3768. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  3769. //
  3770. // error 0.000107046256, which is 13 to 14 bits
  3771. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3772. getF32Constant(DAG, 0x3da235e3));
  3773. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3774. getF32Constant(DAG, 0x3e65b8f3));
  3775. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3776. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3777. getF32Constant(DAG, 0x3f324b07));
  3778. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3779. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3780. getF32Constant(DAG, 0x3f7ff8fd));
  3781. } else { // LimitFloatPrecision <= 18
  3782. // For floating-point precision of 18:
  3783. //
  3784. // TwoToFractionalPartOfX =
  3785. // 0.999999982f +
  3786. // (0.693148872f +
  3787. // (0.240227044f +
  3788. // (0.554906021e-1f +
  3789. // (0.961591928e-2f +
  3790. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  3791. // error 2.47208000*10^(-7), which is better than 18 bits
  3792. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3793. getF32Constant(DAG, 0x3924b03e));
  3794. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3795. getF32Constant(DAG, 0x3ab24b87));
  3796. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3797. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3798. getF32Constant(DAG, 0x3c1d8c17));
  3799. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3800. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3801. getF32Constant(DAG, 0x3d634a1d));
  3802. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3803. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3804. getF32Constant(DAG, 0x3e75fe14));
  3805. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3806. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  3807. getF32Constant(DAG, 0x3f317234));
  3808. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  3809. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  3810. getF32Constant(DAG, 0x3f800000));
  3811. }
  3812. // Add the exponent into the result in integer domain.
  3813. SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32,
  3814. TwoToFractionalPartOfX);
  3815. return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
  3816. DAG.getNode(ISD::ADD, dl, MVT::i32,
  3817. t13, IntegerPartOfX));
  3818. }
  3819. // No special expansion.
  3820. return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
  3821. }
  3822. /// visitPow - Lower a pow intrinsic. Handles the special sequences for
  3823. /// limited-precision mode with x == 10.0f.
  3824. static SDValue expandPow(SDLoc dl, SDValue LHS, SDValue RHS,
  3825. SelectionDAG &DAG, const TargetLowering &TLI) {
  3826. bool IsExp10 = false;
  3827. if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
  3828. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3829. if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
  3830. APFloat Ten(10.0f);
  3831. IsExp10 = LHSC->isExactlyValue(Ten);
  3832. }
  3833. }
  3834. if (IsExp10) {
  3835. // Put the exponent in the right bit position for later addition to the
  3836. // final result:
  3837. //
  3838. // #define LOG2OF10 3.3219281f
  3839. // IntegerPartOfX = (int32_t)(x * LOG2OF10);
  3840. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
  3841. getF32Constant(DAG, 0x40549a78));
  3842. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
  3843. // FractionalPartOfX = x - (float)IntegerPartOfX;
  3844. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  3845. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
  3846. // IntegerPartOfX <<= 23;
  3847. IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  3848. DAG.getConstant(23, TLI.getPointerTy()));
  3849. SDValue TwoToFractionalPartOfX;
  3850. if (LimitFloatPrecision <= 6) {
  3851. // For floating-point precision of 6:
  3852. //
  3853. // twoToFractionalPartOfX =
  3854. // 0.997535578f +
  3855. // (0.735607626f + 0.252464424f * x) * x;
  3856. //
  3857. // error 0.0144103317, which is 6 bits
  3858. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3859. getF32Constant(DAG, 0x3e814304));
  3860. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3861. getF32Constant(DAG, 0x3f3c50c8));
  3862. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3863. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3864. getF32Constant(DAG, 0x3f7f5e7e));
  3865. } else if (LimitFloatPrecision <= 12) {
  3866. // For floating-point precision of 12:
  3867. //
  3868. // TwoToFractionalPartOfX =
  3869. // 0.999892986f +
  3870. // (0.696457318f +
  3871. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  3872. //
  3873. // error 0.000107046256, which is 13 to 14 bits
  3874. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3875. getF32Constant(DAG, 0x3da235e3));
  3876. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3877. getF32Constant(DAG, 0x3e65b8f3));
  3878. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3879. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3880. getF32Constant(DAG, 0x3f324b07));
  3881. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3882. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3883. getF32Constant(DAG, 0x3f7ff8fd));
  3884. } else { // LimitFloatPrecision <= 18
  3885. // For floating-point precision of 18:
  3886. //
  3887. // TwoToFractionalPartOfX =
  3888. // 0.999999982f +
  3889. // (0.693148872f +
  3890. // (0.240227044f +
  3891. // (0.554906021e-1f +
  3892. // (0.961591928e-2f +
  3893. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  3894. // error 2.47208000*10^(-7), which is better than 18 bits
  3895. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3896. getF32Constant(DAG, 0x3924b03e));
  3897. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3898. getF32Constant(DAG, 0x3ab24b87));
  3899. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3900. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3901. getF32Constant(DAG, 0x3c1d8c17));
  3902. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3903. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3904. getF32Constant(DAG, 0x3d634a1d));
  3905. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3906. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3907. getF32Constant(DAG, 0x3e75fe14));
  3908. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3909. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  3910. getF32Constant(DAG, 0x3f317234));
  3911. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  3912. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  3913. getF32Constant(DAG, 0x3f800000));
  3914. }
  3915. SDValue t13 = DAG.getNode(ISD::BITCAST, dl,MVT::i32,TwoToFractionalPartOfX);
  3916. return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
  3917. DAG.getNode(ISD::ADD, dl, MVT::i32,
  3918. t13, IntegerPartOfX));
  3919. }
  3920. // No special expansion.
  3921. return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
  3922. }
  3923. /// ExpandPowI - Expand a llvm.powi intrinsic.
  3924. static SDValue ExpandPowI(SDLoc DL, SDValue LHS, SDValue RHS,
  3925. SelectionDAG &DAG) {
  3926. // If RHS is a constant, we can expand this out to a multiplication tree,
  3927. // otherwise we end up lowering to a call to __powidf2 (for example). When
  3928. // optimizing for size, we only want to do this if the expansion would produce
  3929. // a small number of multiplies, otherwise we do the full expansion.
  3930. if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
  3931. // Get the exponent as a positive value.
  3932. unsigned Val = RHSC->getSExtValue();
  3933. if ((int)Val < 0) Val = -Val;
  3934. // powi(x, 0) -> 1.0
  3935. if (Val == 0)
  3936. return DAG.getConstantFP(1.0, LHS.getValueType());
  3937. const Function *F = DAG.getMachineFunction().getFunction();
  3938. if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
  3939. Attribute::OptimizeForSize) ||
  3940. // If optimizing for size, don't insert too many multiplies. This
  3941. // inserts up to 5 multiplies.
  3942. CountPopulation_32(Val)+Log2_32(Val) < 7) {
  3943. // We use the simple binary decomposition method to generate the multiply
  3944. // sequence. There are more optimal ways to do this (for example,
  3945. // powi(x,15) generates one more multiply than it should), but this has
  3946. // the benefit of being both really simple and much better than a libcall.
  3947. SDValue Res; // Logically starts equal to 1.0
  3948. SDValue CurSquare = LHS;
  3949. while (Val) {
  3950. if (Val & 1) {
  3951. if (Res.getNode())
  3952. Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
  3953. else
  3954. Res = CurSquare; // 1.0*CurSquare.
  3955. }
  3956. CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
  3957. CurSquare, CurSquare);
  3958. Val >>= 1;
  3959. }
  3960. // If the original was negative, invert the result, producing 1/(x*x*x).
  3961. if (RHSC->getSExtValue() < 0)
  3962. Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
  3963. DAG.getConstantFP(1.0, LHS.getValueType()), Res);
  3964. return Res;
  3965. }
  3966. }
  3967. // Otherwise, expand to a libcall.
  3968. return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
  3969. }
  3970. // getTruncatedArgReg - Find underlying register used for an truncated
  3971. // argument.
  3972. static unsigned getTruncatedArgReg(const SDValue &N) {
  3973. if (N.getOpcode() != ISD::TRUNCATE)
  3974. return 0;
  3975. const SDValue &Ext = N.getOperand(0);
  3976. if (Ext.getOpcode() == ISD::AssertZext ||
  3977. Ext.getOpcode() == ISD::AssertSext) {
  3978. const SDValue &CFR = Ext.getOperand(0);
  3979. if (CFR.getOpcode() == ISD::CopyFromReg)
  3980. return cast<RegisterSDNode>(CFR.getOperand(1))->getReg();
  3981. if (CFR.getOpcode() == ISD::TRUNCATE)
  3982. return getTruncatedArgReg(CFR);
  3983. }
  3984. return 0;
  3985. }
  3986. /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
  3987. /// argument, create the corresponding DBG_VALUE machine instruction for it now.
  3988. /// At the end of instruction selection, they will be inserted to the entry BB.
  3989. bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(const Value *V,
  3990. MDNode *Variable,
  3991. MDNode *Expr, int64_t Offset,
  3992. bool IsIndirect,
  3993. const SDValue &N) {
  3994. const Argument *Arg = dyn_cast<Argument>(V);
  3995. if (!Arg)
  3996. return false;
  3997. MachineFunction &MF = DAG.getMachineFunction();
  3998. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  3999. // Ignore inlined function arguments here.
  4000. DIVariable DV(Variable);
  4001. if (DV.isInlinedFnArgument(MF.getFunction()))
  4002. return false;
  4003. Optional<MachineOperand> Op;
  4004. // Some arguments' frame index is recorded during argument lowering.
  4005. if (int FI = FuncInfo.getArgumentFrameIndex(Arg))
  4006. Op = MachineOperand::CreateFI(FI);
  4007. if (!Op && N.getNode()) {
  4008. unsigned Reg;
  4009. if (N.getOpcode() == ISD::CopyFromReg)
  4010. Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
  4011. else
  4012. Reg = getTruncatedArgReg(N);
  4013. if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
  4014. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  4015. unsigned PR = RegInfo.getLiveInPhysReg(Reg);
  4016. if (PR)
  4017. Reg = PR;
  4018. }
  4019. if (Reg)
  4020. Op = MachineOperand::CreateReg(Reg, false);
  4021. }
  4022. if (!Op) {
  4023. // Check if ValueMap has reg number.
  4024. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  4025. if (VMI != FuncInfo.ValueMap.end())
  4026. Op = MachineOperand::CreateReg(VMI->second, false);
  4027. }
  4028. if (!Op && N.getNode())
  4029. // Check if frame index is available.
  4030. if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
  4031. if (FrameIndexSDNode *FINode =
  4032. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  4033. Op = MachineOperand::CreateFI(FINode->getIndex());
  4034. if (!Op)
  4035. return false;
  4036. if (Op->isReg())
  4037. FuncInfo.ArgDbgValues.push_back(
  4038. BuildMI(MF, getCurDebugLoc(), TII->get(TargetOpcode::DBG_VALUE),
  4039. IsIndirect, Op->getReg(), Offset, Variable, Expr));
  4040. else
  4041. FuncInfo.ArgDbgValues.push_back(
  4042. BuildMI(MF, getCurDebugLoc(), TII->get(TargetOpcode::DBG_VALUE))
  4043. .addOperand(*Op)
  4044. .addImm(Offset)
  4045. .addMetadata(Variable)
  4046. .addMetadata(Expr));
  4047. return true;
  4048. }
  4049. // VisualStudio defines setjmp as _setjmp
  4050. #if defined(_MSC_VER) && defined(setjmp) && \
  4051. !defined(setjmp_undefined_for_msvc)
  4052. # pragma push_macro("setjmp")
  4053. # undef setjmp
  4054. # define setjmp_undefined_for_msvc
  4055. #endif
  4056. /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
  4057. /// we want to emit this as a call to a named external function, return the name
  4058. /// otherwise lower it and return null.
  4059. const char *
  4060. SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
  4061. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4062. SDLoc sdl = getCurSDLoc();
  4063. DebugLoc dl = getCurDebugLoc();
  4064. SDValue Res;
  4065. switch (Intrinsic) {
  4066. default:
  4067. // By default, turn this into a target intrinsic node.
  4068. visitTargetIntrinsic(I, Intrinsic);
  4069. return nullptr;
  4070. case Intrinsic::vastart: visitVAStart(I); return nullptr;
  4071. case Intrinsic::vaend: visitVAEnd(I); return nullptr;
  4072. case Intrinsic::vacopy: visitVACopy(I); return nullptr;
  4073. case Intrinsic::returnaddress:
  4074. setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, TLI.getPointerTy(),
  4075. getValue(I.getArgOperand(0))));
  4076. return nullptr;
  4077. case Intrinsic::frameaddress:
  4078. setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, TLI.getPointerTy(),
  4079. getValue(I.getArgOperand(0))));
  4080. return nullptr;
  4081. case Intrinsic::read_register: {
  4082. Value *Reg = I.getArgOperand(0);
  4083. SDValue RegName =
  4084. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  4085. EVT VT = TLI.getValueType(I.getType());
  4086. setValue(&I, DAG.getNode(ISD::READ_REGISTER, sdl, VT, RegName));
  4087. return nullptr;
  4088. }
  4089. case Intrinsic::write_register: {
  4090. Value *Reg = I.getArgOperand(0);
  4091. Value *RegValue = I.getArgOperand(1);
  4092. SDValue Chain = getValue(RegValue).getOperand(0);
  4093. SDValue RegName =
  4094. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  4095. DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
  4096. RegName, getValue(RegValue)));
  4097. return nullptr;
  4098. }
  4099. case Intrinsic::setjmp:
  4100. return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
  4101. case Intrinsic::longjmp:
  4102. return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
  4103. case Intrinsic::memcpy: {
  4104. // Assert for address < 256 since we support only user defined address
  4105. // spaces.
  4106. assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
  4107. < 256 &&
  4108. cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
  4109. < 256 &&
  4110. "Unknown address space");
  4111. SDValue Op1 = getValue(I.getArgOperand(0));
  4112. SDValue Op2 = getValue(I.getArgOperand(1));
  4113. SDValue Op3 = getValue(I.getArgOperand(2));
  4114. unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
  4115. if (!Align)
  4116. Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment.
  4117. bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
  4118. DAG.setRoot(DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, false,
  4119. MachinePointerInfo(I.getArgOperand(0)),
  4120. MachinePointerInfo(I.getArgOperand(1))));
  4121. return nullptr;
  4122. }
  4123. case Intrinsic::memset: {
  4124. // Assert for address < 256 since we support only user defined address
  4125. // spaces.
  4126. assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
  4127. < 256 &&
  4128. "Unknown address space");
  4129. SDValue Op1 = getValue(I.getArgOperand(0));
  4130. SDValue Op2 = getValue(I.getArgOperand(1));
  4131. SDValue Op3 = getValue(I.getArgOperand(2));
  4132. unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
  4133. if (!Align)
  4134. Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment.
  4135. bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
  4136. DAG.setRoot(DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4137. MachinePointerInfo(I.getArgOperand(0))));
  4138. return nullptr;
  4139. }
  4140. case Intrinsic::memmove: {
  4141. // Assert for address < 256 since we support only user defined address
  4142. // spaces.
  4143. assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
  4144. < 256 &&
  4145. cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
  4146. < 256 &&
  4147. "Unknown address space");
  4148. SDValue Op1 = getValue(I.getArgOperand(0));
  4149. SDValue Op2 = getValue(I.getArgOperand(1));
  4150. SDValue Op3 = getValue(I.getArgOperand(2));
  4151. unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
  4152. if (!Align)
  4153. Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment.
  4154. bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
  4155. DAG.setRoot(DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4156. MachinePointerInfo(I.getArgOperand(0)),
  4157. MachinePointerInfo(I.getArgOperand(1))));
  4158. return nullptr;
  4159. }
  4160. case Intrinsic::dbg_declare: {
  4161. const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
  4162. MDNode *Variable = DI.getVariable();
  4163. MDNode *Expression = DI.getExpression();
  4164. const Value *Address = DI.getAddress();
  4165. DIVariable DIVar(Variable);
  4166. assert((!DIVar || DIVar.isVariable()) &&
  4167. "Variable in DbgDeclareInst should be either null or a DIVariable.");
  4168. if (!Address || !DIVar) {
  4169. DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  4170. return nullptr;
  4171. }
  4172. // Check if address has undef value.
  4173. if (isa<UndefValue>(Address) ||
  4174. (Address->use_empty() && !isa<Argument>(Address))) {
  4175. DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  4176. return nullptr;
  4177. }
  4178. SDValue &N = NodeMap[Address];
  4179. if (!N.getNode() && isa<Argument>(Address))
  4180. // Check unused arguments map.
  4181. N = UnusedArgNodeMap[Address];
  4182. SDDbgValue *SDV;
  4183. if (N.getNode()) {
  4184. if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
  4185. Address = BCI->getOperand(0);
  4186. // Parameters are handled specially.
  4187. bool isParameter =
  4188. (DIVariable(Variable).getTag() == dwarf::DW_TAG_arg_variable ||
  4189. isa<Argument>(Address));
  4190. const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
  4191. if (isParameter && !AI) {
  4192. FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
  4193. if (FINode)
  4194. // Byval parameter. We have a frame index at this point.
  4195. SDV = DAG.getFrameIndexDbgValue(
  4196. Variable, Expression, FINode->getIndex(), 0, dl, SDNodeOrder);
  4197. else {
  4198. // Address is an argument, so try to emit its dbg value using
  4199. // virtual register info from the FuncInfo.ValueMap.
  4200. EmitFuncArgumentDbgValue(Address, Variable, Expression, 0, false, N);
  4201. return nullptr;
  4202. }
  4203. } else if (AI)
  4204. SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
  4205. true, 0, dl, SDNodeOrder);
  4206. else {
  4207. // Can't do anything with other non-AI cases yet.
  4208. DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  4209. DEBUG(dbgs() << "non-AllocaInst issue for Address: \n\t");
  4210. DEBUG(Address->dump());
  4211. return nullptr;
  4212. }
  4213. DAG.AddDbgValue(SDV, N.getNode(), isParameter);
  4214. } else {
  4215. // If Address is an argument then try to emit its dbg value using
  4216. // virtual register info from the FuncInfo.ValueMap.
  4217. if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, 0, false,
  4218. N)) {
  4219. // If variable is pinned by a alloca in dominating bb then
  4220. // use StaticAllocaMap.
  4221. if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
  4222. if (AI->getParent() != DI.getParent()) {
  4223. DenseMap<const AllocaInst*, int>::iterator SI =
  4224. FuncInfo.StaticAllocaMap.find(AI);
  4225. if (SI != FuncInfo.StaticAllocaMap.end()) {
  4226. SDV = DAG.getFrameIndexDbgValue(Variable, Expression, SI->second,
  4227. 0, dl, SDNodeOrder);
  4228. DAG.AddDbgValue(SDV, nullptr, false);
  4229. return nullptr;
  4230. }
  4231. }
  4232. }
  4233. DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  4234. }
  4235. }
  4236. return nullptr;
  4237. }
  4238. case Intrinsic::dbg_value: {
  4239. const DbgValueInst &DI = cast<DbgValueInst>(I);
  4240. DIVariable DIVar(DI.getVariable());
  4241. assert((!DIVar || DIVar.isVariable()) &&
  4242. "Variable in DbgValueInst should be either null or a DIVariable.");
  4243. if (!DIVar)
  4244. return nullptr;
  4245. MDNode *Variable = DI.getVariable();
  4246. MDNode *Expression = DI.getExpression();
  4247. uint64_t Offset = DI.getOffset();
  4248. const Value *V = DI.getValue();
  4249. if (!V)
  4250. return nullptr;
  4251. SDDbgValue *SDV;
  4252. if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
  4253. SDV = DAG.getConstantDbgValue(Variable, Expression, V, Offset, dl,
  4254. SDNodeOrder);
  4255. DAG.AddDbgValue(SDV, nullptr, false);
  4256. } else {
  4257. // Do not use getValue() in here; we don't want to generate code at
  4258. // this point if it hasn't been done yet.
  4259. SDValue N = NodeMap[V];
  4260. if (!N.getNode() && isa<Argument>(V))
  4261. // Check unused arguments map.
  4262. N = UnusedArgNodeMap[V];
  4263. if (N.getNode()) {
  4264. // A dbg.value for an alloca is always indirect.
  4265. bool IsIndirect = isa<AllocaInst>(V) || Offset != 0;
  4266. if (!EmitFuncArgumentDbgValue(V, Variable, Expression, Offset,
  4267. IsIndirect, N)) {
  4268. SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
  4269. IsIndirect, Offset, dl, SDNodeOrder);
  4270. DAG.AddDbgValue(SDV, N.getNode(), false);
  4271. }
  4272. } else if (!V->use_empty() ) {
  4273. // Do not call getValue(V) yet, as we don't want to generate code.
  4274. // Remember it for later.
  4275. DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
  4276. DanglingDebugInfoMap[V] = DDI;
  4277. } else {
  4278. // We may expand this to cover more cases. One case where we have no
  4279. // data available is an unreferenced parameter.
  4280. DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  4281. }
  4282. }
  4283. // Build a debug info table entry.
  4284. if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
  4285. V = BCI->getOperand(0);
  4286. const AllocaInst *AI = dyn_cast<AllocaInst>(V);
  4287. // Don't handle byval struct arguments or VLAs, for example.
  4288. if (!AI) {
  4289. DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n");
  4290. DEBUG(dbgs() << " Last seen at:\n " << *V << "\n");
  4291. return nullptr;
  4292. }
  4293. DenseMap<const AllocaInst*, int>::iterator SI =
  4294. FuncInfo.StaticAllocaMap.find(AI);
  4295. if (SI == FuncInfo.StaticAllocaMap.end())
  4296. return nullptr; // VLAs.
  4297. return nullptr;
  4298. }
  4299. case Intrinsic::eh_typeid_for: {
  4300. // Find the type id for the given typeinfo.
  4301. GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
  4302. unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
  4303. Res = DAG.getConstant(TypeID, MVT::i32);
  4304. setValue(&I, Res);
  4305. return nullptr;
  4306. }
  4307. case Intrinsic::eh_return_i32:
  4308. case Intrinsic::eh_return_i64:
  4309. DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
  4310. DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
  4311. MVT::Other,
  4312. getControlRoot(),
  4313. getValue(I.getArgOperand(0)),
  4314. getValue(I.getArgOperand(1))));
  4315. return nullptr;
  4316. case Intrinsic::eh_unwind_init:
  4317. DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
  4318. return nullptr;
  4319. case Intrinsic::eh_dwarf_cfa: {
  4320. SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), sdl,
  4321. TLI.getPointerTy());
  4322. SDValue Offset = DAG.getNode(ISD::ADD, sdl,
  4323. CfaArg.getValueType(),
  4324. DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, sdl,
  4325. CfaArg.getValueType()),
  4326. CfaArg);
  4327. SDValue FA = DAG.getNode(ISD::FRAMEADDR, sdl, TLI.getPointerTy(),
  4328. DAG.getConstant(0, TLI.getPointerTy()));
  4329. setValue(&I, DAG.getNode(ISD::ADD, sdl, FA.getValueType(),
  4330. FA, Offset));
  4331. return nullptr;
  4332. }
  4333. case Intrinsic::eh_sjlj_callsite: {
  4334. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  4335. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
  4336. assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
  4337. assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
  4338. MMI.setCurrentCallSite(CI->getZExtValue());
  4339. return nullptr;
  4340. }
  4341. case Intrinsic::eh_sjlj_functioncontext: {
  4342. // Get and store the index of the function context.
  4343. MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
  4344. AllocaInst *FnCtx =
  4345. cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
  4346. int FI = FuncInfo.StaticAllocaMap[FnCtx];
  4347. MFI->setFunctionContextIndex(FI);
  4348. return nullptr;
  4349. }
  4350. case Intrinsic::eh_sjlj_setjmp: {
  4351. SDValue Ops[2];
  4352. Ops[0] = getRoot();
  4353. Ops[1] = getValue(I.getArgOperand(0));
  4354. SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
  4355. DAG.getVTList(MVT::i32, MVT::Other), Ops);
  4356. setValue(&I, Op.getValue(0));
  4357. DAG.setRoot(Op.getValue(1));
  4358. return nullptr;
  4359. }
  4360. case Intrinsic::eh_sjlj_longjmp: {
  4361. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
  4362. getRoot(), getValue(I.getArgOperand(0))));
  4363. return nullptr;
  4364. }
  4365. case Intrinsic::masked_load:
  4366. visitMaskedLoad(I);
  4367. return nullptr;
  4368. case Intrinsic::masked_store:
  4369. visitMaskedStore(I);
  4370. return nullptr;
  4371. case Intrinsic::x86_mmx_pslli_w:
  4372. case Intrinsic::x86_mmx_pslli_d:
  4373. case Intrinsic::x86_mmx_pslli_q:
  4374. case Intrinsic::x86_mmx_psrli_w:
  4375. case Intrinsic::x86_mmx_psrli_d:
  4376. case Intrinsic::x86_mmx_psrli_q:
  4377. case Intrinsic::x86_mmx_psrai_w:
  4378. case Intrinsic::x86_mmx_psrai_d: {
  4379. SDValue ShAmt = getValue(I.getArgOperand(1));
  4380. if (isa<ConstantSDNode>(ShAmt)) {
  4381. visitTargetIntrinsic(I, Intrinsic);
  4382. return nullptr;
  4383. }
  4384. unsigned NewIntrinsic = 0;
  4385. EVT ShAmtVT = MVT::v2i32;
  4386. switch (Intrinsic) {
  4387. case Intrinsic::x86_mmx_pslli_w:
  4388. NewIntrinsic = Intrinsic::x86_mmx_psll_w;
  4389. break;
  4390. case Intrinsic::x86_mmx_pslli_d:
  4391. NewIntrinsic = Intrinsic::x86_mmx_psll_d;
  4392. break;
  4393. case Intrinsic::x86_mmx_pslli_q:
  4394. NewIntrinsic = Intrinsic::x86_mmx_psll_q;
  4395. break;
  4396. case Intrinsic::x86_mmx_psrli_w:
  4397. NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
  4398. break;
  4399. case Intrinsic::x86_mmx_psrli_d:
  4400. NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
  4401. break;
  4402. case Intrinsic::x86_mmx_psrli_q:
  4403. NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
  4404. break;
  4405. case Intrinsic::x86_mmx_psrai_w:
  4406. NewIntrinsic = Intrinsic::x86_mmx_psra_w;
  4407. break;
  4408. case Intrinsic::x86_mmx_psrai_d:
  4409. NewIntrinsic = Intrinsic::x86_mmx_psra_d;
  4410. break;
  4411. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  4412. }
  4413. // The vector shift intrinsics with scalars uses 32b shift amounts but
  4414. // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
  4415. // to be zero.
  4416. // We must do this early because v2i32 is not a legal type.
  4417. SDValue ShOps[2];
  4418. ShOps[0] = ShAmt;
  4419. ShOps[1] = DAG.getConstant(0, MVT::i32);
  4420. ShAmt = DAG.getNode(ISD::BUILD_VECTOR, sdl, ShAmtVT, ShOps);
  4421. EVT DestVT = TLI.getValueType(I.getType());
  4422. ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
  4423. Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
  4424. DAG.getConstant(NewIntrinsic, MVT::i32),
  4425. getValue(I.getArgOperand(0)), ShAmt);
  4426. setValue(&I, Res);
  4427. return nullptr;
  4428. }
  4429. case Intrinsic::x86_avx_vinsertf128_pd_256:
  4430. case Intrinsic::x86_avx_vinsertf128_ps_256:
  4431. case Intrinsic::x86_avx_vinsertf128_si_256:
  4432. case Intrinsic::x86_avx2_vinserti128: {
  4433. EVT DestVT = TLI.getValueType(I.getType());
  4434. EVT ElVT = TLI.getValueType(I.getArgOperand(1)->getType());
  4435. uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(2))->getZExtValue() & 1) *
  4436. ElVT.getVectorNumElements();
  4437. Res =
  4438. DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, DestVT,
  4439. getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
  4440. DAG.getConstant(Idx, TLI.getVectorIdxTy()));
  4441. setValue(&I, Res);
  4442. return nullptr;
  4443. }
  4444. case Intrinsic::x86_avx_vextractf128_pd_256:
  4445. case Intrinsic::x86_avx_vextractf128_ps_256:
  4446. case Intrinsic::x86_avx_vextractf128_si_256:
  4447. case Intrinsic::x86_avx2_vextracti128: {
  4448. EVT DestVT = TLI.getValueType(I.getType());
  4449. uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(1))->getZExtValue() & 1) *
  4450. DestVT.getVectorNumElements();
  4451. Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, DestVT,
  4452. getValue(I.getArgOperand(0)),
  4453. DAG.getConstant(Idx, TLI.getVectorIdxTy()));
  4454. setValue(&I, Res);
  4455. return nullptr;
  4456. }
  4457. case Intrinsic::convertff:
  4458. case Intrinsic::convertfsi:
  4459. case Intrinsic::convertfui:
  4460. case Intrinsic::convertsif:
  4461. case Intrinsic::convertuif:
  4462. case Intrinsic::convertss:
  4463. case Intrinsic::convertsu:
  4464. case Intrinsic::convertus:
  4465. case Intrinsic::convertuu: {
  4466. ISD::CvtCode Code = ISD::CVT_INVALID;
  4467. switch (Intrinsic) {
  4468. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  4469. case Intrinsic::convertff: Code = ISD::CVT_FF; break;
  4470. case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
  4471. case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
  4472. case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
  4473. case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
  4474. case Intrinsic::convertss: Code = ISD::CVT_SS; break;
  4475. case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
  4476. case Intrinsic::convertus: Code = ISD::CVT_US; break;
  4477. case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
  4478. }
  4479. EVT DestVT = TLI.getValueType(I.getType());
  4480. const Value *Op1 = I.getArgOperand(0);
  4481. Res = DAG.getConvertRndSat(DestVT, sdl, getValue(Op1),
  4482. DAG.getValueType(DestVT),
  4483. DAG.getValueType(getValue(Op1).getValueType()),
  4484. getValue(I.getArgOperand(1)),
  4485. getValue(I.getArgOperand(2)),
  4486. Code);
  4487. setValue(&I, Res);
  4488. return nullptr;
  4489. }
  4490. case Intrinsic::powi:
  4491. setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
  4492. getValue(I.getArgOperand(1)), DAG));
  4493. return nullptr;
  4494. case Intrinsic::log:
  4495. setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  4496. return nullptr;
  4497. case Intrinsic::log2:
  4498. setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  4499. return nullptr;
  4500. case Intrinsic::log10:
  4501. setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  4502. return nullptr;
  4503. case Intrinsic::exp:
  4504. setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  4505. return nullptr;
  4506. case Intrinsic::exp2:
  4507. setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  4508. return nullptr;
  4509. case Intrinsic::pow:
  4510. setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
  4511. getValue(I.getArgOperand(1)), DAG, TLI));
  4512. return nullptr;
  4513. case Intrinsic::sqrt:
  4514. case Intrinsic::fabs:
  4515. case Intrinsic::sin:
  4516. case Intrinsic::cos:
  4517. case Intrinsic::floor:
  4518. case Intrinsic::ceil:
  4519. case Intrinsic::trunc:
  4520. case Intrinsic::rint:
  4521. case Intrinsic::nearbyint:
  4522. case Intrinsic::round: {
  4523. unsigned Opcode;
  4524. switch (Intrinsic) {
  4525. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  4526. case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
  4527. case Intrinsic::fabs: Opcode = ISD::FABS; break;
  4528. case Intrinsic::sin: Opcode = ISD::FSIN; break;
  4529. case Intrinsic::cos: Opcode = ISD::FCOS; break;
  4530. case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
  4531. case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
  4532. case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
  4533. case Intrinsic::rint: Opcode = ISD::FRINT; break;
  4534. case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
  4535. case Intrinsic::round: Opcode = ISD::FROUND; break;
  4536. }
  4537. setValue(&I, DAG.getNode(Opcode, sdl,
  4538. getValue(I.getArgOperand(0)).getValueType(),
  4539. getValue(I.getArgOperand(0))));
  4540. return nullptr;
  4541. }
  4542. case Intrinsic::minnum:
  4543. setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
  4544. getValue(I.getArgOperand(0)).getValueType(),
  4545. getValue(I.getArgOperand(0)),
  4546. getValue(I.getArgOperand(1))));
  4547. return nullptr;
  4548. case Intrinsic::maxnum:
  4549. setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
  4550. getValue(I.getArgOperand(0)).getValueType(),
  4551. getValue(I.getArgOperand(0)),
  4552. getValue(I.getArgOperand(1))));
  4553. return nullptr;
  4554. case Intrinsic::copysign:
  4555. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
  4556. getValue(I.getArgOperand(0)).getValueType(),
  4557. getValue(I.getArgOperand(0)),
  4558. getValue(I.getArgOperand(1))));
  4559. return nullptr;
  4560. case Intrinsic::fma:
  4561. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  4562. getValue(I.getArgOperand(0)).getValueType(),
  4563. getValue(I.getArgOperand(0)),
  4564. getValue(I.getArgOperand(1)),
  4565. getValue(I.getArgOperand(2))));
  4566. return nullptr;
  4567. case Intrinsic::fmuladd: {
  4568. EVT VT = TLI.getValueType(I.getType());
  4569. if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
  4570. TLI.isFMAFasterThanFMulAndFAdd(VT)) {
  4571. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  4572. getValue(I.getArgOperand(0)).getValueType(),
  4573. getValue(I.getArgOperand(0)),
  4574. getValue(I.getArgOperand(1)),
  4575. getValue(I.getArgOperand(2))));
  4576. } else {
  4577. SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
  4578. getValue(I.getArgOperand(0)).getValueType(),
  4579. getValue(I.getArgOperand(0)),
  4580. getValue(I.getArgOperand(1)));
  4581. SDValue Add = DAG.getNode(ISD::FADD, sdl,
  4582. getValue(I.getArgOperand(0)).getValueType(),
  4583. Mul,
  4584. getValue(I.getArgOperand(2)));
  4585. setValue(&I, Add);
  4586. }
  4587. return nullptr;
  4588. }
  4589. case Intrinsic::convert_to_fp16:
  4590. setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
  4591. DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
  4592. getValue(I.getArgOperand(0)),
  4593. DAG.getTargetConstant(0, MVT::i32))));
  4594. return nullptr;
  4595. case Intrinsic::convert_from_fp16:
  4596. setValue(&I,
  4597. DAG.getNode(ISD::FP_EXTEND, sdl, TLI.getValueType(I.getType()),
  4598. DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
  4599. getValue(I.getArgOperand(0)))));
  4600. return nullptr;
  4601. case Intrinsic::pcmarker: {
  4602. SDValue Tmp = getValue(I.getArgOperand(0));
  4603. DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
  4604. return nullptr;
  4605. }
  4606. case Intrinsic::readcyclecounter: {
  4607. SDValue Op = getRoot();
  4608. Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
  4609. DAG.getVTList(MVT::i64, MVT::Other), Op);
  4610. setValue(&I, Res);
  4611. DAG.setRoot(Res.getValue(1));
  4612. return nullptr;
  4613. }
  4614. case Intrinsic::bswap:
  4615. setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
  4616. getValue(I.getArgOperand(0)).getValueType(),
  4617. getValue(I.getArgOperand(0))));
  4618. return nullptr;
  4619. case Intrinsic::cttz: {
  4620. SDValue Arg = getValue(I.getArgOperand(0));
  4621. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  4622. EVT Ty = Arg.getValueType();
  4623. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
  4624. sdl, Ty, Arg));
  4625. return nullptr;
  4626. }
  4627. case Intrinsic::ctlz: {
  4628. SDValue Arg = getValue(I.getArgOperand(0));
  4629. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  4630. EVT Ty = Arg.getValueType();
  4631. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
  4632. sdl, Ty, Arg));
  4633. return nullptr;
  4634. }
  4635. case Intrinsic::ctpop: {
  4636. SDValue Arg = getValue(I.getArgOperand(0));
  4637. EVT Ty = Arg.getValueType();
  4638. setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
  4639. return nullptr;
  4640. }
  4641. case Intrinsic::stacksave: {
  4642. SDValue Op = getRoot();
  4643. Res = DAG.getNode(ISD::STACKSAVE, sdl,
  4644. DAG.getVTList(TLI.getPointerTy(), MVT::Other), Op);
  4645. setValue(&I, Res);
  4646. DAG.setRoot(Res.getValue(1));
  4647. return nullptr;
  4648. }
  4649. case Intrinsic::stackrestore: {
  4650. Res = getValue(I.getArgOperand(0));
  4651. DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
  4652. return nullptr;
  4653. }
  4654. case Intrinsic::stackprotector: {
  4655. // Emit code into the DAG to store the stack guard onto the stack.
  4656. MachineFunction &MF = DAG.getMachineFunction();
  4657. MachineFrameInfo *MFI = MF.getFrameInfo();
  4658. EVT PtrTy = TLI.getPointerTy();
  4659. SDValue Src, Chain = getRoot();
  4660. const Value *Ptr = cast<LoadInst>(I.getArgOperand(0))->getPointerOperand();
  4661. const GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr);
  4662. // See if Ptr is a bitcast. If it is, look through it and see if we can get
  4663. // global variable __stack_chk_guard.
  4664. if (!GV)
  4665. if (const Operator *BC = dyn_cast<Operator>(Ptr))
  4666. if (BC->getOpcode() == Instruction::BitCast)
  4667. GV = dyn_cast<GlobalVariable>(BC->getOperand(0));
  4668. if (GV && TLI.useLoadStackGuardNode()) {
  4669. // Emit a LOAD_STACK_GUARD node.
  4670. MachineSDNode *Node = DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD,
  4671. sdl, PtrTy, Chain);
  4672. MachinePointerInfo MPInfo(GV);
  4673. MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
  4674. unsigned Flags = MachineMemOperand::MOLoad |
  4675. MachineMemOperand::MOInvariant;
  4676. *MemRefs = MF.getMachineMemOperand(MPInfo, Flags,
  4677. PtrTy.getSizeInBits() / 8,
  4678. DAG.getEVTAlignment(PtrTy));
  4679. Node->setMemRefs(MemRefs, MemRefs + 1);
  4680. // Copy the guard value to a virtual register so that it can be
  4681. // retrieved in the epilogue.
  4682. Src = SDValue(Node, 0);
  4683. const TargetRegisterClass *RC =
  4684. TLI.getRegClassFor(Src.getSimpleValueType());
  4685. unsigned Reg = MF.getRegInfo().createVirtualRegister(RC);
  4686. SPDescriptor.setGuardReg(Reg);
  4687. Chain = DAG.getCopyToReg(Chain, sdl, Reg, Src);
  4688. } else {
  4689. Src = getValue(I.getArgOperand(0)); // The guard's value.
  4690. }
  4691. AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
  4692. int FI = FuncInfo.StaticAllocaMap[Slot];
  4693. MFI->setStackProtectorIndex(FI);
  4694. SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
  4695. // Store the stack protector onto the stack.
  4696. Res = DAG.getStore(Chain, sdl, Src, FIN,
  4697. MachinePointerInfo::getFixedStack(FI),
  4698. true, false, 0);
  4699. setValue(&I, Res);
  4700. DAG.setRoot(Res);
  4701. return nullptr;
  4702. }
  4703. case Intrinsic::objectsize: {
  4704. // If we don't know by now, we're never going to know.
  4705. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
  4706. assert(CI && "Non-constant type in __builtin_object_size?");
  4707. SDValue Arg = getValue(I.getCalledValue());
  4708. EVT Ty = Arg.getValueType();
  4709. if (CI->isZero())
  4710. Res = DAG.getConstant(-1ULL, Ty);
  4711. else
  4712. Res = DAG.getConstant(0, Ty);
  4713. setValue(&I, Res);
  4714. return nullptr;
  4715. }
  4716. case Intrinsic::annotation:
  4717. case Intrinsic::ptr_annotation:
  4718. // Drop the intrinsic, but forward the value
  4719. setValue(&I, getValue(I.getOperand(0)));
  4720. return nullptr;
  4721. case Intrinsic::assume:
  4722. case Intrinsic::var_annotation:
  4723. // Discard annotate attributes and assumptions
  4724. return nullptr;
  4725. case Intrinsic::init_trampoline: {
  4726. const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
  4727. SDValue Ops[6];
  4728. Ops[0] = getRoot();
  4729. Ops[1] = getValue(I.getArgOperand(0));
  4730. Ops[2] = getValue(I.getArgOperand(1));
  4731. Ops[3] = getValue(I.getArgOperand(2));
  4732. Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
  4733. Ops[5] = DAG.getSrcValue(F);
  4734. Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
  4735. DAG.setRoot(Res);
  4736. return nullptr;
  4737. }
  4738. case Intrinsic::adjust_trampoline: {
  4739. setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
  4740. TLI.getPointerTy(),
  4741. getValue(I.getArgOperand(0))));
  4742. return nullptr;
  4743. }
  4744. case Intrinsic::gcroot:
  4745. if (GFI) {
  4746. const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
  4747. const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
  4748. FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
  4749. GFI->addStackRoot(FI->getIndex(), TypeMap);
  4750. }
  4751. return nullptr;
  4752. case Intrinsic::gcread:
  4753. case Intrinsic::gcwrite:
  4754. llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
  4755. case Intrinsic::flt_rounds:
  4756. setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
  4757. return nullptr;
  4758. case Intrinsic::expect: {
  4759. // Just replace __builtin_expect(exp, c) with EXP.
  4760. setValue(&I, getValue(I.getArgOperand(0)));
  4761. return nullptr;
  4762. }
  4763. case Intrinsic::debugtrap:
  4764. case Intrinsic::trap: {
  4765. StringRef TrapFuncName = TM.Options.getTrapFunctionName();
  4766. if (TrapFuncName.empty()) {
  4767. ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
  4768. ISD::TRAP : ISD::DEBUGTRAP;
  4769. DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
  4770. return nullptr;
  4771. }
  4772. TargetLowering::ArgListTy Args;
  4773. TargetLowering::CallLoweringInfo CLI(DAG);
  4774. CLI.setDebugLoc(sdl).setChain(getRoot())
  4775. .setCallee(CallingConv::C, I.getType(),
  4776. DAG.getExternalSymbol(TrapFuncName.data(), TLI.getPointerTy()),
  4777. std::move(Args), 0);
  4778. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  4779. DAG.setRoot(Result.second);
  4780. return nullptr;
  4781. }
  4782. case Intrinsic::uadd_with_overflow:
  4783. case Intrinsic::sadd_with_overflow:
  4784. case Intrinsic::usub_with_overflow:
  4785. case Intrinsic::ssub_with_overflow:
  4786. case Intrinsic::umul_with_overflow:
  4787. case Intrinsic::smul_with_overflow: {
  4788. ISD::NodeType Op;
  4789. switch (Intrinsic) {
  4790. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  4791. case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
  4792. case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
  4793. case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
  4794. case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
  4795. case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
  4796. case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
  4797. }
  4798. SDValue Op1 = getValue(I.getArgOperand(0));
  4799. SDValue Op2 = getValue(I.getArgOperand(1));
  4800. SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
  4801. setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
  4802. return nullptr;
  4803. }
  4804. case Intrinsic::prefetch: {
  4805. SDValue Ops[5];
  4806. unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  4807. Ops[0] = getRoot();
  4808. Ops[1] = getValue(I.getArgOperand(0));
  4809. Ops[2] = getValue(I.getArgOperand(1));
  4810. Ops[3] = getValue(I.getArgOperand(2));
  4811. Ops[4] = getValue(I.getArgOperand(3));
  4812. DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
  4813. DAG.getVTList(MVT::Other), Ops,
  4814. EVT::getIntegerVT(*Context, 8),
  4815. MachinePointerInfo(I.getArgOperand(0)),
  4816. 0, /* align */
  4817. false, /* volatile */
  4818. rw==0, /* read */
  4819. rw==1)); /* write */
  4820. return nullptr;
  4821. }
  4822. case Intrinsic::lifetime_start:
  4823. case Intrinsic::lifetime_end: {
  4824. bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
  4825. // Stack coloring is not enabled in O0, discard region information.
  4826. if (TM.getOptLevel() == CodeGenOpt::None)
  4827. return nullptr;
  4828. SmallVector<Value *, 4> Allocas;
  4829. GetUnderlyingObjects(I.getArgOperand(1), Allocas, DL);
  4830. for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
  4831. E = Allocas.end(); Object != E; ++Object) {
  4832. AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
  4833. // Could not find an Alloca.
  4834. if (!LifetimeObject)
  4835. continue;
  4836. // First check that the Alloca is static, otherwise it won't have a
  4837. // valid frame index.
  4838. auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
  4839. if (SI == FuncInfo.StaticAllocaMap.end())
  4840. return nullptr;
  4841. int FI = SI->second;
  4842. SDValue Ops[2];
  4843. Ops[0] = getRoot();
  4844. Ops[1] = DAG.getFrameIndex(FI, TLI.getPointerTy(), true);
  4845. unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
  4846. Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
  4847. DAG.setRoot(Res);
  4848. }
  4849. return nullptr;
  4850. }
  4851. case Intrinsic::invariant_start:
  4852. // Discard region information.
  4853. setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
  4854. return nullptr;
  4855. case Intrinsic::invariant_end:
  4856. // Discard region information.
  4857. return nullptr;
  4858. case Intrinsic::stackprotectorcheck: {
  4859. // Do not actually emit anything for this basic block. Instead we initialize
  4860. // the stack protector descriptor and export the guard variable so we can
  4861. // access it in FinishBasicBlock.
  4862. const BasicBlock *BB = I.getParent();
  4863. SPDescriptor.initialize(BB, FuncInfo.MBBMap[BB], I);
  4864. ExportFromCurrentBlock(SPDescriptor.getGuard());
  4865. // Flush our exports since we are going to process a terminator.
  4866. (void)getControlRoot();
  4867. return nullptr;
  4868. }
  4869. case Intrinsic::clear_cache:
  4870. return TLI.getClearCacheBuiltinName();
  4871. case Intrinsic::donothing:
  4872. // ignore
  4873. return nullptr;
  4874. case Intrinsic::experimental_stackmap: {
  4875. visitStackmap(I);
  4876. return nullptr;
  4877. }
  4878. case Intrinsic::experimental_patchpoint_void:
  4879. case Intrinsic::experimental_patchpoint_i64: {
  4880. visitPatchpoint(&I);
  4881. return nullptr;
  4882. }
  4883. case Intrinsic::experimental_gc_statepoint: {
  4884. visitStatepoint(I);
  4885. return nullptr;
  4886. }
  4887. case Intrinsic::experimental_gc_result_int:
  4888. case Intrinsic::experimental_gc_result_float:
  4889. case Intrinsic::experimental_gc_result_ptr: {
  4890. visitGCResult(I);
  4891. return nullptr;
  4892. }
  4893. case Intrinsic::experimental_gc_relocate: {
  4894. visitGCRelocate(I);
  4895. return nullptr;
  4896. }
  4897. case Intrinsic::instrprof_increment:
  4898. llvm_unreachable("instrprof failed to lower an increment");
  4899. }
  4900. }
  4901. std::pair<SDValue, SDValue>
  4902. SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
  4903. MachineBasicBlock *LandingPad) {
  4904. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  4905. MCSymbol *BeginLabel = nullptr;
  4906. if (LandingPad) {
  4907. // Insert a label before the invoke call to mark the try range. This can be
  4908. // used to detect deletion of the invoke via the MachineModuleInfo.
  4909. BeginLabel = MMI.getContext().CreateTempSymbol();
  4910. // For SjLj, keep track of which landing pads go with which invokes
  4911. // so as to maintain the ordering of pads in the LSDA.
  4912. unsigned CallSiteIndex = MMI.getCurrentCallSite();
  4913. if (CallSiteIndex) {
  4914. MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
  4915. LPadToCallSiteMap[LandingPad].push_back(CallSiteIndex);
  4916. // Now that the call site is handled, stop tracking it.
  4917. MMI.setCurrentCallSite(0);
  4918. }
  4919. // Both PendingLoads and PendingExports must be flushed here;
  4920. // this call might not return.
  4921. (void)getRoot();
  4922. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
  4923. CLI.setChain(getRoot());
  4924. }
  4925. const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
  4926. std::pair<SDValue, SDValue> Result = TLI->LowerCallTo(CLI);
  4927. assert((CLI.IsTailCall || Result.second.getNode()) &&
  4928. "Non-null chain expected with non-tail call!");
  4929. assert((Result.second.getNode() || !Result.first.getNode()) &&
  4930. "Null value expected with tail call!");
  4931. if (!Result.second.getNode()) {
  4932. // As a special case, a null chain means that a tail call has been emitted
  4933. // and the DAG root is already updated.
  4934. HasTailCall = true;
  4935. // Since there's no actual continuation from this block, nothing can be
  4936. // relying on us setting vregs for them.
  4937. PendingExports.clear();
  4938. } else {
  4939. DAG.setRoot(Result.second);
  4940. }
  4941. if (LandingPad) {
  4942. // Insert a label at the end of the invoke call to mark the try range. This
  4943. // can be used to detect deletion of the invoke via the MachineModuleInfo.
  4944. MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol();
  4945. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
  4946. // Inform MachineModuleInfo of range.
  4947. MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
  4948. }
  4949. return Result;
  4950. }
  4951. void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
  4952. bool isTailCall,
  4953. MachineBasicBlock *LandingPad) {
  4954. PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
  4955. FunctionType *FTy = cast<FunctionType>(PT->getElementType());
  4956. Type *RetTy = FTy->getReturnType();
  4957. TargetLowering::ArgListTy Args;
  4958. TargetLowering::ArgListEntry Entry;
  4959. Args.reserve(CS.arg_size());
  4960. for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
  4961. i != e; ++i) {
  4962. const Value *V = *i;
  4963. // Skip empty types
  4964. if (V->getType()->isEmptyTy())
  4965. continue;
  4966. SDValue ArgNode = getValue(V);
  4967. Entry.Node = ArgNode; Entry.Ty = V->getType();
  4968. // Skip the first return-type Attribute to get to params.
  4969. Entry.setAttributes(&CS, i - CS.arg_begin() + 1);
  4970. Args.push_back(Entry);
  4971. }
  4972. // Check if target-independent constraints permit a tail call here.
  4973. // Target-dependent constraints are checked within TLI->LowerCallTo.
  4974. if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
  4975. isTailCall = false;
  4976. TargetLowering::CallLoweringInfo CLI(DAG);
  4977. CLI.setDebugLoc(getCurSDLoc()).setChain(getRoot())
  4978. .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
  4979. .setTailCall(isTailCall);
  4980. std::pair<SDValue,SDValue> Result = lowerInvokable(CLI, LandingPad);
  4981. if (Result.first.getNode())
  4982. setValue(CS.getInstruction(), Result.first);
  4983. }
  4984. /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
  4985. /// value is equal or not-equal to zero.
  4986. static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
  4987. for (const User *U : V->users()) {
  4988. if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
  4989. if (IC->isEquality())
  4990. if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
  4991. if (C->isNullValue())
  4992. continue;
  4993. // Unknown instruction.
  4994. return false;
  4995. }
  4996. return true;
  4997. }
  4998. static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
  4999. Type *LoadTy,
  5000. SelectionDAGBuilder &Builder) {
  5001. // Check to see if this load can be trivially constant folded, e.g. if the
  5002. // input is from a string literal.
  5003. if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
  5004. // Cast pointer to the type we really want to load.
  5005. LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
  5006. PointerType::getUnqual(LoadTy));
  5007. if (const Constant *LoadCst =
  5008. ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
  5009. Builder.DL))
  5010. return Builder.getValue(LoadCst);
  5011. }
  5012. // Otherwise, we have to emit the load. If the pointer is to unfoldable but
  5013. // still constant memory, the input chain can be the entry node.
  5014. SDValue Root;
  5015. bool ConstantMemory = false;
  5016. // Do not serialize (non-volatile) loads of constant memory with anything.
  5017. if (Builder.AA->pointsToConstantMemory(PtrVal)) {
  5018. Root = Builder.DAG.getEntryNode();
  5019. ConstantMemory = true;
  5020. } else {
  5021. // Do not serialize non-volatile loads against each other.
  5022. Root = Builder.DAG.getRoot();
  5023. }
  5024. SDValue Ptr = Builder.getValue(PtrVal);
  5025. SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
  5026. Ptr, MachinePointerInfo(PtrVal),
  5027. false /*volatile*/,
  5028. false /*nontemporal*/,
  5029. false /*isinvariant*/, 1 /* align=1 */);
  5030. if (!ConstantMemory)
  5031. Builder.PendingLoads.push_back(LoadVal.getValue(1));
  5032. return LoadVal;
  5033. }
  5034. /// processIntegerCallValue - Record the value for an instruction that
  5035. /// produces an integer result, converting the type where necessary.
  5036. void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
  5037. SDValue Value,
  5038. bool IsSigned) {
  5039. EVT VT = DAG.getTargetLoweringInfo().getValueType(I.getType(), true);
  5040. if (IsSigned)
  5041. Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
  5042. else
  5043. Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
  5044. setValue(&I, Value);
  5045. }
  5046. /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
  5047. /// If so, return true and lower it, otherwise return false and it will be
  5048. /// lowered like a normal call.
  5049. bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
  5050. // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
  5051. if (I.getNumArgOperands() != 3)
  5052. return false;
  5053. const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
  5054. if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
  5055. !I.getArgOperand(2)->getType()->isIntegerTy() ||
  5056. !I.getType()->isIntegerTy())
  5057. return false;
  5058. const Value *Size = I.getArgOperand(2);
  5059. const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
  5060. if (CSize && CSize->getZExtValue() == 0) {
  5061. EVT CallVT = DAG.getTargetLoweringInfo().getValueType(I.getType(), true);
  5062. setValue(&I, DAG.getConstant(0, CallVT));
  5063. return true;
  5064. }
  5065. const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
  5066. std::pair<SDValue, SDValue> Res =
  5067. TSI.EmitTargetCodeForMemcmp(DAG, getCurSDLoc(), DAG.getRoot(),
  5068. getValue(LHS), getValue(RHS), getValue(Size),
  5069. MachinePointerInfo(LHS),
  5070. MachinePointerInfo(RHS));
  5071. if (Res.first.getNode()) {
  5072. processIntegerCallValue(I, Res.first, true);
  5073. PendingLoads.push_back(Res.second);
  5074. return true;
  5075. }
  5076. // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
  5077. // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
  5078. if (CSize && IsOnlyUsedInZeroEqualityComparison(&I)) {
  5079. bool ActuallyDoIt = true;
  5080. MVT LoadVT;
  5081. Type *LoadTy;
  5082. switch (CSize->getZExtValue()) {
  5083. default:
  5084. LoadVT = MVT::Other;
  5085. LoadTy = nullptr;
  5086. ActuallyDoIt = false;
  5087. break;
  5088. case 2:
  5089. LoadVT = MVT::i16;
  5090. LoadTy = Type::getInt16Ty(CSize->getContext());
  5091. break;
  5092. case 4:
  5093. LoadVT = MVT::i32;
  5094. LoadTy = Type::getInt32Ty(CSize->getContext());
  5095. break;
  5096. case 8:
  5097. LoadVT = MVT::i64;
  5098. LoadTy = Type::getInt64Ty(CSize->getContext());
  5099. break;
  5100. /*
  5101. case 16:
  5102. LoadVT = MVT::v4i32;
  5103. LoadTy = Type::getInt32Ty(CSize->getContext());
  5104. LoadTy = VectorType::get(LoadTy, 4);
  5105. break;
  5106. */
  5107. }
  5108. // This turns into unaligned loads. We only do this if the target natively
  5109. // supports the MVT we'll be loading or if it is small enough (<= 4) that
  5110. // we'll only produce a small number of byte loads.
  5111. // Require that we can find a legal MVT, and only do this if the target
  5112. // supports unaligned loads of that type. Expanding into byte loads would
  5113. // bloat the code.
  5114. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5115. if (ActuallyDoIt && CSize->getZExtValue() > 4) {
  5116. unsigned DstAS = LHS->getType()->getPointerAddressSpace();
  5117. unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
  5118. // TODO: Handle 5 byte compare as 4-byte + 1 byte.
  5119. // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
  5120. // TODO: Check alignment of src and dest ptrs.
  5121. if (!TLI.isTypeLegal(LoadVT) ||
  5122. !TLI.allowsMisalignedMemoryAccesses(LoadVT, SrcAS) ||
  5123. !TLI.allowsMisalignedMemoryAccesses(LoadVT, DstAS))
  5124. ActuallyDoIt = false;
  5125. }
  5126. if (ActuallyDoIt) {
  5127. SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
  5128. SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
  5129. SDValue Res = DAG.getSetCC(getCurSDLoc(), MVT::i1, LHSVal, RHSVal,
  5130. ISD::SETNE);
  5131. processIntegerCallValue(I, Res, false);
  5132. return true;
  5133. }
  5134. }
  5135. return false;
  5136. }
  5137. /// visitMemChrCall -- See if we can lower a memchr call into an optimized
  5138. /// form. If so, return true and lower it, otherwise return false and it
  5139. /// will be lowered like a normal call.
  5140. bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
  5141. // Verify that the prototype makes sense. void *memchr(void *, int, size_t)
  5142. if (I.getNumArgOperands() != 3)
  5143. return false;
  5144. const Value *Src = I.getArgOperand(0);
  5145. const Value *Char = I.getArgOperand(1);
  5146. const Value *Length = I.getArgOperand(2);
  5147. if (!Src->getType()->isPointerTy() ||
  5148. !Char->getType()->isIntegerTy() ||
  5149. !Length->getType()->isIntegerTy() ||
  5150. !I.getType()->isPointerTy())
  5151. return false;
  5152. const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
  5153. std::pair<SDValue, SDValue> Res =
  5154. TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
  5155. getValue(Src), getValue(Char), getValue(Length),
  5156. MachinePointerInfo(Src));
  5157. if (Res.first.getNode()) {
  5158. setValue(&I, Res.first);
  5159. PendingLoads.push_back(Res.second);
  5160. return true;
  5161. }
  5162. return false;
  5163. }
  5164. /// visitStrCpyCall -- See if we can lower a strcpy or stpcpy call into an
  5165. /// optimized form. If so, return true and lower it, otherwise return false
  5166. /// and it will be lowered like a normal call.
  5167. bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
  5168. // Verify that the prototype makes sense. char *strcpy(char *, char *)
  5169. if (I.getNumArgOperands() != 2)
  5170. return false;
  5171. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  5172. if (!Arg0->getType()->isPointerTy() ||
  5173. !Arg1->getType()->isPointerTy() ||
  5174. !I.getType()->isPointerTy())
  5175. return false;
  5176. const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
  5177. std::pair<SDValue, SDValue> Res =
  5178. TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
  5179. getValue(Arg0), getValue(Arg1),
  5180. MachinePointerInfo(Arg0),
  5181. MachinePointerInfo(Arg1), isStpcpy);
  5182. if (Res.first.getNode()) {
  5183. setValue(&I, Res.first);
  5184. DAG.setRoot(Res.second);
  5185. return true;
  5186. }
  5187. return false;
  5188. }
  5189. /// visitStrCmpCall - See if we can lower a call to strcmp in an optimized form.
  5190. /// If so, return true and lower it, otherwise return false and it will be
  5191. /// lowered like a normal call.
  5192. bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
  5193. // Verify that the prototype makes sense. int strcmp(void*,void*)
  5194. if (I.getNumArgOperands() != 2)
  5195. return false;
  5196. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  5197. if (!Arg0->getType()->isPointerTy() ||
  5198. !Arg1->getType()->isPointerTy() ||
  5199. !I.getType()->isIntegerTy())
  5200. return false;
  5201. const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
  5202. std::pair<SDValue, SDValue> Res =
  5203. TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
  5204. getValue(Arg0), getValue(Arg1),
  5205. MachinePointerInfo(Arg0),
  5206. MachinePointerInfo(Arg1));
  5207. if (Res.first.getNode()) {
  5208. processIntegerCallValue(I, Res.first, true);
  5209. PendingLoads.push_back(Res.second);
  5210. return true;
  5211. }
  5212. return false;
  5213. }
  5214. /// visitStrLenCall -- See if we can lower a strlen call into an optimized
  5215. /// form. If so, return true and lower it, otherwise return false and it
  5216. /// will be lowered like a normal call.
  5217. bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
  5218. // Verify that the prototype makes sense. size_t strlen(char *)
  5219. if (I.getNumArgOperands() != 1)
  5220. return false;
  5221. const Value *Arg0 = I.getArgOperand(0);
  5222. if (!Arg0->getType()->isPointerTy() || !I.getType()->isIntegerTy())
  5223. return false;
  5224. const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
  5225. std::pair<SDValue, SDValue> Res =
  5226. TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
  5227. getValue(Arg0), MachinePointerInfo(Arg0));
  5228. if (Res.first.getNode()) {
  5229. processIntegerCallValue(I, Res.first, false);
  5230. PendingLoads.push_back(Res.second);
  5231. return true;
  5232. }
  5233. return false;
  5234. }
  5235. /// visitStrNLenCall -- See if we can lower a strnlen call into an optimized
  5236. /// form. If so, return true and lower it, otherwise return false and it
  5237. /// will be lowered like a normal call.
  5238. bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
  5239. // Verify that the prototype makes sense. size_t strnlen(char *, size_t)
  5240. if (I.getNumArgOperands() != 2)
  5241. return false;
  5242. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  5243. if (!Arg0->getType()->isPointerTy() ||
  5244. !Arg1->getType()->isIntegerTy() ||
  5245. !I.getType()->isIntegerTy())
  5246. return false;
  5247. const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
  5248. std::pair<SDValue, SDValue> Res =
  5249. TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
  5250. getValue(Arg0), getValue(Arg1),
  5251. MachinePointerInfo(Arg0));
  5252. if (Res.first.getNode()) {
  5253. processIntegerCallValue(I, Res.first, false);
  5254. PendingLoads.push_back(Res.second);
  5255. return true;
  5256. }
  5257. return false;
  5258. }
  5259. /// visitUnaryFloatCall - If a call instruction is a unary floating-point
  5260. /// operation (as expected), translate it to an SDNode with the specified opcode
  5261. /// and return true.
  5262. bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
  5263. unsigned Opcode) {
  5264. // Sanity check that it really is a unary floating-point call.
  5265. if (I.getNumArgOperands() != 1 ||
  5266. !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
  5267. I.getType() != I.getArgOperand(0)->getType() ||
  5268. !I.onlyReadsMemory())
  5269. return false;
  5270. SDValue Tmp = getValue(I.getArgOperand(0));
  5271. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
  5272. return true;
  5273. }
  5274. /// visitBinaryFloatCall - If a call instruction is a binary floating-point
  5275. /// operation (as expected), translate it to an SDNode with the specified opcode
  5276. /// and return true.
  5277. bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
  5278. unsigned Opcode) {
  5279. // Sanity check that it really is a binary floating-point call.
  5280. if (I.getNumArgOperands() != 2 ||
  5281. !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
  5282. I.getType() != I.getArgOperand(0)->getType() ||
  5283. I.getType() != I.getArgOperand(1)->getType() ||
  5284. !I.onlyReadsMemory())
  5285. return false;
  5286. SDValue Tmp0 = getValue(I.getArgOperand(0));
  5287. SDValue Tmp1 = getValue(I.getArgOperand(1));
  5288. EVT VT = Tmp0.getValueType();
  5289. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
  5290. return true;
  5291. }
  5292. void SelectionDAGBuilder::visitCall(const CallInst &I) {
  5293. // Handle inline assembly differently.
  5294. if (isa<InlineAsm>(I.getCalledValue())) {
  5295. visitInlineAsm(&I);
  5296. return;
  5297. }
  5298. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  5299. ComputeUsesVAFloatArgument(I, &MMI);
  5300. const char *RenameFn = nullptr;
  5301. if (Function *F = I.getCalledFunction()) {
  5302. if (F->isDeclaration()) {
  5303. if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
  5304. if (unsigned IID = II->getIntrinsicID(F)) {
  5305. RenameFn = visitIntrinsicCall(I, IID);
  5306. if (!RenameFn)
  5307. return;
  5308. }
  5309. }
  5310. if (unsigned IID = F->getIntrinsicID()) {
  5311. RenameFn = visitIntrinsicCall(I, IID);
  5312. if (!RenameFn)
  5313. return;
  5314. }
  5315. }
  5316. // Check for well-known libc/libm calls. If the function is internal, it
  5317. // can't be a library call.
  5318. LibFunc::Func Func;
  5319. if (!F->hasLocalLinkage() && F->hasName() &&
  5320. LibInfo->getLibFunc(F->getName(), Func) &&
  5321. LibInfo->hasOptimizedCodeGen(Func)) {
  5322. switch (Func) {
  5323. default: break;
  5324. case LibFunc::copysign:
  5325. case LibFunc::copysignf:
  5326. case LibFunc::copysignl:
  5327. if (I.getNumArgOperands() == 2 && // Basic sanity checks.
  5328. I.getArgOperand(0)->getType()->isFloatingPointTy() &&
  5329. I.getType() == I.getArgOperand(0)->getType() &&
  5330. I.getType() == I.getArgOperand(1)->getType() &&
  5331. I.onlyReadsMemory()) {
  5332. SDValue LHS = getValue(I.getArgOperand(0));
  5333. SDValue RHS = getValue(I.getArgOperand(1));
  5334. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
  5335. LHS.getValueType(), LHS, RHS));
  5336. return;
  5337. }
  5338. break;
  5339. case LibFunc::fabs:
  5340. case LibFunc::fabsf:
  5341. case LibFunc::fabsl:
  5342. if (visitUnaryFloatCall(I, ISD::FABS))
  5343. return;
  5344. break;
  5345. case LibFunc::fmin:
  5346. case LibFunc::fminf:
  5347. case LibFunc::fminl:
  5348. if (visitBinaryFloatCall(I, ISD::FMINNUM))
  5349. return;
  5350. break;
  5351. case LibFunc::fmax:
  5352. case LibFunc::fmaxf:
  5353. case LibFunc::fmaxl:
  5354. if (visitBinaryFloatCall(I, ISD::FMAXNUM))
  5355. return;
  5356. break;
  5357. case LibFunc::sin:
  5358. case LibFunc::sinf:
  5359. case LibFunc::sinl:
  5360. if (visitUnaryFloatCall(I, ISD::FSIN))
  5361. return;
  5362. break;
  5363. case LibFunc::cos:
  5364. case LibFunc::cosf:
  5365. case LibFunc::cosl:
  5366. if (visitUnaryFloatCall(I, ISD::FCOS))
  5367. return;
  5368. break;
  5369. case LibFunc::sqrt:
  5370. case LibFunc::sqrtf:
  5371. case LibFunc::sqrtl:
  5372. case LibFunc::sqrt_finite:
  5373. case LibFunc::sqrtf_finite:
  5374. case LibFunc::sqrtl_finite:
  5375. if (visitUnaryFloatCall(I, ISD::FSQRT))
  5376. return;
  5377. break;
  5378. case LibFunc::floor:
  5379. case LibFunc::floorf:
  5380. case LibFunc::floorl:
  5381. if (visitUnaryFloatCall(I, ISD::FFLOOR))
  5382. return;
  5383. break;
  5384. case LibFunc::nearbyint:
  5385. case LibFunc::nearbyintf:
  5386. case LibFunc::nearbyintl:
  5387. if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
  5388. return;
  5389. break;
  5390. case LibFunc::ceil:
  5391. case LibFunc::ceilf:
  5392. case LibFunc::ceill:
  5393. if (visitUnaryFloatCall(I, ISD::FCEIL))
  5394. return;
  5395. break;
  5396. case LibFunc::rint:
  5397. case LibFunc::rintf:
  5398. case LibFunc::rintl:
  5399. if (visitUnaryFloatCall(I, ISD::FRINT))
  5400. return;
  5401. break;
  5402. case LibFunc::round:
  5403. case LibFunc::roundf:
  5404. case LibFunc::roundl:
  5405. if (visitUnaryFloatCall(I, ISD::FROUND))
  5406. return;
  5407. break;
  5408. case LibFunc::trunc:
  5409. case LibFunc::truncf:
  5410. case LibFunc::truncl:
  5411. if (visitUnaryFloatCall(I, ISD::FTRUNC))
  5412. return;
  5413. break;
  5414. case LibFunc::log2:
  5415. case LibFunc::log2f:
  5416. case LibFunc::log2l:
  5417. if (visitUnaryFloatCall(I, ISD::FLOG2))
  5418. return;
  5419. break;
  5420. case LibFunc::exp2:
  5421. case LibFunc::exp2f:
  5422. case LibFunc::exp2l:
  5423. if (visitUnaryFloatCall(I, ISD::FEXP2))
  5424. return;
  5425. break;
  5426. case LibFunc::memcmp:
  5427. if (visitMemCmpCall(I))
  5428. return;
  5429. break;
  5430. case LibFunc::memchr:
  5431. if (visitMemChrCall(I))
  5432. return;
  5433. break;
  5434. case LibFunc::strcpy:
  5435. if (visitStrCpyCall(I, false))
  5436. return;
  5437. break;
  5438. case LibFunc::stpcpy:
  5439. if (visitStrCpyCall(I, true))
  5440. return;
  5441. break;
  5442. case LibFunc::strcmp:
  5443. if (visitStrCmpCall(I))
  5444. return;
  5445. break;
  5446. case LibFunc::strlen:
  5447. if (visitStrLenCall(I))
  5448. return;
  5449. break;
  5450. case LibFunc::strnlen:
  5451. if (visitStrNLenCall(I))
  5452. return;
  5453. break;
  5454. }
  5455. }
  5456. }
  5457. SDValue Callee;
  5458. if (!RenameFn)
  5459. Callee = getValue(I.getCalledValue());
  5460. else
  5461. Callee = DAG.getExternalSymbol(RenameFn,
  5462. DAG.getTargetLoweringInfo().getPointerTy());
  5463. // Check if we can potentially perform a tail call. More detailed checking is
  5464. // be done within LowerCallTo, after more information about the call is known.
  5465. LowerCallTo(&I, Callee, I.isTailCall());
  5466. }
  5467. namespace {
  5468. /// AsmOperandInfo - This contains information for each constraint that we are
  5469. /// lowering.
  5470. class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
  5471. public:
  5472. /// CallOperand - If this is the result output operand or a clobber
  5473. /// this is null, otherwise it is the incoming operand to the CallInst.
  5474. /// This gets modified as the asm is processed.
  5475. SDValue CallOperand;
  5476. /// AssignedRegs - If this is a register or register class operand, this
  5477. /// contains the set of register corresponding to the operand.
  5478. RegsForValue AssignedRegs;
  5479. explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
  5480. : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr,0) {
  5481. }
  5482. /// getCallOperandValEVT - Return the EVT of the Value* that this operand
  5483. /// corresponds to. If there is no Value* for this operand, it returns
  5484. /// MVT::Other.
  5485. EVT getCallOperandValEVT(LLVMContext &Context,
  5486. const TargetLowering &TLI,
  5487. const DataLayout *DL) const {
  5488. if (!CallOperandVal) return MVT::Other;
  5489. if (isa<BasicBlock>(CallOperandVal))
  5490. return TLI.getPointerTy();
  5491. llvm::Type *OpTy = CallOperandVal->getType();
  5492. // FIXME: code duplicated from TargetLowering::ParseConstraints().
  5493. // If this is an indirect operand, the operand is a pointer to the
  5494. // accessed type.
  5495. if (isIndirect) {
  5496. llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
  5497. if (!PtrTy)
  5498. report_fatal_error("Indirect operand for inline asm not a pointer!");
  5499. OpTy = PtrTy->getElementType();
  5500. }
  5501. // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
  5502. if (StructType *STy = dyn_cast<StructType>(OpTy))
  5503. if (STy->getNumElements() == 1)
  5504. OpTy = STy->getElementType(0);
  5505. // If OpTy is not a single value, it may be a struct/union that we
  5506. // can tile with integers.
  5507. if (!OpTy->isSingleValueType() && OpTy->isSized()) {
  5508. unsigned BitSize = DL->getTypeSizeInBits(OpTy);
  5509. switch (BitSize) {
  5510. default: break;
  5511. case 1:
  5512. case 8:
  5513. case 16:
  5514. case 32:
  5515. case 64:
  5516. case 128:
  5517. OpTy = IntegerType::get(Context, BitSize);
  5518. break;
  5519. }
  5520. }
  5521. return TLI.getValueType(OpTy, true);
  5522. }
  5523. };
  5524. typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
  5525. } // end anonymous namespace
  5526. /// GetRegistersForValue - Assign registers (virtual or physical) for the
  5527. /// specified operand. We prefer to assign virtual registers, to allow the
  5528. /// register allocator to handle the assignment process. However, if the asm
  5529. /// uses features that we can't model on machineinstrs, we have SDISel do the
  5530. /// allocation. This produces generally horrible, but correct, code.
  5531. ///
  5532. /// OpInfo describes the operand.
  5533. ///
  5534. static void GetRegistersForValue(SelectionDAG &DAG,
  5535. const TargetLowering &TLI,
  5536. SDLoc DL,
  5537. SDISelAsmOperandInfo &OpInfo) {
  5538. LLVMContext &Context = *DAG.getContext();
  5539. MachineFunction &MF = DAG.getMachineFunction();
  5540. SmallVector<unsigned, 4> Regs;
  5541. // If this is a constraint for a single physreg, or a constraint for a
  5542. // register class, find it.
  5543. std::pair<unsigned, const TargetRegisterClass*> PhysReg =
  5544. TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
  5545. OpInfo.ConstraintVT);
  5546. unsigned NumRegs = 1;
  5547. if (OpInfo.ConstraintVT != MVT::Other) {
  5548. // If this is a FP input in an integer register (or visa versa) insert a bit
  5549. // cast of the input value. More generally, handle any case where the input
  5550. // value disagrees with the register class we plan to stick this in.
  5551. if (OpInfo.Type == InlineAsm::isInput &&
  5552. PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
  5553. // Try to convert to the first EVT that the reg class contains. If the
  5554. // types are identical size, use a bitcast to convert (e.g. two differing
  5555. // vector types).
  5556. MVT RegVT = *PhysReg.second->vt_begin();
  5557. if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
  5558. OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
  5559. RegVT, OpInfo.CallOperand);
  5560. OpInfo.ConstraintVT = RegVT;
  5561. } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
  5562. // If the input is a FP value and we want it in FP registers, do a
  5563. // bitcast to the corresponding integer type. This turns an f64 value
  5564. // into i64, which can be passed with two i32 values on a 32-bit
  5565. // machine.
  5566. RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
  5567. OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
  5568. RegVT, OpInfo.CallOperand);
  5569. OpInfo.ConstraintVT = RegVT;
  5570. }
  5571. }
  5572. NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
  5573. }
  5574. MVT RegVT;
  5575. EVT ValueVT = OpInfo.ConstraintVT;
  5576. // If this is a constraint for a specific physical register, like {r17},
  5577. // assign it now.
  5578. if (unsigned AssignedReg = PhysReg.first) {
  5579. const TargetRegisterClass *RC = PhysReg.second;
  5580. if (OpInfo.ConstraintVT == MVT::Other)
  5581. ValueVT = *RC->vt_begin();
  5582. // Get the actual register value type. This is important, because the user
  5583. // may have asked for (e.g.) the AX register in i32 type. We need to
  5584. // remember that AX is actually i16 to get the right extension.
  5585. RegVT = *RC->vt_begin();
  5586. // This is a explicit reference to a physical register.
  5587. Regs.push_back(AssignedReg);
  5588. // If this is an expanded reference, add the rest of the regs to Regs.
  5589. if (NumRegs != 1) {
  5590. TargetRegisterClass::iterator I = RC->begin();
  5591. for (; *I != AssignedReg; ++I)
  5592. assert(I != RC->end() && "Didn't find reg!");
  5593. // Already added the first reg.
  5594. --NumRegs; ++I;
  5595. for (; NumRegs; --NumRegs, ++I) {
  5596. assert(I != RC->end() && "Ran out of registers to allocate!");
  5597. Regs.push_back(*I);
  5598. }
  5599. }
  5600. OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
  5601. return;
  5602. }
  5603. // Otherwise, if this was a reference to an LLVM register class, create vregs
  5604. // for this reference.
  5605. if (const TargetRegisterClass *RC = PhysReg.second) {
  5606. RegVT = *RC->vt_begin();
  5607. if (OpInfo.ConstraintVT == MVT::Other)
  5608. ValueVT = RegVT;
  5609. // Create the appropriate number of virtual registers.
  5610. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  5611. for (; NumRegs; --NumRegs)
  5612. Regs.push_back(RegInfo.createVirtualRegister(RC));
  5613. OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
  5614. return;
  5615. }
  5616. // Otherwise, we couldn't allocate enough registers for this.
  5617. }
  5618. /// visitInlineAsm - Handle a call to an InlineAsm object.
  5619. ///
  5620. void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
  5621. const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  5622. /// ConstraintOperands - Information about all of the constraints.
  5623. SDISelAsmOperandInfoVector ConstraintOperands;
  5624. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5625. TargetLowering::AsmOperandInfoVector
  5626. TargetConstraints = TLI.ParseConstraints(CS);
  5627. bool hasMemory = false;
  5628. unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
  5629. unsigned ResNo = 0; // ResNo - The result number of the next output.
  5630. for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
  5631. ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
  5632. SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
  5633. MVT OpVT = MVT::Other;
  5634. // Compute the value type for each operand.
  5635. switch (OpInfo.Type) {
  5636. case InlineAsm::isOutput:
  5637. // Indirect outputs just consume an argument.
  5638. if (OpInfo.isIndirect) {
  5639. OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
  5640. break;
  5641. }
  5642. // The return value of the call is this value. As such, there is no
  5643. // corresponding argument.
  5644. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  5645. if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
  5646. OpVT = TLI.getSimpleValueType(STy->getElementType(ResNo));
  5647. } else {
  5648. assert(ResNo == 0 && "Asm only has one result!");
  5649. OpVT = TLI.getSimpleValueType(CS.getType());
  5650. }
  5651. ++ResNo;
  5652. break;
  5653. case InlineAsm::isInput:
  5654. OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
  5655. break;
  5656. case InlineAsm::isClobber:
  5657. // Nothing to do.
  5658. break;
  5659. }
  5660. // If this is an input or an indirect output, process the call argument.
  5661. // BasicBlocks are labels, currently appearing only in asm's.
  5662. if (OpInfo.CallOperandVal) {
  5663. if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
  5664. OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
  5665. } else {
  5666. OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
  5667. }
  5668. OpVT =
  5669. OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, DL).getSimpleVT();
  5670. }
  5671. OpInfo.ConstraintVT = OpVT;
  5672. // Indirect operand accesses access memory.
  5673. if (OpInfo.isIndirect)
  5674. hasMemory = true;
  5675. else {
  5676. for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) {
  5677. TargetLowering::ConstraintType
  5678. CType = TLI.getConstraintType(OpInfo.Codes[j]);
  5679. if (CType == TargetLowering::C_Memory) {
  5680. hasMemory = true;
  5681. break;
  5682. }
  5683. }
  5684. }
  5685. }
  5686. SDValue Chain, Flag;
  5687. // We won't need to flush pending loads if this asm doesn't touch
  5688. // memory and is nonvolatile.
  5689. if (hasMemory || IA->hasSideEffects())
  5690. Chain = getRoot();
  5691. else
  5692. Chain = DAG.getRoot();
  5693. // Second pass over the constraints: compute which constraint option to use
  5694. // and assign registers to constraints that want a specific physreg.
  5695. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  5696. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  5697. // If this is an output operand with a matching input operand, look up the
  5698. // matching input. If their types mismatch, e.g. one is an integer, the
  5699. // other is floating point, or their sizes are different, flag it as an
  5700. // error.
  5701. if (OpInfo.hasMatchingInput()) {
  5702. SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
  5703. if (OpInfo.ConstraintVT != Input.ConstraintVT) {
  5704. std::pair<unsigned, const TargetRegisterClass*> MatchRC =
  5705. TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
  5706. OpInfo.ConstraintVT);
  5707. std::pair<unsigned, const TargetRegisterClass*> InputRC =
  5708. TLI.getRegForInlineAsmConstraint(Input.ConstraintCode,
  5709. Input.ConstraintVT);
  5710. if ((OpInfo.ConstraintVT.isInteger() !=
  5711. Input.ConstraintVT.isInteger()) ||
  5712. (MatchRC.second != InputRC.second)) {
  5713. report_fatal_error("Unsupported asm: input constraint"
  5714. " with a matching output constraint of"
  5715. " incompatible type!");
  5716. }
  5717. Input.ConstraintVT = OpInfo.ConstraintVT;
  5718. }
  5719. }
  5720. // Compute the constraint code and ConstraintType to use.
  5721. TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
  5722. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  5723. OpInfo.Type == InlineAsm::isClobber)
  5724. continue;
  5725. // If this is a memory input, and if the operand is not indirect, do what we
  5726. // need to to provide an address for the memory input.
  5727. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  5728. !OpInfo.isIndirect) {
  5729. assert((OpInfo.isMultipleAlternative ||
  5730. (OpInfo.Type == InlineAsm::isInput)) &&
  5731. "Can only indirectify direct input operands!");
  5732. // Memory operands really want the address of the value. If we don't have
  5733. // an indirect input, put it in the constpool if we can, otherwise spill
  5734. // it to a stack slot.
  5735. // TODO: This isn't quite right. We need to handle these according to
  5736. // the addressing mode that the constraint wants. Also, this may take
  5737. // an additional register for the computation and we don't want that
  5738. // either.
  5739. // If the operand is a float, integer, or vector constant, spill to a
  5740. // constant pool entry to get its address.
  5741. const Value *OpVal = OpInfo.CallOperandVal;
  5742. if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
  5743. isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
  5744. OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
  5745. TLI.getPointerTy());
  5746. } else {
  5747. // Otherwise, create a stack slot and emit a store to it before the
  5748. // asm.
  5749. Type *Ty = OpVal->getType();
  5750. uint64_t TySize = TLI.getDataLayout()->getTypeAllocSize(Ty);
  5751. unsigned Align = TLI.getDataLayout()->getPrefTypeAlignment(Ty);
  5752. MachineFunction &MF = DAG.getMachineFunction();
  5753. int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
  5754. SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
  5755. Chain = DAG.getStore(Chain, getCurSDLoc(),
  5756. OpInfo.CallOperand, StackSlot,
  5757. MachinePointerInfo::getFixedStack(SSFI),
  5758. false, false, 0);
  5759. OpInfo.CallOperand = StackSlot;
  5760. }
  5761. // There is no longer a Value* corresponding to this operand.
  5762. OpInfo.CallOperandVal = nullptr;
  5763. // It is now an indirect operand.
  5764. OpInfo.isIndirect = true;
  5765. }
  5766. // If this constraint is for a specific register, allocate it before
  5767. // anything else.
  5768. if (OpInfo.ConstraintType == TargetLowering::C_Register)
  5769. GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
  5770. }
  5771. // Second pass - Loop over all of the operands, assigning virtual or physregs
  5772. // to register class operands.
  5773. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  5774. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  5775. // C_Register operands have already been allocated, Other/Memory don't need
  5776. // to be.
  5777. if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
  5778. GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
  5779. }
  5780. // AsmNodeOperands - The operands for the ISD::INLINEASM node.
  5781. std::vector<SDValue> AsmNodeOperands;
  5782. AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
  5783. AsmNodeOperands.push_back(
  5784. DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
  5785. TLI.getPointerTy()));
  5786. // If we have a !srcloc metadata node associated with it, we want to attach
  5787. // this to the ultimately generated inline asm machineinstr. To do this, we
  5788. // pass in the third operand as this (potentially null) inline asm MDNode.
  5789. const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
  5790. AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
  5791. // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
  5792. // bits as operand 3.
  5793. unsigned ExtraInfo = 0;
  5794. if (IA->hasSideEffects())
  5795. ExtraInfo |= InlineAsm::Extra_HasSideEffects;
  5796. if (IA->isAlignStack())
  5797. ExtraInfo |= InlineAsm::Extra_IsAlignStack;
  5798. // Set the asm dialect.
  5799. ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
  5800. // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
  5801. for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
  5802. TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
  5803. // Compute the constraint code and ConstraintType to use.
  5804. TLI.ComputeConstraintToUse(OpInfo, SDValue());
  5805. // Ideally, we would only check against memory constraints. However, the
  5806. // meaning of an other constraint can be target-specific and we can't easily
  5807. // reason about it. Therefore, be conservative and set MayLoad/MayStore
  5808. // for other constriants as well.
  5809. if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
  5810. OpInfo.ConstraintType == TargetLowering::C_Other) {
  5811. if (OpInfo.Type == InlineAsm::isInput)
  5812. ExtraInfo |= InlineAsm::Extra_MayLoad;
  5813. else if (OpInfo.Type == InlineAsm::isOutput)
  5814. ExtraInfo |= InlineAsm::Extra_MayStore;
  5815. else if (OpInfo.Type == InlineAsm::isClobber)
  5816. ExtraInfo |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
  5817. }
  5818. }
  5819. AsmNodeOperands.push_back(DAG.getTargetConstant(ExtraInfo,
  5820. TLI.getPointerTy()));
  5821. // Loop over all of the inputs, copying the operand values into the
  5822. // appropriate registers and processing the output regs.
  5823. RegsForValue RetValRegs;
  5824. // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
  5825. std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
  5826. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  5827. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  5828. switch (OpInfo.Type) {
  5829. case InlineAsm::isOutput: {
  5830. if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
  5831. OpInfo.ConstraintType != TargetLowering::C_Register) {
  5832. // Memory output, or 'other' output (e.g. 'X' constraint).
  5833. assert(OpInfo.isIndirect && "Memory output must be indirect operand");
  5834. // Add information to the INLINEASM node to know about this output.
  5835. unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  5836. AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags,
  5837. TLI.getPointerTy()));
  5838. AsmNodeOperands.push_back(OpInfo.CallOperand);
  5839. break;
  5840. }
  5841. // Otherwise, this is a register or register class output.
  5842. // Copy the output from the appropriate register. Find a register that
  5843. // we can use.
  5844. if (OpInfo.AssignedRegs.Regs.empty()) {
  5845. LLVMContext &Ctx = *DAG.getContext();
  5846. Ctx.emitError(CS.getInstruction(),
  5847. "couldn't allocate output register for constraint '" +
  5848. Twine(OpInfo.ConstraintCode) + "'");
  5849. return;
  5850. }
  5851. // If this is an indirect operand, store through the pointer after the
  5852. // asm.
  5853. if (OpInfo.isIndirect) {
  5854. IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
  5855. OpInfo.CallOperandVal));
  5856. } else {
  5857. // This is the result value of the call.
  5858. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  5859. // Concatenate this output onto the outputs list.
  5860. RetValRegs.append(OpInfo.AssignedRegs);
  5861. }
  5862. // Add information to the INLINEASM node to know that this register is
  5863. // set.
  5864. OpInfo.AssignedRegs
  5865. .AddInlineAsmOperands(OpInfo.isEarlyClobber
  5866. ? InlineAsm::Kind_RegDefEarlyClobber
  5867. : InlineAsm::Kind_RegDef,
  5868. false, 0, DAG, AsmNodeOperands);
  5869. break;
  5870. }
  5871. case InlineAsm::isInput: {
  5872. SDValue InOperandVal = OpInfo.CallOperand;
  5873. if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
  5874. // If this is required to match an output register we have already set,
  5875. // just use its register.
  5876. unsigned OperandNo = OpInfo.getMatchedOperand();
  5877. // Scan until we find the definition we already emitted of this operand.
  5878. // When we find it, create a RegsForValue operand.
  5879. unsigned CurOp = InlineAsm::Op_FirstOperand;
  5880. for (; OperandNo; --OperandNo) {
  5881. // Advance to the next operand.
  5882. unsigned OpFlag =
  5883. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  5884. assert((InlineAsm::isRegDefKind(OpFlag) ||
  5885. InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
  5886. InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
  5887. CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
  5888. }
  5889. unsigned OpFlag =
  5890. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  5891. if (InlineAsm::isRegDefKind(OpFlag) ||
  5892. InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
  5893. // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
  5894. if (OpInfo.isIndirect) {
  5895. // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
  5896. LLVMContext &Ctx = *DAG.getContext();
  5897. Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
  5898. " don't know how to handle tied "
  5899. "indirect register inputs");
  5900. return;
  5901. }
  5902. RegsForValue MatchedRegs;
  5903. MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
  5904. MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
  5905. MatchedRegs.RegVTs.push_back(RegVT);
  5906. MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
  5907. for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
  5908. i != e; ++i) {
  5909. if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT))
  5910. MatchedRegs.Regs.push_back(RegInfo.createVirtualRegister(RC));
  5911. else {
  5912. LLVMContext &Ctx = *DAG.getContext();
  5913. Ctx.emitError(CS.getInstruction(),
  5914. "inline asm error: This value"
  5915. " type register class is not natively supported!");
  5916. return;
  5917. }
  5918. }
  5919. // Use the produced MatchedRegs object to
  5920. MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurSDLoc(),
  5921. Chain, &Flag, CS.getInstruction());
  5922. MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
  5923. true, OpInfo.getMatchedOperand(),
  5924. DAG, AsmNodeOperands);
  5925. break;
  5926. }
  5927. assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
  5928. assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
  5929. "Unexpected number of operands");
  5930. // Add information to the INLINEASM node to know about this input.
  5931. // See InlineAsm.h isUseOperandTiedToDef.
  5932. OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
  5933. OpInfo.getMatchedOperand());
  5934. AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
  5935. TLI.getPointerTy()));
  5936. AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
  5937. break;
  5938. }
  5939. // Treat indirect 'X' constraint as memory.
  5940. if (OpInfo.ConstraintType == TargetLowering::C_Other &&
  5941. OpInfo.isIndirect)
  5942. OpInfo.ConstraintType = TargetLowering::C_Memory;
  5943. if (OpInfo.ConstraintType == TargetLowering::C_Other) {
  5944. std::vector<SDValue> Ops;
  5945. TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
  5946. Ops, DAG);
  5947. if (Ops.empty()) {
  5948. LLVMContext &Ctx = *DAG.getContext();
  5949. Ctx.emitError(CS.getInstruction(),
  5950. "invalid operand for inline asm constraint '" +
  5951. Twine(OpInfo.ConstraintCode) + "'");
  5952. return;
  5953. }
  5954. // Add information to the INLINEASM node to know about this input.
  5955. unsigned ResOpType =
  5956. InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
  5957. AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
  5958. TLI.getPointerTy()));
  5959. AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
  5960. break;
  5961. }
  5962. if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
  5963. assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
  5964. assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
  5965. "Memory operands expect pointer values");
  5966. // Add information to the INLINEASM node to know about this input.
  5967. unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  5968. AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
  5969. TLI.getPointerTy()));
  5970. AsmNodeOperands.push_back(InOperandVal);
  5971. break;
  5972. }
  5973. assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
  5974. OpInfo.ConstraintType == TargetLowering::C_Register) &&
  5975. "Unknown constraint type!");
  5976. // TODO: Support this.
  5977. if (OpInfo.isIndirect) {
  5978. LLVMContext &Ctx = *DAG.getContext();
  5979. Ctx.emitError(CS.getInstruction(),
  5980. "Don't know how to handle indirect register inputs yet "
  5981. "for constraint '" +
  5982. Twine(OpInfo.ConstraintCode) + "'");
  5983. return;
  5984. }
  5985. // Copy the input into the appropriate registers.
  5986. if (OpInfo.AssignedRegs.Regs.empty()) {
  5987. LLVMContext &Ctx = *DAG.getContext();
  5988. Ctx.emitError(CS.getInstruction(),
  5989. "couldn't allocate input reg for constraint '" +
  5990. Twine(OpInfo.ConstraintCode) + "'");
  5991. return;
  5992. }
  5993. OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurSDLoc(),
  5994. Chain, &Flag, CS.getInstruction());
  5995. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
  5996. DAG, AsmNodeOperands);
  5997. break;
  5998. }
  5999. case InlineAsm::isClobber: {
  6000. // Add the clobbered value to the operand list, so that the register
  6001. // allocator is aware that the physreg got clobbered.
  6002. if (!OpInfo.AssignedRegs.Regs.empty())
  6003. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
  6004. false, 0, DAG,
  6005. AsmNodeOperands);
  6006. break;
  6007. }
  6008. }
  6009. }
  6010. // Finish up input operands. Set the input chain and add the flag last.
  6011. AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
  6012. if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
  6013. Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
  6014. DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
  6015. Flag = Chain.getValue(1);
  6016. // If this asm returns a register value, copy the result from that register
  6017. // and set it as the value of the call.
  6018. if (!RetValRegs.Regs.empty()) {
  6019. SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
  6020. Chain, &Flag, CS.getInstruction());
  6021. // FIXME: Why don't we do this for inline asms with MRVs?
  6022. if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
  6023. EVT ResultType = TLI.getValueType(CS.getType());
  6024. // If any of the results of the inline asm is a vector, it may have the
  6025. // wrong width/num elts. This can happen for register classes that can
  6026. // contain multiple different value types. The preg or vreg allocated may
  6027. // not have the same VT as was expected. Convert it to the right type
  6028. // with bit_convert.
  6029. if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
  6030. Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
  6031. ResultType, Val);
  6032. } else if (ResultType != Val.getValueType() &&
  6033. ResultType.isInteger() && Val.getValueType().isInteger()) {
  6034. // If a result value was tied to an input value, the computed result may
  6035. // have a wider width than the expected result. Extract the relevant
  6036. // portion.
  6037. Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
  6038. }
  6039. assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
  6040. }
  6041. setValue(CS.getInstruction(), Val);
  6042. // Don't need to use this as a chain in this case.
  6043. if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
  6044. return;
  6045. }
  6046. std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
  6047. // Process indirect outputs, first output all of the flagged copies out of
  6048. // physregs.
  6049. for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
  6050. RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
  6051. const Value *Ptr = IndirectStoresToEmit[i].second;
  6052. SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
  6053. Chain, &Flag, IA);
  6054. StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
  6055. }
  6056. // Emit the non-flagged stores from the physregs.
  6057. SmallVector<SDValue, 8> OutChains;
  6058. for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
  6059. SDValue Val = DAG.getStore(Chain, getCurSDLoc(),
  6060. StoresToEmit[i].first,
  6061. getValue(StoresToEmit[i].second),
  6062. MachinePointerInfo(StoresToEmit[i].second),
  6063. false, false, 0);
  6064. OutChains.push_back(Val);
  6065. }
  6066. if (!OutChains.empty())
  6067. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
  6068. DAG.setRoot(Chain);
  6069. }
  6070. void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
  6071. DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
  6072. MVT::Other, getRoot(),
  6073. getValue(I.getArgOperand(0)),
  6074. DAG.getSrcValue(I.getArgOperand(0))));
  6075. }
  6076. void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
  6077. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6078. const DataLayout &DL = *TLI.getDataLayout();
  6079. SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurSDLoc(),
  6080. getRoot(), getValue(I.getOperand(0)),
  6081. DAG.getSrcValue(I.getOperand(0)),
  6082. DL.getABITypeAlignment(I.getType()));
  6083. setValue(&I, V);
  6084. DAG.setRoot(V.getValue(1));
  6085. }
  6086. void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
  6087. DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
  6088. MVT::Other, getRoot(),
  6089. getValue(I.getArgOperand(0)),
  6090. DAG.getSrcValue(I.getArgOperand(0))));
  6091. }
  6092. void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
  6093. DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
  6094. MVT::Other, getRoot(),
  6095. getValue(I.getArgOperand(0)),
  6096. getValue(I.getArgOperand(1)),
  6097. DAG.getSrcValue(I.getArgOperand(0)),
  6098. DAG.getSrcValue(I.getArgOperand(1))));
  6099. }
  6100. /// \brief Lower an argument list according to the target calling convention.
  6101. ///
  6102. /// \return A tuple of <return-value, token-chain>
  6103. ///
  6104. /// This is a helper for lowering intrinsics that follow a target calling
  6105. /// convention or require stack pointer adjustment. Only a subset of the
  6106. /// intrinsic's operands need to participate in the calling convention.
  6107. std::pair<SDValue, SDValue>
  6108. SelectionDAGBuilder::lowerCallOperands(ImmutableCallSite CS, unsigned ArgIdx,
  6109. unsigned NumArgs, SDValue Callee,
  6110. bool UseVoidTy,
  6111. MachineBasicBlock *LandingPad) {
  6112. TargetLowering::ArgListTy Args;
  6113. Args.reserve(NumArgs);
  6114. // Populate the argument list.
  6115. // Attributes for args start at offset 1, after the return attribute.
  6116. for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs, AttrI = ArgIdx + 1;
  6117. ArgI != ArgE; ++ArgI) {
  6118. const Value *V = CS->getOperand(ArgI);
  6119. assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
  6120. TargetLowering::ArgListEntry Entry;
  6121. Entry.Node = getValue(V);
  6122. Entry.Ty = V->getType();
  6123. Entry.setAttributes(&CS, AttrI);
  6124. Args.push_back(Entry);
  6125. }
  6126. Type *retTy = UseVoidTy ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
  6127. TargetLowering::CallLoweringInfo CLI(DAG);
  6128. CLI.setDebugLoc(getCurSDLoc()).setChain(getRoot())
  6129. .setCallee(CS.getCallingConv(), retTy, Callee, std::move(Args), NumArgs)
  6130. .setDiscardResult(CS->use_empty());
  6131. return lowerInvokable(CLI, LandingPad);
  6132. }
  6133. /// \brief Add a stack map intrinsic call's live variable operands to a stackmap
  6134. /// or patchpoint target node's operand list.
  6135. ///
  6136. /// Constants are converted to TargetConstants purely as an optimization to
  6137. /// avoid constant materialization and register allocation.
  6138. ///
  6139. /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
  6140. /// generate addess computation nodes, and so ExpandISelPseudo can convert the
  6141. /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
  6142. /// address materialization and register allocation, but may also be required
  6143. /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
  6144. /// alloca in the entry block, then the runtime may assume that the alloca's
  6145. /// StackMap location can be read immediately after compilation and that the
  6146. /// location is valid at any point during execution (this is similar to the
  6147. /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
  6148. /// only available in a register, then the runtime would need to trap when
  6149. /// execution reaches the StackMap in order to read the alloca's location.
  6150. static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
  6151. SmallVectorImpl<SDValue> &Ops,
  6152. SelectionDAGBuilder &Builder) {
  6153. for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
  6154. SDValue OpVal = Builder.getValue(CS.getArgument(i));
  6155. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
  6156. Ops.push_back(
  6157. Builder.DAG.getTargetConstant(StackMaps::ConstantOp, MVT::i64));
  6158. Ops.push_back(
  6159. Builder.DAG.getTargetConstant(C->getSExtValue(), MVT::i64));
  6160. } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
  6161. const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
  6162. Ops.push_back(
  6163. Builder.DAG.getTargetFrameIndex(FI->getIndex(), TLI.getPointerTy()));
  6164. } else
  6165. Ops.push_back(OpVal);
  6166. }
  6167. }
  6168. /// \brief Lower llvm.experimental.stackmap directly to its target opcode.
  6169. void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
  6170. // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
  6171. // [live variables...])
  6172. assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
  6173. SDValue Chain, InFlag, Callee, NullPtr;
  6174. SmallVector<SDValue, 32> Ops;
  6175. SDLoc DL = getCurSDLoc();
  6176. Callee = getValue(CI.getCalledValue());
  6177. NullPtr = DAG.getIntPtrConstant(0, true);
  6178. // The stackmap intrinsic only records the live variables (the arguemnts
  6179. // passed to it) and emits NOPS (if requested). Unlike the patchpoint
  6180. // intrinsic, this won't be lowered to a function call. This means we don't
  6181. // have to worry about calling conventions and target specific lowering code.
  6182. // Instead we perform the call lowering right here.
  6183. //
  6184. // chain, flag = CALLSEQ_START(chain, 0)
  6185. // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
  6186. // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
  6187. //
  6188. Chain = DAG.getCALLSEQ_START(getRoot(), NullPtr, DL);
  6189. InFlag = Chain.getValue(1);
  6190. // Add the <id> and <numBytes> constants.
  6191. SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
  6192. Ops.push_back(DAG.getTargetConstant(
  6193. cast<ConstantSDNode>(IDVal)->getZExtValue(), MVT::i64));
  6194. SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
  6195. Ops.push_back(DAG.getTargetConstant(
  6196. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), MVT::i32));
  6197. // Push live variables for the stack map.
  6198. addStackMapLiveVars(&CI, 2, Ops, *this);
  6199. // We are not pushing any register mask info here on the operands list,
  6200. // because the stackmap doesn't clobber anything.
  6201. // Push the chain and the glue flag.
  6202. Ops.push_back(Chain);
  6203. Ops.push_back(InFlag);
  6204. // Create the STACKMAP node.
  6205. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  6206. SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
  6207. Chain = SDValue(SM, 0);
  6208. InFlag = Chain.getValue(1);
  6209. Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
  6210. // Stackmaps don't generate values, so nothing goes into the NodeMap.
  6211. // Set the root to the target-lowered call chain.
  6212. DAG.setRoot(Chain);
  6213. // Inform the Frame Information that we have a stackmap in this function.
  6214. FuncInfo.MF->getFrameInfo()->setHasStackMap();
  6215. }
  6216. /// \brief Lower llvm.experimental.patchpoint directly to its target opcode.
  6217. void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
  6218. MachineBasicBlock *LandingPad) {
  6219. // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
  6220. // i32 <numBytes>,
  6221. // i8* <target>,
  6222. // i32 <numArgs>,
  6223. // [Args...],
  6224. // [live variables...])
  6225. CallingConv::ID CC = CS.getCallingConv();
  6226. bool IsAnyRegCC = CC == CallingConv::AnyReg;
  6227. bool HasDef = !CS->getType()->isVoidTy();
  6228. SDValue Callee = getValue(CS->getOperand(2)); // <target>
  6229. // Get the real number of arguments participating in the call <numArgs>
  6230. SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
  6231. unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
  6232. // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
  6233. // Intrinsics include all meta-operands up to but not including CC.
  6234. unsigned NumMetaOpers = PatchPointOpers::CCPos;
  6235. assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
  6236. "Not enough arguments provided to the patchpoint intrinsic");
  6237. // For AnyRegCC the arguments are lowered later on manually.
  6238. unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
  6239. std::pair<SDValue, SDValue> Result =
  6240. lowerCallOperands(CS, NumMetaOpers, NumCallArgs, Callee, IsAnyRegCC,
  6241. LandingPad);
  6242. SDNode *CallEnd = Result.second.getNode();
  6243. if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
  6244. CallEnd = CallEnd->getOperand(0).getNode();
  6245. /// Get a call instruction from the call sequence chain.
  6246. /// Tail calls are not allowed.
  6247. assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
  6248. "Expected a callseq node.");
  6249. SDNode *Call = CallEnd->getOperand(0).getNode();
  6250. bool HasGlue = Call->getGluedNode();
  6251. // Replace the target specific call node with the patchable intrinsic.
  6252. SmallVector<SDValue, 8> Ops;
  6253. // Add the <id> and <numBytes> constants.
  6254. SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
  6255. Ops.push_back(DAG.getTargetConstant(
  6256. cast<ConstantSDNode>(IDVal)->getZExtValue(), MVT::i64));
  6257. SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
  6258. Ops.push_back(DAG.getTargetConstant(
  6259. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), MVT::i32));
  6260. // Assume that the Callee is a constant address.
  6261. // FIXME: handle function symbols in the future.
  6262. Ops.push_back(
  6263. DAG.getIntPtrConstant(cast<ConstantSDNode>(Callee)->getZExtValue(),
  6264. /*isTarget=*/true));
  6265. // Adjust <numArgs> to account for any arguments that have been passed on the
  6266. // stack instead.
  6267. // Call Node: Chain, Target, {Args}, RegMask, [Glue]
  6268. unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
  6269. NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
  6270. Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, MVT::i32));
  6271. // Add the calling convention
  6272. Ops.push_back(DAG.getTargetConstant((unsigned)CC, MVT::i32));
  6273. // Add the arguments we omitted previously. The register allocator should
  6274. // place these in any free register.
  6275. if (IsAnyRegCC)
  6276. for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
  6277. Ops.push_back(getValue(CS.getArgument(i)));
  6278. // Push the arguments from the call instruction up to the register mask.
  6279. SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
  6280. for (SDNode::op_iterator i = Call->op_begin()+2; i != e; ++i)
  6281. Ops.push_back(*i);
  6282. // Push live variables for the stack map.
  6283. addStackMapLiveVars(CS, NumMetaOpers + NumArgs, Ops, *this);
  6284. // Push the register mask info.
  6285. if (HasGlue)
  6286. Ops.push_back(*(Call->op_end()-2));
  6287. else
  6288. Ops.push_back(*(Call->op_end()-1));
  6289. // Push the chain (this is originally the first operand of the call, but
  6290. // becomes now the last or second to last operand).
  6291. Ops.push_back(*(Call->op_begin()));
  6292. // Push the glue flag (last operand).
  6293. if (HasGlue)
  6294. Ops.push_back(*(Call->op_end()-1));
  6295. SDVTList NodeTys;
  6296. if (IsAnyRegCC && HasDef) {
  6297. // Create the return types based on the intrinsic definition
  6298. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6299. SmallVector<EVT, 3> ValueVTs;
  6300. ComputeValueVTs(TLI, CS->getType(), ValueVTs);
  6301. assert(ValueVTs.size() == 1 && "Expected only one return value type.");
  6302. // There is always a chain and a glue type at the end
  6303. ValueVTs.push_back(MVT::Other);
  6304. ValueVTs.push_back(MVT::Glue);
  6305. NodeTys = DAG.getVTList(ValueVTs);
  6306. } else
  6307. NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  6308. // Replace the target specific call node with a PATCHPOINT node.
  6309. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
  6310. getCurSDLoc(), NodeTys, Ops);
  6311. // Update the NodeMap.
  6312. if (HasDef) {
  6313. if (IsAnyRegCC)
  6314. setValue(CS.getInstruction(), SDValue(MN, 0));
  6315. else
  6316. setValue(CS.getInstruction(), Result.first);
  6317. }
  6318. // Fixup the consumers of the intrinsic. The chain and glue may be used in the
  6319. // call sequence. Furthermore the location of the chain and glue can change
  6320. // when the AnyReg calling convention is used and the intrinsic returns a
  6321. // value.
  6322. if (IsAnyRegCC && HasDef) {
  6323. SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
  6324. SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
  6325. DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
  6326. } else
  6327. DAG.ReplaceAllUsesWith(Call, MN);
  6328. DAG.DeleteNode(Call);
  6329. // Inform the Frame Information that we have a patchpoint in this function.
  6330. FuncInfo.MF->getFrameInfo()->setHasPatchPoint();
  6331. }
  6332. /// Returns an AttributeSet representing the attributes applied to the return
  6333. /// value of the given call.
  6334. static AttributeSet getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
  6335. SmallVector<Attribute::AttrKind, 2> Attrs;
  6336. if (CLI.RetSExt)
  6337. Attrs.push_back(Attribute::SExt);
  6338. if (CLI.RetZExt)
  6339. Attrs.push_back(Attribute::ZExt);
  6340. if (CLI.IsInReg)
  6341. Attrs.push_back(Attribute::InReg);
  6342. return AttributeSet::get(CLI.RetTy->getContext(), AttributeSet::ReturnIndex,
  6343. Attrs);
  6344. }
  6345. /// TargetLowering::LowerCallTo - This is the default LowerCallTo
  6346. /// implementation, which just calls LowerCall.
  6347. /// FIXME: When all targets are
  6348. /// migrated to using LowerCall, this hook should be integrated into SDISel.
  6349. std::pair<SDValue, SDValue>
  6350. TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
  6351. // Handle the incoming return values from the call.
  6352. CLI.Ins.clear();
  6353. Type *OrigRetTy = CLI.RetTy;
  6354. SmallVector<EVT, 4> RetTys;
  6355. SmallVector<uint64_t, 4> Offsets;
  6356. ComputeValueVTs(*this, CLI.RetTy, RetTys, &Offsets);
  6357. SmallVector<ISD::OutputArg, 4> Outs;
  6358. GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this);
  6359. bool CanLowerReturn =
  6360. this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
  6361. CLI.IsVarArg, Outs, CLI.RetTy->getContext());
  6362. SDValue DemoteStackSlot;
  6363. int DemoteStackIdx = -100;
  6364. if (!CanLowerReturn) {
  6365. // FIXME: equivalent assert?
  6366. // assert(!CS.hasInAllocaArgument() &&
  6367. // "sret demotion is incompatible with inalloca");
  6368. uint64_t TySize = getDataLayout()->getTypeAllocSize(CLI.RetTy);
  6369. unsigned Align = getDataLayout()->getPrefTypeAlignment(CLI.RetTy);
  6370. MachineFunction &MF = CLI.DAG.getMachineFunction();
  6371. DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
  6372. Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy);
  6373. DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getPointerTy());
  6374. ArgListEntry Entry;
  6375. Entry.Node = DemoteStackSlot;
  6376. Entry.Ty = StackSlotPtrType;
  6377. Entry.isSExt = false;
  6378. Entry.isZExt = false;
  6379. Entry.isInReg = false;
  6380. Entry.isSRet = true;
  6381. Entry.isNest = false;
  6382. Entry.isByVal = false;
  6383. Entry.isReturned = false;
  6384. Entry.Alignment = Align;
  6385. CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
  6386. CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
  6387. } else {
  6388. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  6389. EVT VT = RetTys[I];
  6390. MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
  6391. unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
  6392. for (unsigned i = 0; i != NumRegs; ++i) {
  6393. ISD::InputArg MyFlags;
  6394. MyFlags.VT = RegisterVT;
  6395. MyFlags.ArgVT = VT;
  6396. MyFlags.Used = CLI.IsReturnValueUsed;
  6397. if (CLI.RetSExt)
  6398. MyFlags.Flags.setSExt();
  6399. if (CLI.RetZExt)
  6400. MyFlags.Flags.setZExt();
  6401. if (CLI.IsInReg)
  6402. MyFlags.Flags.setInReg();
  6403. CLI.Ins.push_back(MyFlags);
  6404. }
  6405. }
  6406. }
  6407. // Handle all of the outgoing arguments.
  6408. CLI.Outs.clear();
  6409. CLI.OutVals.clear();
  6410. ArgListTy &Args = CLI.getArgs();
  6411. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  6412. SmallVector<EVT, 4> ValueVTs;
  6413. ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
  6414. Type *FinalType = Args[i].Ty;
  6415. if (Args[i].isByVal)
  6416. FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
  6417. bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
  6418. FinalType, CLI.CallConv, CLI.IsVarArg);
  6419. for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
  6420. ++Value) {
  6421. EVT VT = ValueVTs[Value];
  6422. Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
  6423. SDValue Op = SDValue(Args[i].Node.getNode(),
  6424. Args[i].Node.getResNo() + Value);
  6425. ISD::ArgFlagsTy Flags;
  6426. unsigned OriginalAlignment = getDataLayout()->getABITypeAlignment(ArgTy);
  6427. if (Args[i].isZExt)
  6428. Flags.setZExt();
  6429. if (Args[i].isSExt)
  6430. Flags.setSExt();
  6431. if (Args[i].isInReg)
  6432. Flags.setInReg();
  6433. if (Args[i].isSRet)
  6434. Flags.setSRet();
  6435. if (Args[i].isByVal)
  6436. Flags.setByVal();
  6437. if (Args[i].isInAlloca) {
  6438. Flags.setInAlloca();
  6439. // Set the byval flag for CCAssignFn callbacks that don't know about
  6440. // inalloca. This way we can know how many bytes we should've allocated
  6441. // and how many bytes a callee cleanup function will pop. If we port
  6442. // inalloca to more targets, we'll have to add custom inalloca handling
  6443. // in the various CC lowering callbacks.
  6444. Flags.setByVal();
  6445. }
  6446. if (Args[i].isByVal || Args[i].isInAlloca) {
  6447. PointerType *Ty = cast<PointerType>(Args[i].Ty);
  6448. Type *ElementTy = Ty->getElementType();
  6449. Flags.setByValSize(getDataLayout()->getTypeAllocSize(ElementTy));
  6450. // For ByVal, alignment should come from FE. BE will guess if this
  6451. // info is not there but there are cases it cannot get right.
  6452. unsigned FrameAlign;
  6453. if (Args[i].Alignment)
  6454. FrameAlign = Args[i].Alignment;
  6455. else
  6456. FrameAlign = getByValTypeAlignment(ElementTy);
  6457. Flags.setByValAlign(FrameAlign);
  6458. }
  6459. if (Args[i].isNest)
  6460. Flags.setNest();
  6461. if (NeedsRegBlock) {
  6462. Flags.setInConsecutiveRegs();
  6463. if (Value == NumValues - 1)
  6464. Flags.setInConsecutiveRegsLast();
  6465. }
  6466. Flags.setOrigAlign(OriginalAlignment);
  6467. MVT PartVT = getRegisterType(CLI.RetTy->getContext(), VT);
  6468. unsigned NumParts = getNumRegisters(CLI.RetTy->getContext(), VT);
  6469. SmallVector<SDValue, 4> Parts(NumParts);
  6470. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  6471. if (Args[i].isSExt)
  6472. ExtendKind = ISD::SIGN_EXTEND;
  6473. else if (Args[i].isZExt)
  6474. ExtendKind = ISD::ZERO_EXTEND;
  6475. // Conservatively only handle 'returned' on non-vectors for now
  6476. if (Args[i].isReturned && !Op.getValueType().isVector()) {
  6477. assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
  6478. "unexpected use of 'returned'");
  6479. // Before passing 'returned' to the target lowering code, ensure that
  6480. // either the register MVT and the actual EVT are the same size or that
  6481. // the return value and argument are extended in the same way; in these
  6482. // cases it's safe to pass the argument register value unchanged as the
  6483. // return register value (although it's at the target's option whether
  6484. // to do so)
  6485. // TODO: allow code generation to take advantage of partially preserved
  6486. // registers rather than clobbering the entire register when the
  6487. // parameter extension method is not compatible with the return
  6488. // extension method
  6489. if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
  6490. (ExtendKind != ISD::ANY_EXTEND &&
  6491. CLI.RetSExt == Args[i].isSExt && CLI.RetZExt == Args[i].isZExt))
  6492. Flags.setReturned();
  6493. }
  6494. getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
  6495. CLI.CS ? CLI.CS->getInstruction() : nullptr, ExtendKind);
  6496. for (unsigned j = 0; j != NumParts; ++j) {
  6497. // if it isn't first piece, alignment must be 1
  6498. ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
  6499. i < CLI.NumFixedArgs,
  6500. i, j*Parts[j].getValueType().getStoreSize());
  6501. if (NumParts > 1 && j == 0)
  6502. MyFlags.Flags.setSplit();
  6503. else if (j != 0)
  6504. MyFlags.Flags.setOrigAlign(1);
  6505. CLI.Outs.push_back(MyFlags);
  6506. CLI.OutVals.push_back(Parts[j]);
  6507. }
  6508. }
  6509. }
  6510. SmallVector<SDValue, 4> InVals;
  6511. CLI.Chain = LowerCall(CLI, InVals);
  6512. // Verify that the target's LowerCall behaved as expected.
  6513. assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
  6514. "LowerCall didn't return a valid chain!");
  6515. assert((!CLI.IsTailCall || InVals.empty()) &&
  6516. "LowerCall emitted a return value for a tail call!");
  6517. assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
  6518. "LowerCall didn't emit the correct number of values!");
  6519. // For a tail call, the return value is merely live-out and there aren't
  6520. // any nodes in the DAG representing it. Return a special value to
  6521. // indicate that a tail call has been emitted and no more Instructions
  6522. // should be processed in the current block.
  6523. if (CLI.IsTailCall) {
  6524. CLI.DAG.setRoot(CLI.Chain);
  6525. return std::make_pair(SDValue(), SDValue());
  6526. }
  6527. DEBUG(for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
  6528. assert(InVals[i].getNode() &&
  6529. "LowerCall emitted a null value!");
  6530. assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
  6531. "LowerCall emitted a value with the wrong type!");
  6532. });
  6533. SmallVector<SDValue, 4> ReturnValues;
  6534. if (!CanLowerReturn) {
  6535. // The instruction result is the result of loading from the
  6536. // hidden sret parameter.
  6537. SmallVector<EVT, 1> PVTs;
  6538. Type *PtrRetTy = PointerType::getUnqual(OrigRetTy);
  6539. ComputeValueVTs(*this, PtrRetTy, PVTs);
  6540. assert(PVTs.size() == 1 && "Pointers should fit in one register");
  6541. EVT PtrVT = PVTs[0];
  6542. unsigned NumValues = RetTys.size();
  6543. ReturnValues.resize(NumValues);
  6544. SmallVector<SDValue, 4> Chains(NumValues);
  6545. for (unsigned i = 0; i < NumValues; ++i) {
  6546. SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
  6547. CLI.DAG.getConstant(Offsets[i], PtrVT));
  6548. SDValue L = CLI.DAG.getLoad(
  6549. RetTys[i], CLI.DL, CLI.Chain, Add,
  6550. MachinePointerInfo::getFixedStack(DemoteStackIdx, Offsets[i]), false,
  6551. false, false, 1);
  6552. ReturnValues[i] = L;
  6553. Chains[i] = L.getValue(1);
  6554. }
  6555. CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
  6556. } else {
  6557. // Collect the legal value parts into potentially illegal values
  6558. // that correspond to the original function's return values.
  6559. ISD::NodeType AssertOp = ISD::DELETED_NODE;
  6560. if (CLI.RetSExt)
  6561. AssertOp = ISD::AssertSext;
  6562. else if (CLI.RetZExt)
  6563. AssertOp = ISD::AssertZext;
  6564. unsigned CurReg = 0;
  6565. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  6566. EVT VT = RetTys[I];
  6567. MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
  6568. unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
  6569. ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
  6570. NumRegs, RegisterVT, VT, nullptr,
  6571. AssertOp));
  6572. CurReg += NumRegs;
  6573. }
  6574. // For a function returning void, there is no return value. We can't create
  6575. // such a node, so we just return a null return value in that case. In
  6576. // that case, nothing will actually look at the value.
  6577. if (ReturnValues.empty())
  6578. return std::make_pair(SDValue(), CLI.Chain);
  6579. }
  6580. SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
  6581. CLI.DAG.getVTList(RetTys), ReturnValues);
  6582. return std::make_pair(Res, CLI.Chain);
  6583. }
  6584. void TargetLowering::LowerOperationWrapper(SDNode *N,
  6585. SmallVectorImpl<SDValue> &Results,
  6586. SelectionDAG &DAG) const {
  6587. SDValue Res = LowerOperation(SDValue(N, 0), DAG);
  6588. if (Res.getNode())
  6589. Results.push_back(Res);
  6590. }
  6591. SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
  6592. llvm_unreachable("LowerOperation not implemented for this target!");
  6593. }
  6594. void
  6595. SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
  6596. SDValue Op = getNonRegisterValue(V);
  6597. assert((Op.getOpcode() != ISD::CopyFromReg ||
  6598. cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
  6599. "Copy from a reg to the same reg!");
  6600. assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
  6601. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6602. RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
  6603. SDValue Chain = DAG.getEntryNode();
  6604. ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
  6605. FuncInfo.PreferredExtendType.end())
  6606. ? ISD::ANY_EXTEND
  6607. : FuncInfo.PreferredExtendType[V];
  6608. RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
  6609. PendingExports.push_back(Chain);
  6610. }
  6611. #include "llvm/CodeGen/SelectionDAGISel.h"
  6612. /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
  6613. /// entry block, return true. This includes arguments used by switches, since
  6614. /// the switch may expand into multiple basic blocks.
  6615. static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
  6616. // With FastISel active, we may be splitting blocks, so force creation
  6617. // of virtual registers for all non-dead arguments.
  6618. if (FastISel)
  6619. return A->use_empty();
  6620. const BasicBlock *Entry = A->getParent()->begin();
  6621. for (const User *U : A->users())
  6622. if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U))
  6623. return false; // Use not in entry block.
  6624. return true;
  6625. }
  6626. void SelectionDAGISel::LowerArguments(const Function &F) {
  6627. SelectionDAG &DAG = SDB->DAG;
  6628. SDLoc dl = SDB->getCurSDLoc();
  6629. const DataLayout *DL = TLI->getDataLayout();
  6630. SmallVector<ISD::InputArg, 16> Ins;
  6631. if (!FuncInfo->CanLowerReturn) {
  6632. // Put in an sret pointer parameter before all the other parameters.
  6633. SmallVector<EVT, 1> ValueVTs;
  6634. ComputeValueVTs(*TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
  6635. // NOTE: Assuming that a pointer will never break down to more than one VT
  6636. // or one register.
  6637. ISD::ArgFlagsTy Flags;
  6638. Flags.setSRet();
  6639. MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
  6640. ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 0, 0);
  6641. Ins.push_back(RetArg);
  6642. }
  6643. // Set up the incoming argument description vector.
  6644. unsigned Idx = 1;
  6645. for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
  6646. I != E; ++I, ++Idx) {
  6647. SmallVector<EVT, 4> ValueVTs;
  6648. ComputeValueVTs(*TLI, I->getType(), ValueVTs);
  6649. bool isArgValueUsed = !I->use_empty();
  6650. unsigned PartBase = 0;
  6651. Type *FinalType = I->getType();
  6652. if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
  6653. FinalType = cast<PointerType>(FinalType)->getElementType();
  6654. bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
  6655. FinalType, F.getCallingConv(), F.isVarArg());
  6656. for (unsigned Value = 0, NumValues = ValueVTs.size();
  6657. Value != NumValues; ++Value) {
  6658. EVT VT = ValueVTs[Value];
  6659. Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
  6660. ISD::ArgFlagsTy Flags;
  6661. unsigned OriginalAlignment = DL->getABITypeAlignment(ArgTy);
  6662. if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
  6663. Flags.setZExt();
  6664. if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
  6665. Flags.setSExt();
  6666. if (F.getAttributes().hasAttribute(Idx, Attribute::InReg))
  6667. Flags.setInReg();
  6668. if (F.getAttributes().hasAttribute(Idx, Attribute::StructRet))
  6669. Flags.setSRet();
  6670. if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
  6671. Flags.setByVal();
  6672. if (F.getAttributes().hasAttribute(Idx, Attribute::InAlloca)) {
  6673. Flags.setInAlloca();
  6674. // Set the byval flag for CCAssignFn callbacks that don't know about
  6675. // inalloca. This way we can know how many bytes we should've allocated
  6676. // and how many bytes a callee cleanup function will pop. If we port
  6677. // inalloca to more targets, we'll have to add custom inalloca handling
  6678. // in the various CC lowering callbacks.
  6679. Flags.setByVal();
  6680. }
  6681. if (Flags.isByVal() || Flags.isInAlloca()) {
  6682. PointerType *Ty = cast<PointerType>(I->getType());
  6683. Type *ElementTy = Ty->getElementType();
  6684. Flags.setByValSize(DL->getTypeAllocSize(ElementTy));
  6685. // For ByVal, alignment should be passed from FE. BE will guess if
  6686. // this info is not there but there are cases it cannot get right.
  6687. unsigned FrameAlign;
  6688. if (F.getParamAlignment(Idx))
  6689. FrameAlign = F.getParamAlignment(Idx);
  6690. else
  6691. FrameAlign = TLI->getByValTypeAlignment(ElementTy);
  6692. Flags.setByValAlign(FrameAlign);
  6693. }
  6694. if (F.getAttributes().hasAttribute(Idx, Attribute::Nest))
  6695. Flags.setNest();
  6696. if (NeedsRegBlock) {
  6697. Flags.setInConsecutiveRegs();
  6698. if (Value == NumValues - 1)
  6699. Flags.setInConsecutiveRegsLast();
  6700. }
  6701. Flags.setOrigAlign(OriginalAlignment);
  6702. MVT RegisterVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
  6703. unsigned NumRegs = TLI->getNumRegisters(*CurDAG->getContext(), VT);
  6704. for (unsigned i = 0; i != NumRegs; ++i) {
  6705. ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
  6706. Idx-1, PartBase+i*RegisterVT.getStoreSize());
  6707. if (NumRegs > 1 && i == 0)
  6708. MyFlags.Flags.setSplit();
  6709. // if it isn't first piece, alignment must be 1
  6710. else if (i > 0)
  6711. MyFlags.Flags.setOrigAlign(1);
  6712. Ins.push_back(MyFlags);
  6713. }
  6714. PartBase += VT.getStoreSize();
  6715. }
  6716. }
  6717. // Call the target to set up the argument values.
  6718. SmallVector<SDValue, 8> InVals;
  6719. SDValue NewRoot = TLI->LowerFormalArguments(
  6720. DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
  6721. // Verify that the target's LowerFormalArguments behaved as expected.
  6722. assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
  6723. "LowerFormalArguments didn't return a valid chain!");
  6724. assert(InVals.size() == Ins.size() &&
  6725. "LowerFormalArguments didn't emit the correct number of values!");
  6726. DEBUG({
  6727. for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
  6728. assert(InVals[i].getNode() &&
  6729. "LowerFormalArguments emitted a null value!");
  6730. assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
  6731. "LowerFormalArguments emitted a value with the wrong type!");
  6732. }
  6733. });
  6734. // Update the DAG with the new chain value resulting from argument lowering.
  6735. DAG.setRoot(NewRoot);
  6736. // Set up the argument values.
  6737. unsigned i = 0;
  6738. Idx = 1;
  6739. if (!FuncInfo->CanLowerReturn) {
  6740. // Create a virtual register for the sret pointer, and put in a copy
  6741. // from the sret argument into it.
  6742. SmallVector<EVT, 1> ValueVTs;
  6743. ComputeValueVTs(*TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
  6744. MVT VT = ValueVTs[0].getSimpleVT();
  6745. MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
  6746. ISD::NodeType AssertOp = ISD::DELETED_NODE;
  6747. SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
  6748. RegVT, VT, nullptr, AssertOp);
  6749. MachineFunction& MF = SDB->DAG.getMachineFunction();
  6750. MachineRegisterInfo& RegInfo = MF.getRegInfo();
  6751. unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
  6752. FuncInfo->DemoteRegister = SRetReg;
  6753. NewRoot =
  6754. SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
  6755. DAG.setRoot(NewRoot);
  6756. // i indexes lowered arguments. Bump it past the hidden sret argument.
  6757. // Idx indexes LLVM arguments. Don't touch it.
  6758. ++i;
  6759. }
  6760. for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
  6761. ++I, ++Idx) {
  6762. SmallVector<SDValue, 4> ArgValues;
  6763. SmallVector<EVT, 4> ValueVTs;
  6764. ComputeValueVTs(*TLI, I->getType(), ValueVTs);
  6765. unsigned NumValues = ValueVTs.size();
  6766. // If this argument is unused then remember its value. It is used to generate
  6767. // debugging information.
  6768. if (I->use_empty() && NumValues) {
  6769. SDB->setUnusedArgValue(I, InVals[i]);
  6770. // Also remember any frame index for use in FastISel.
  6771. if (FrameIndexSDNode *FI =
  6772. dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
  6773. FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
  6774. }
  6775. for (unsigned Val = 0; Val != NumValues; ++Val) {
  6776. EVT VT = ValueVTs[Val];
  6777. MVT PartVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
  6778. unsigned NumParts = TLI->getNumRegisters(*CurDAG->getContext(), VT);
  6779. if (!I->use_empty()) {
  6780. ISD::NodeType AssertOp = ISD::DELETED_NODE;
  6781. if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
  6782. AssertOp = ISD::AssertSext;
  6783. else if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
  6784. AssertOp = ISD::AssertZext;
  6785. ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
  6786. NumParts, PartVT, VT,
  6787. nullptr, AssertOp));
  6788. }
  6789. i += NumParts;
  6790. }
  6791. // We don't need to do anything else for unused arguments.
  6792. if (ArgValues.empty())
  6793. continue;
  6794. // Note down frame index.
  6795. if (FrameIndexSDNode *FI =
  6796. dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
  6797. FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
  6798. SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
  6799. SDB->getCurSDLoc());
  6800. SDB->setValue(I, Res);
  6801. if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
  6802. if (LoadSDNode *LNode =
  6803. dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
  6804. if (FrameIndexSDNode *FI =
  6805. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  6806. FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
  6807. }
  6808. // If this argument is live outside of the entry block, insert a copy from
  6809. // wherever we got it to the vreg that other BB's will reference it as.
  6810. if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
  6811. // If we can, though, try to skip creating an unnecessary vreg.
  6812. // FIXME: This isn't very clean... it would be nice to make this more
  6813. // general. It's also subtly incompatible with the hacks FastISel
  6814. // uses with vregs.
  6815. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  6816. if (TargetRegisterInfo::isVirtualRegister(Reg)) {
  6817. FuncInfo->ValueMap[I] = Reg;
  6818. continue;
  6819. }
  6820. }
  6821. if (!isOnlyUsedInEntryBlock(I, TM.Options.EnableFastISel)) {
  6822. FuncInfo->InitializeRegForValue(I);
  6823. SDB->CopyToExportRegsIfNeeded(I);
  6824. }
  6825. }
  6826. assert(i == InVals.size() && "Argument register count mismatch!");
  6827. // Finally, if the target has anything special to do, allow it to do so.
  6828. // FIXME: this should insert code into the DAG!
  6829. EmitFunctionEntryCode();
  6830. }
  6831. /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
  6832. /// ensure constants are generated when needed. Remember the virtual registers
  6833. /// that need to be added to the Machine PHI nodes as input. We cannot just
  6834. /// directly add them, because expansion might result in multiple MBB's for one
  6835. /// BB. As such, the start of the BB might correspond to a different MBB than
  6836. /// the end.
  6837. ///
  6838. void
  6839. SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
  6840. const TerminatorInst *TI = LLVMBB->getTerminator();
  6841. SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
  6842. // Check successor nodes' PHI nodes that expect a constant to be available
  6843. // from this block.
  6844. for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
  6845. const BasicBlock *SuccBB = TI->getSuccessor(succ);
  6846. if (!isa<PHINode>(SuccBB->begin())) continue;
  6847. MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
  6848. // If this terminator has multiple identical successors (common for
  6849. // switches), only handle each succ once.
  6850. if (!SuccsHandled.insert(SuccMBB).second)
  6851. continue;
  6852. MachineBasicBlock::iterator MBBI = SuccMBB->begin();
  6853. // At this point we know that there is a 1-1 correspondence between LLVM PHI
  6854. // nodes and Machine PHI nodes, but the incoming operands have not been
  6855. // emitted yet.
  6856. for (BasicBlock::const_iterator I = SuccBB->begin();
  6857. const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
  6858. // Ignore dead phi's.
  6859. if (PN->use_empty()) continue;
  6860. // Skip empty types
  6861. if (PN->getType()->isEmptyTy())
  6862. continue;
  6863. unsigned Reg;
  6864. const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
  6865. if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
  6866. unsigned &RegOut = ConstantsOut[C];
  6867. if (RegOut == 0) {
  6868. RegOut = FuncInfo.CreateRegs(C->getType());
  6869. CopyValueToVirtualRegister(C, RegOut);
  6870. }
  6871. Reg = RegOut;
  6872. } else {
  6873. DenseMap<const Value *, unsigned>::iterator I =
  6874. FuncInfo.ValueMap.find(PHIOp);
  6875. if (I != FuncInfo.ValueMap.end())
  6876. Reg = I->second;
  6877. else {
  6878. assert(isa<AllocaInst>(PHIOp) &&
  6879. FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
  6880. "Didn't codegen value into a register!??");
  6881. Reg = FuncInfo.CreateRegs(PHIOp->getType());
  6882. CopyValueToVirtualRegister(PHIOp, Reg);
  6883. }
  6884. }
  6885. // Remember that this register needs to added to the machine PHI node as
  6886. // the input for this MBB.
  6887. SmallVector<EVT, 4> ValueVTs;
  6888. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6889. ComputeValueVTs(TLI, PN->getType(), ValueVTs);
  6890. for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
  6891. EVT VT = ValueVTs[vti];
  6892. unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
  6893. for (unsigned i = 0, e = NumRegisters; i != e; ++i)
  6894. FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
  6895. Reg += NumRegisters;
  6896. }
  6897. }
  6898. }
  6899. ConstantsOut.clear();
  6900. }
  6901. /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
  6902. /// is 0.
  6903. MachineBasicBlock *
  6904. SelectionDAGBuilder::StackProtectorDescriptor::
  6905. AddSuccessorMBB(const BasicBlock *BB,
  6906. MachineBasicBlock *ParentMBB,
  6907. bool IsLikely,
  6908. MachineBasicBlock *SuccMBB) {
  6909. // If SuccBB has not been created yet, create it.
  6910. if (!SuccMBB) {
  6911. MachineFunction *MF = ParentMBB->getParent();
  6912. MachineFunction::iterator BBI = ParentMBB;
  6913. SuccMBB = MF->CreateMachineBasicBlock(BB);
  6914. MF->insert(++BBI, SuccMBB);
  6915. }
  6916. // Add it as a successor of ParentMBB.
  6917. ParentMBB->addSuccessor(
  6918. SuccMBB, BranchProbabilityInfo::getBranchWeightStackProtector(IsLikely));
  6919. return SuccMBB;
  6920. }