SelectionDAGBuilder.cpp 360 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309
  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/Loads.h"
  23. #include "llvm/Analysis/TargetLibraryInfo.h"
  24. #include "llvm/Analysis/ValueTracking.h"
  25. #include "llvm/Analysis/VectorUtils.h"
  26. #include "llvm/CodeGen/Analysis.h"
  27. #include "llvm/CodeGen/FastISel.h"
  28. #include "llvm/CodeGen/FunctionLoweringInfo.h"
  29. #include "llvm/CodeGen/GCMetadata.h"
  30. #include "llvm/CodeGen/GCStrategy.h"
  31. #include "llvm/CodeGen/MachineFrameInfo.h"
  32. #include "llvm/CodeGen/MachineFunction.h"
  33. #include "llvm/CodeGen/MachineInstrBuilder.h"
  34. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  35. #include "llvm/CodeGen/MachineModuleInfo.h"
  36. #include "llvm/CodeGen/MachineRegisterInfo.h"
  37. #include "llvm/CodeGen/SelectionDAG.h"
  38. #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
  39. #include "llvm/CodeGen/StackMaps.h"
  40. #include "llvm/CodeGen/WinEHFuncInfo.h"
  41. #include "llvm/IR/CallingConv.h"
  42. #include "llvm/IR/Constants.h"
  43. #include "llvm/IR/DataLayout.h"
  44. #include "llvm/IR/DebugInfo.h"
  45. #include "llvm/IR/DerivedTypes.h"
  46. #include "llvm/IR/Function.h"
  47. #include "llvm/IR/GetElementPtrTypeIterator.h"
  48. #include "llvm/IR/GlobalVariable.h"
  49. #include "llvm/IR/InlineAsm.h"
  50. #include "llvm/IR/Instructions.h"
  51. #include "llvm/IR/IntrinsicInst.h"
  52. #include "llvm/IR/Intrinsics.h"
  53. #include "llvm/IR/LLVMContext.h"
  54. #include "llvm/IR/Module.h"
  55. #include "llvm/IR/Statepoint.h"
  56. #include "llvm/MC/MCSymbol.h"
  57. #include "llvm/Support/CommandLine.h"
  58. #include "llvm/Support/Debug.h"
  59. #include "llvm/Support/ErrorHandling.h"
  60. #include "llvm/Support/MathExtras.h"
  61. #include "llvm/Support/raw_ostream.h"
  62. #include "llvm/Target/TargetFrameLowering.h"
  63. #include "llvm/Target/TargetInstrInfo.h"
  64. #include "llvm/Target/TargetIntrinsicInfo.h"
  65. #include "llvm/Target/TargetLowering.h"
  66. #include "llvm/Target/TargetOptions.h"
  67. #include "llvm/Target/TargetSubtargetInfo.h"
  68. #include <algorithm>
  69. #include <utility>
  70. using namespace llvm;
  71. #define DEBUG_TYPE "isel"
  72. /// LimitFloatPrecision - Generate low-precision inline sequences for
  73. /// some float libcalls (6, 8 or 12 bits).
  74. static unsigned LimitFloatPrecision;
  75. static cl::opt<unsigned, true>
  76. LimitFPPrecision("limit-float-precision",
  77. cl::desc("Generate low-precision inline sequences "
  78. "for some float libcalls"),
  79. cl::location(LimitFloatPrecision),
  80. cl::init(0));
  81. static cl::opt<bool>
  82. EnableFMFInDAG("enable-fmf-dag", cl::init(true), cl::Hidden,
  83. cl::desc("Enable fast-math-flags for DAG nodes"));
  84. /// Minimum jump table density for normal functions.
  85. static cl::opt<unsigned>
  86. JumpTableDensity("jump-table-density", cl::init(10), cl::Hidden,
  87. cl::desc("Minimum density for building a jump table in "
  88. "a normal function"));
  89. /// Minimum jump table density for -Os or -Oz functions.
  90. static cl::opt<unsigned>
  91. OptsizeJumpTableDensity("optsize-jump-table-density", cl::init(40), cl::Hidden,
  92. cl::desc("Minimum density for building a jump table in "
  93. "an optsize function"));
  94. // Limit the width of DAG chains. This is important in general to prevent
  95. // DAG-based analysis from blowing up. For example, alias analysis and
  96. // load clustering may not complete in reasonable time. It is difficult to
  97. // recognize and avoid this situation within each individual analysis, and
  98. // future analyses are likely to have the same behavior. Limiting DAG width is
  99. // the safe approach and will be especially important with global DAGs.
  100. //
  101. // MaxParallelChains default is arbitrarily high to avoid affecting
  102. // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
  103. // sequence over this should have been converted to llvm.memcpy by the
  104. // frontend. It is easy to induce this behavior with .ll code such as:
  105. // %buffer = alloca [4096 x i8]
  106. // %data = load [4096 x i8]* %argPtr
  107. // store [4096 x i8] %data, [4096 x i8]* %buffer
  108. static const unsigned MaxParallelChains = 64;
  109. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  110. const SDValue *Parts, unsigned NumParts,
  111. MVT PartVT, EVT ValueVT, const Value *V);
  112. /// getCopyFromParts - Create a value that contains the specified legal parts
  113. /// combined into the value they represent. If the parts combine to a type
  114. /// larger than ValueVT then AssertOp can be used to specify whether the extra
  115. /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
  116. /// (ISD::AssertSext).
  117. static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
  118. const SDValue *Parts, unsigned NumParts,
  119. MVT PartVT, EVT ValueVT, const Value *V,
  120. Optional<ISD::NodeType> AssertOp = None) {
  121. if (ValueVT.isVector())
  122. return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
  123. PartVT, ValueVT, V);
  124. assert(NumParts > 0 && "No parts to assemble!");
  125. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  126. SDValue Val = Parts[0];
  127. if (NumParts > 1) {
  128. // Assemble the value from multiple parts.
  129. if (ValueVT.isInteger()) {
  130. unsigned PartBits = PartVT.getSizeInBits();
  131. unsigned ValueBits = ValueVT.getSizeInBits();
  132. // Assemble the power of 2 part.
  133. unsigned RoundParts = NumParts & (NumParts - 1) ?
  134. 1 << Log2_32(NumParts) : NumParts;
  135. unsigned RoundBits = PartBits * RoundParts;
  136. EVT RoundVT = RoundBits == ValueBits ?
  137. ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
  138. SDValue Lo, Hi;
  139. EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
  140. if (RoundParts > 2) {
  141. Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
  142. PartVT, HalfVT, V);
  143. Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
  144. RoundParts / 2, PartVT, HalfVT, V);
  145. } else {
  146. Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
  147. Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
  148. }
  149. if (DAG.getDataLayout().isBigEndian())
  150. std::swap(Lo, Hi);
  151. Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
  152. if (RoundParts < NumParts) {
  153. // Assemble the trailing non-power-of-2 part.
  154. unsigned OddParts = NumParts - RoundParts;
  155. EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
  156. Hi = getCopyFromParts(DAG, DL,
  157. Parts + RoundParts, OddParts, PartVT, OddVT, V);
  158. // Combine the round and odd parts.
  159. Lo = Val;
  160. if (DAG.getDataLayout().isBigEndian())
  161. std::swap(Lo, Hi);
  162. EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  163. Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
  164. Hi =
  165. DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
  166. DAG.getConstant(Lo.getValueSizeInBits(), DL,
  167. TLI.getPointerTy(DAG.getDataLayout())));
  168. Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
  169. Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
  170. }
  171. } else if (PartVT.isFloatingPoint()) {
  172. // FP split into multiple FP parts (for ppcf128)
  173. assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
  174. "Unexpected split");
  175. SDValue Lo, Hi;
  176. Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
  177. Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
  178. if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
  179. std::swap(Lo, Hi);
  180. Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
  181. } else {
  182. // FP split into integer parts (soft fp)
  183. assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
  184. !PartVT.isVector() && "Unexpected split");
  185. EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  186. Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
  187. }
  188. }
  189. // There is now one part, held in Val. Correct it to match ValueVT.
  190. // PartEVT is the type of the register class that holds the value.
  191. // ValueVT is the type of the inline asm operation.
  192. EVT PartEVT = Val.getValueType();
  193. if (PartEVT == ValueVT)
  194. return Val;
  195. if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
  196. ValueVT.bitsLT(PartEVT)) {
  197. // For an FP value in an integer part, we need to truncate to the right
  198. // width first.
  199. PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  200. Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
  201. }
  202. // Handle types that have the same size.
  203. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
  204. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  205. // Handle types with different sizes.
  206. if (PartEVT.isInteger() && ValueVT.isInteger()) {
  207. if (ValueVT.bitsLT(PartEVT)) {
  208. // For a truncate, see if we have any information to
  209. // indicate whether the truncated bits will always be
  210. // zero or sign-extension.
  211. if (AssertOp.hasValue())
  212. Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
  213. DAG.getValueType(ValueVT));
  214. return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  215. }
  216. return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
  217. }
  218. if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  219. // FP_ROUND's are always exact here.
  220. if (ValueVT.bitsLT(Val.getValueType()))
  221. return DAG.getNode(
  222. ISD::FP_ROUND, DL, ValueVT, Val,
  223. DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
  224. return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
  225. }
  226. llvm_unreachable("Unknown mismatch!");
  227. }
  228. static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
  229. const Twine &ErrMsg) {
  230. const Instruction *I = dyn_cast_or_null<Instruction>(V);
  231. if (!V)
  232. return Ctx.emitError(ErrMsg);
  233. const char *AsmError = ", possible invalid constraint for vector type";
  234. if (const CallInst *CI = dyn_cast<CallInst>(I))
  235. if (isa<InlineAsm>(CI->getCalledValue()))
  236. return Ctx.emitError(I, ErrMsg + AsmError);
  237. return Ctx.emitError(I, ErrMsg);
  238. }
  239. /// getCopyFromPartsVector - Create a value that contains the specified legal
  240. /// parts combined into the value they represent. If the parts combine to a
  241. /// type larger than ValueVT then AssertOp can be used to specify whether the
  242. /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
  243. /// ValueVT (ISD::AssertSext).
  244. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  245. const SDValue *Parts, unsigned NumParts,
  246. MVT PartVT, EVT ValueVT, const Value *V) {
  247. assert(ValueVT.isVector() && "Not a vector value");
  248. assert(NumParts > 0 && "No parts to assemble!");
  249. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  250. SDValue Val = Parts[0];
  251. // Handle a multi-element vector.
  252. if (NumParts > 1) {
  253. EVT IntermediateVT;
  254. MVT RegisterVT;
  255. unsigned NumIntermediates;
  256. unsigned NumRegs =
  257. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  258. NumIntermediates, RegisterVT);
  259. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  260. NumParts = NumRegs; // Silence a compiler warning.
  261. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  262. assert(RegisterVT.getSizeInBits() ==
  263. Parts[0].getSimpleValueType().getSizeInBits() &&
  264. "Part type sizes don't match!");
  265. // Assemble the parts into intermediate operands.
  266. SmallVector<SDValue, 8> Ops(NumIntermediates);
  267. if (NumIntermediates == NumParts) {
  268. // If the register was not expanded, truncate or copy the value,
  269. // as appropriate.
  270. for (unsigned i = 0; i != NumParts; ++i)
  271. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
  272. PartVT, IntermediateVT, V);
  273. } else if (NumParts > 0) {
  274. // If the intermediate type was expanded, build the intermediate
  275. // operands from the parts.
  276. assert(NumParts % NumIntermediates == 0 &&
  277. "Must expand into a divisible number of parts!");
  278. unsigned Factor = NumParts / NumIntermediates;
  279. for (unsigned i = 0; i != NumIntermediates; ++i)
  280. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
  281. PartVT, IntermediateVT, V);
  282. }
  283. // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
  284. // intermediate operands.
  285. Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
  286. : ISD::BUILD_VECTOR,
  287. DL, ValueVT, Ops);
  288. }
  289. // There is now one part, held in Val. Correct it to match ValueVT.
  290. EVT PartEVT = Val.getValueType();
  291. if (PartEVT == ValueVT)
  292. return Val;
  293. if (PartEVT.isVector()) {
  294. // If the element type of the source/dest vectors are the same, but the
  295. // parts vector has more elements than the value vector, then we have a
  296. // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
  297. // elements we want.
  298. if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
  299. assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
  300. "Cannot narrow, it would be a lossy transformation");
  301. return DAG.getNode(
  302. ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
  303. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  304. }
  305. // Vector/Vector bitcast.
  306. if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
  307. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  308. assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
  309. "Cannot handle this kind of promotion");
  310. // Promoted vector extract
  311. return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
  312. }
  313. // Trivial bitcast if the types are the same size and the destination
  314. // vector type is legal.
  315. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
  316. TLI.isTypeLegal(ValueVT))
  317. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  318. // Handle cases such as i8 -> <1 x i1>
  319. if (ValueVT.getVectorNumElements() != 1) {
  320. diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
  321. "non-trivial scalar-to-vector conversion");
  322. return DAG.getUNDEF(ValueVT);
  323. }
  324. if (ValueVT.getVectorNumElements() == 1 &&
  325. ValueVT.getVectorElementType() != PartEVT)
  326. Val = DAG.getAnyExtOrTrunc(Val, DL, ValueVT.getScalarType());
  327. return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
  328. }
  329. static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
  330. SDValue Val, SDValue *Parts, unsigned NumParts,
  331. MVT PartVT, const Value *V);
  332. /// getCopyToParts - Create a series of nodes that contain the specified value
  333. /// split into legal parts. If the parts contain more bits than Val, then, for
  334. /// integers, ExtendKind can be used to specify how to generate the extra bits.
  335. static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
  336. SDValue *Parts, unsigned NumParts, MVT PartVT,
  337. const Value *V,
  338. ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
  339. EVT ValueVT = Val.getValueType();
  340. // Handle the vector case separately.
  341. if (ValueVT.isVector())
  342. return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V);
  343. unsigned PartBits = PartVT.getSizeInBits();
  344. unsigned OrigNumParts = NumParts;
  345. assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
  346. "Copying to an illegal type!");
  347. if (NumParts == 0)
  348. return;
  349. assert(!ValueVT.isVector() && "Vector case handled elsewhere");
  350. EVT PartEVT = PartVT;
  351. if (PartEVT == ValueVT) {
  352. assert(NumParts == 1 && "No-op copy with multiple parts!");
  353. Parts[0] = Val;
  354. return;
  355. }
  356. if (NumParts * PartBits > ValueVT.getSizeInBits()) {
  357. // If the parts cover more bits than the value has, promote the value.
  358. if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  359. assert(NumParts == 1 && "Do not know what to promote to!");
  360. Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
  361. } else {
  362. if (ValueVT.isFloatingPoint()) {
  363. // FP values need to be bitcast, then extended if they are being put
  364. // into a larger container.
  365. ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  366. Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  367. }
  368. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  369. ValueVT.isInteger() &&
  370. "Unknown mismatch!");
  371. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  372. Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
  373. if (PartVT == MVT::x86mmx)
  374. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  375. }
  376. } else if (PartBits == ValueVT.getSizeInBits()) {
  377. // Different types of the same size.
  378. assert(NumParts == 1 && PartEVT != ValueVT);
  379. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  380. } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
  381. // If the parts cover less bits than value has, truncate the value.
  382. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  383. ValueVT.isInteger() &&
  384. "Unknown mismatch!");
  385. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  386. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  387. if (PartVT == MVT::x86mmx)
  388. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  389. }
  390. // The value may have changed - recompute ValueVT.
  391. ValueVT = Val.getValueType();
  392. assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
  393. "Failed to tile the value with PartVT!");
  394. if (NumParts == 1) {
  395. if (PartEVT != ValueVT) {
  396. diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
  397. "scalar-to-vector conversion failed");
  398. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  399. }
  400. Parts[0] = Val;
  401. return;
  402. }
  403. // Expand the value into multiple parts.
  404. if (NumParts & (NumParts - 1)) {
  405. // The number of parts is not a power of 2. Split off and copy the tail.
  406. assert(PartVT.isInteger() && ValueVT.isInteger() &&
  407. "Do not know what to expand to!");
  408. unsigned RoundParts = 1 << Log2_32(NumParts);
  409. unsigned RoundBits = RoundParts * PartBits;
  410. unsigned OddParts = NumParts - RoundParts;
  411. SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
  412. DAG.getIntPtrConstant(RoundBits, DL));
  413. getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
  414. if (DAG.getDataLayout().isBigEndian())
  415. // The odd parts were reversed by getCopyToParts - unreverse them.
  416. std::reverse(Parts + RoundParts, Parts + NumParts);
  417. NumParts = RoundParts;
  418. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  419. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  420. }
  421. // The number of parts is a power of 2. Repeatedly bisect the value using
  422. // EXTRACT_ELEMENT.
  423. Parts[0] = DAG.getNode(ISD::BITCAST, DL,
  424. EVT::getIntegerVT(*DAG.getContext(),
  425. ValueVT.getSizeInBits()),
  426. Val);
  427. for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
  428. for (unsigned i = 0; i < NumParts; i += StepSize) {
  429. unsigned ThisBits = StepSize * PartBits / 2;
  430. EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
  431. SDValue &Part0 = Parts[i];
  432. SDValue &Part1 = Parts[i+StepSize/2];
  433. Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  434. ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
  435. Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  436. ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
  437. if (ThisBits == PartBits && ThisVT != PartVT) {
  438. Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
  439. Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
  440. }
  441. }
  442. }
  443. if (DAG.getDataLayout().isBigEndian())
  444. std::reverse(Parts, Parts + OrigNumParts);
  445. }
  446. /// getCopyToPartsVector - Create a series of nodes that contain the specified
  447. /// value split into legal parts.
  448. static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  449. SDValue Val, SDValue *Parts, unsigned NumParts,
  450. MVT PartVT, const Value *V) {
  451. EVT ValueVT = Val.getValueType();
  452. assert(ValueVT.isVector() && "Not a vector");
  453. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  454. if (NumParts == 1) {
  455. EVT PartEVT = PartVT;
  456. if (PartEVT == ValueVT) {
  457. // Nothing to do.
  458. } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
  459. // Bitconvert vector->vector case.
  460. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  461. } else if (PartVT.isVector() &&
  462. PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
  463. PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
  464. EVT ElementVT = PartVT.getVectorElementType();
  465. // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
  466. // undef elements.
  467. SmallVector<SDValue, 16> Ops;
  468. for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
  469. Ops.push_back(DAG.getNode(
  470. ISD::EXTRACT_VECTOR_ELT, DL, ElementVT, Val,
  471. DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))));
  472. for (unsigned i = ValueVT.getVectorNumElements(),
  473. e = PartVT.getVectorNumElements(); i != e; ++i)
  474. Ops.push_back(DAG.getUNDEF(ElementVT));
  475. Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, Ops);
  476. // FIXME: Use CONCAT for 2x -> 4x.
  477. //SDValue UndefElts = DAG.getUNDEF(VectorTy);
  478. //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
  479. } else if (PartVT.isVector() &&
  480. PartEVT.getVectorElementType().bitsGE(
  481. ValueVT.getVectorElementType()) &&
  482. PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
  483. // Promoted vector extract
  484. Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
  485. } else{
  486. // Vector -> scalar conversion.
  487. assert(ValueVT.getVectorNumElements() == 1 &&
  488. "Only trivial vector-to-scalar conversions should get here!");
  489. Val = DAG.getNode(
  490. ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
  491. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  492. Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
  493. }
  494. Parts[0] = Val;
  495. return;
  496. }
  497. // Handle a multi-element vector.
  498. EVT IntermediateVT;
  499. MVT RegisterVT;
  500. unsigned NumIntermediates;
  501. unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
  502. IntermediateVT,
  503. NumIntermediates, RegisterVT);
  504. unsigned NumElements = ValueVT.getVectorNumElements();
  505. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  506. NumParts = NumRegs; // Silence a compiler warning.
  507. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  508. // Split the vector into intermediate operands.
  509. SmallVector<SDValue, 8> Ops(NumIntermediates);
  510. for (unsigned i = 0; i != NumIntermediates; ++i) {
  511. if (IntermediateVT.isVector())
  512. Ops[i] =
  513. DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
  514. DAG.getConstant(i * (NumElements / NumIntermediates), DL,
  515. TLI.getVectorIdxTy(DAG.getDataLayout())));
  516. else
  517. Ops[i] = DAG.getNode(
  518. ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
  519. DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  520. }
  521. // Split the intermediate operands into legal parts.
  522. if (NumParts == NumIntermediates) {
  523. // If the register was not expanded, promote or copy the value,
  524. // as appropriate.
  525. for (unsigned i = 0; i != NumParts; ++i)
  526. getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
  527. } else if (NumParts > 0) {
  528. // If the intermediate type was expanded, split each the value into
  529. // legal parts.
  530. assert(NumIntermediates != 0 && "division by zero");
  531. assert(NumParts % NumIntermediates == 0 &&
  532. "Must expand into a divisible number of parts!");
  533. unsigned Factor = NumParts / NumIntermediates;
  534. for (unsigned i = 0; i != NumIntermediates; ++i)
  535. getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
  536. }
  537. }
  538. RegsForValue::RegsForValue() {}
  539. RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
  540. EVT valuevt)
  541. : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
  542. RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
  543. const DataLayout &DL, unsigned Reg, Type *Ty) {
  544. ComputeValueVTs(TLI, DL, Ty, ValueVTs);
  545. for (EVT ValueVT : ValueVTs) {
  546. unsigned NumRegs = TLI.getNumRegisters(Context, ValueVT);
  547. MVT RegisterVT = TLI.getRegisterType(Context, ValueVT);
  548. for (unsigned i = 0; i != NumRegs; ++i)
  549. Regs.push_back(Reg + i);
  550. RegVTs.push_back(RegisterVT);
  551. Reg += NumRegs;
  552. }
  553. }
  554. /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
  555. /// this value and returns the result as a ValueVT value. This uses
  556. /// Chain/Flag as the input and updates them for the output Chain/Flag.
  557. /// If the Flag pointer is NULL, no flag is used.
  558. SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
  559. FunctionLoweringInfo &FuncInfo,
  560. const SDLoc &dl, SDValue &Chain,
  561. SDValue *Flag, const Value *V) const {
  562. // A Value with type {} or [0 x %t] needs no registers.
  563. if (ValueVTs.empty())
  564. return SDValue();
  565. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  566. // Assemble the legal parts into the final values.
  567. SmallVector<SDValue, 4> Values(ValueVTs.size());
  568. SmallVector<SDValue, 8> Parts;
  569. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  570. // Copy the legal parts from the registers.
  571. EVT ValueVT = ValueVTs[Value];
  572. unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
  573. MVT RegisterVT = RegVTs[Value];
  574. Parts.resize(NumRegs);
  575. for (unsigned i = 0; i != NumRegs; ++i) {
  576. SDValue P;
  577. if (!Flag) {
  578. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
  579. } else {
  580. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
  581. *Flag = P.getValue(2);
  582. }
  583. Chain = P.getValue(1);
  584. Parts[i] = P;
  585. // If the source register was virtual and if we know something about it,
  586. // add an assert node.
  587. if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
  588. !RegisterVT.isInteger() || RegisterVT.isVector())
  589. continue;
  590. const FunctionLoweringInfo::LiveOutInfo *LOI =
  591. FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
  592. if (!LOI)
  593. continue;
  594. unsigned RegSize = RegisterVT.getSizeInBits();
  595. unsigned NumSignBits = LOI->NumSignBits;
  596. unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
  597. if (NumZeroBits == RegSize) {
  598. // The current value is a zero.
  599. // Explicitly express that as it would be easier for
  600. // optimizations to kick in.
  601. Parts[i] = DAG.getConstant(0, dl, RegisterVT);
  602. continue;
  603. }
  604. // FIXME: We capture more information than the dag can represent. For
  605. // now, just use the tightest assertzext/assertsext possible.
  606. bool isSExt = true;
  607. EVT FromVT(MVT::Other);
  608. if (NumSignBits == RegSize) {
  609. isSExt = true; // ASSERT SEXT 1
  610. FromVT = MVT::i1;
  611. } else if (NumZeroBits >= RegSize - 1) {
  612. isSExt = false; // ASSERT ZEXT 1
  613. FromVT = MVT::i1;
  614. } else if (NumSignBits > RegSize - 8) {
  615. isSExt = true; // ASSERT SEXT 8
  616. FromVT = MVT::i8;
  617. } else if (NumZeroBits >= RegSize - 8) {
  618. isSExt = false; // ASSERT ZEXT 8
  619. FromVT = MVT::i8;
  620. } else if (NumSignBits > RegSize - 16) {
  621. isSExt = true; // ASSERT SEXT 16
  622. FromVT = MVT::i16;
  623. } else if (NumZeroBits >= RegSize - 16) {
  624. isSExt = false; // ASSERT ZEXT 16
  625. FromVT = MVT::i16;
  626. } else if (NumSignBits > RegSize - 32) {
  627. isSExt = true; // ASSERT SEXT 32
  628. FromVT = MVT::i32;
  629. } else if (NumZeroBits >= RegSize - 32) {
  630. isSExt = false; // ASSERT ZEXT 32
  631. FromVT = MVT::i32;
  632. } else {
  633. continue;
  634. }
  635. // Add an assertion node.
  636. assert(FromVT != MVT::Other);
  637. Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
  638. RegisterVT, P, DAG.getValueType(FromVT));
  639. }
  640. Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
  641. NumRegs, RegisterVT, ValueVT, V);
  642. Part += NumRegs;
  643. Parts.clear();
  644. }
  645. return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
  646. }
  647. /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
  648. /// specified value into the registers specified by this object. This uses
  649. /// Chain/Flag as the input and updates them for the output Chain/Flag.
  650. /// If the Flag pointer is NULL, no flag is used.
  651. void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
  652. const SDLoc &dl, SDValue &Chain, SDValue *Flag,
  653. const Value *V,
  654. ISD::NodeType PreferredExtendType) const {
  655. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  656. ISD::NodeType ExtendKind = PreferredExtendType;
  657. // Get the list of the values's legal parts.
  658. unsigned NumRegs = Regs.size();
  659. SmallVector<SDValue, 8> Parts(NumRegs);
  660. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  661. EVT ValueVT = ValueVTs[Value];
  662. unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
  663. MVT RegisterVT = RegVTs[Value];
  664. if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
  665. ExtendKind = ISD::ZERO_EXTEND;
  666. getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
  667. &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
  668. Part += NumParts;
  669. }
  670. // Copy the parts into the registers.
  671. SmallVector<SDValue, 8> Chains(NumRegs);
  672. for (unsigned i = 0; i != NumRegs; ++i) {
  673. SDValue Part;
  674. if (!Flag) {
  675. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
  676. } else {
  677. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
  678. *Flag = Part.getValue(1);
  679. }
  680. Chains[i] = Part.getValue(0);
  681. }
  682. if (NumRegs == 1 || Flag)
  683. // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
  684. // flagged to it. That is the CopyToReg nodes and the user are considered
  685. // a single scheduling unit. If we create a TokenFactor and return it as
  686. // chain, then the TokenFactor is both a predecessor (operand) of the
  687. // user as well as a successor (the TF operands are flagged to the user).
  688. // c1, f1 = CopyToReg
  689. // c2, f2 = CopyToReg
  690. // c3 = TokenFactor c1, c2
  691. // ...
  692. // = op c3, ..., f2
  693. Chain = Chains[NumRegs-1];
  694. else
  695. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  696. }
  697. /// AddInlineAsmOperands - Add this value to the specified inlineasm node
  698. /// operand list. This adds the code marker and includes the number of
  699. /// values added into it.
  700. void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
  701. unsigned MatchingIdx, const SDLoc &dl,
  702. SelectionDAG &DAG,
  703. std::vector<SDValue> &Ops) const {
  704. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  705. unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
  706. if (HasMatching)
  707. Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
  708. else if (!Regs.empty() &&
  709. TargetRegisterInfo::isVirtualRegister(Regs.front())) {
  710. // Put the register class of the virtual registers in the flag word. That
  711. // way, later passes can recompute register class constraints for inline
  712. // assembly as well as normal instructions.
  713. // Don't do this for tied operands that can use the regclass information
  714. // from the def.
  715. const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
  716. const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
  717. Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
  718. }
  719. SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
  720. Ops.push_back(Res);
  721. unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
  722. for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
  723. unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
  724. MVT RegisterVT = RegVTs[Value];
  725. for (unsigned i = 0; i != NumRegs; ++i) {
  726. assert(Reg < Regs.size() && "Mismatch in # registers expected");
  727. unsigned TheReg = Regs[Reg++];
  728. Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
  729. if (TheReg == SP && Code == InlineAsm::Kind_Clobber) {
  730. // If we clobbered the stack pointer, MFI should know about it.
  731. assert(DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment());
  732. }
  733. }
  734. }
  735. }
  736. void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa,
  737. const TargetLibraryInfo *li) {
  738. AA = &aa;
  739. GFI = gfi;
  740. LibInfo = li;
  741. DL = &DAG.getDataLayout();
  742. Context = DAG.getContext();
  743. LPadToCallSiteMap.clear();
  744. }
  745. /// clear - Clear out the current SelectionDAG and the associated
  746. /// state and prepare this SelectionDAGBuilder object to be used
  747. /// for a new block. This doesn't clear out information about
  748. /// additional blocks that are needed to complete switch lowering
  749. /// or PHI node updating; that information is cleared out as it is
  750. /// consumed.
  751. void SelectionDAGBuilder::clear() {
  752. NodeMap.clear();
  753. UnusedArgNodeMap.clear();
  754. PendingLoads.clear();
  755. PendingExports.clear();
  756. CurInst = nullptr;
  757. HasTailCall = false;
  758. SDNodeOrder = LowestSDNodeOrder;
  759. StatepointLowering.clear();
  760. }
  761. /// clearDanglingDebugInfo - Clear the dangling debug information
  762. /// map. This function is separated from the clear so that debug
  763. /// information that is dangling in a basic block can be properly
  764. /// resolved in a different basic block. This allows the
  765. /// SelectionDAG to resolve dangling debug information attached
  766. /// to PHI nodes.
  767. void SelectionDAGBuilder::clearDanglingDebugInfo() {
  768. DanglingDebugInfoMap.clear();
  769. }
  770. /// getRoot - Return the current virtual root of the Selection DAG,
  771. /// flushing any PendingLoad items. This must be done before emitting
  772. /// a store or any other node that may need to be ordered after any
  773. /// prior load instructions.
  774. ///
  775. SDValue SelectionDAGBuilder::getRoot() {
  776. if (PendingLoads.empty())
  777. return DAG.getRoot();
  778. if (PendingLoads.size() == 1) {
  779. SDValue Root = PendingLoads[0];
  780. DAG.setRoot(Root);
  781. PendingLoads.clear();
  782. return Root;
  783. }
  784. // Otherwise, we have to make a token factor node.
  785. SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  786. PendingLoads);
  787. PendingLoads.clear();
  788. DAG.setRoot(Root);
  789. return Root;
  790. }
  791. /// getControlRoot - Similar to getRoot, but instead of flushing all the
  792. /// PendingLoad items, flush all the PendingExports items. It is necessary
  793. /// to do this before emitting a terminator instruction.
  794. ///
  795. SDValue SelectionDAGBuilder::getControlRoot() {
  796. SDValue Root = DAG.getRoot();
  797. if (PendingExports.empty())
  798. return Root;
  799. // Turn all of the CopyToReg chains into one factored node.
  800. if (Root.getOpcode() != ISD::EntryToken) {
  801. unsigned i = 0, e = PendingExports.size();
  802. for (; i != e; ++i) {
  803. assert(PendingExports[i].getNode()->getNumOperands() > 1);
  804. if (PendingExports[i].getNode()->getOperand(0) == Root)
  805. break; // Don't add the root if we already indirectly depend on it.
  806. }
  807. if (i == e)
  808. PendingExports.push_back(Root);
  809. }
  810. Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  811. PendingExports);
  812. PendingExports.clear();
  813. DAG.setRoot(Root);
  814. return Root;
  815. }
  816. void SelectionDAGBuilder::visit(const Instruction &I) {
  817. // Set up outgoing PHI node register values before emitting the terminator.
  818. if (isa<TerminatorInst>(&I)) {
  819. HandlePHINodesInSuccessorBlocks(I.getParent());
  820. }
  821. ++SDNodeOrder;
  822. CurInst = &I;
  823. visit(I.getOpcode(), I);
  824. if (!isa<TerminatorInst>(&I) && !HasTailCall &&
  825. !isStatepoint(&I)) // statepoints handle their exports internally
  826. CopyToExportRegsIfNeeded(&I);
  827. CurInst = nullptr;
  828. }
  829. void SelectionDAGBuilder::visitPHI(const PHINode &) {
  830. llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
  831. }
  832. void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
  833. // Note: this doesn't use InstVisitor, because it has to work with
  834. // ConstantExpr's in addition to instructions.
  835. switch (Opcode) {
  836. default: llvm_unreachable("Unknown instruction type encountered!");
  837. // Build the switch statement using the Instruction.def file.
  838. #define HANDLE_INST(NUM, OPCODE, CLASS) \
  839. case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
  840. #include "llvm/IR/Instruction.def"
  841. }
  842. }
  843. // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
  844. // generate the debug data structures now that we've seen its definition.
  845. void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
  846. SDValue Val) {
  847. DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
  848. if (DDI.getDI()) {
  849. const DbgValueInst *DI = DDI.getDI();
  850. DebugLoc dl = DDI.getdl();
  851. unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
  852. DILocalVariable *Variable = DI->getVariable();
  853. DIExpression *Expr = DI->getExpression();
  854. assert(Variable->isValidLocationForIntrinsic(dl) &&
  855. "Expected inlined-at fields to agree");
  856. uint64_t Offset = DI->getOffset();
  857. SDDbgValue *SDV;
  858. if (Val.getNode()) {
  859. if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, Offset, false,
  860. Val)) {
  861. SDV = getDbgValue(Val, Variable, Expr, Offset, dl, DbgSDNodeOrder);
  862. DAG.AddDbgValue(SDV, Val.getNode(), false);
  863. }
  864. } else
  865. DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
  866. DanglingDebugInfoMap[V] = DanglingDebugInfo();
  867. }
  868. }
  869. /// getCopyFromRegs - If there was virtual register allocated for the value V
  870. /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
  871. SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
  872. DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
  873. SDValue Result;
  874. if (It != FuncInfo.ValueMap.end()) {
  875. unsigned InReg = It->second;
  876. RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
  877. DAG.getDataLayout(), InReg, Ty);
  878. SDValue Chain = DAG.getEntryNode();
  879. Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
  880. resolveDanglingDebugInfo(V, Result);
  881. }
  882. return Result;
  883. }
  884. /// getValue - Return an SDValue for the given Value.
  885. SDValue SelectionDAGBuilder::getValue(const Value *V) {
  886. // If we already have an SDValue for this value, use it. It's important
  887. // to do this first, so that we don't create a CopyFromReg if we already
  888. // have a regular SDValue.
  889. SDValue &N = NodeMap[V];
  890. if (N.getNode()) return N;
  891. // If there's a virtual register allocated and initialized for this
  892. // value, use it.
  893. if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
  894. return copyFromReg;
  895. // Otherwise create a new SDValue and remember it.
  896. SDValue Val = getValueImpl(V);
  897. NodeMap[V] = Val;
  898. resolveDanglingDebugInfo(V, Val);
  899. return Val;
  900. }
  901. // Return true if SDValue exists for the given Value
  902. bool SelectionDAGBuilder::findValue(const Value *V) const {
  903. return (NodeMap.find(V) != NodeMap.end()) ||
  904. (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
  905. }
  906. /// getNonRegisterValue - Return an SDValue for the given Value, but
  907. /// don't look in FuncInfo.ValueMap for a virtual register.
  908. SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
  909. // If we already have an SDValue for this value, use it.
  910. SDValue &N = NodeMap[V];
  911. if (N.getNode()) {
  912. if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
  913. // Remove the debug location from the node as the node is about to be used
  914. // in a location which may differ from the original debug location. This
  915. // is relevant to Constant and ConstantFP nodes because they can appear
  916. // as constant expressions inside PHI nodes.
  917. N->setDebugLoc(DebugLoc());
  918. }
  919. return N;
  920. }
  921. // Otherwise create a new SDValue and remember it.
  922. SDValue Val = getValueImpl(V);
  923. NodeMap[V] = Val;
  924. resolveDanglingDebugInfo(V, Val);
  925. return Val;
  926. }
  927. /// getValueImpl - Helper function for getValue and getNonRegisterValue.
  928. /// Create an SDValue for the given value.
  929. SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
  930. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  931. if (const Constant *C = dyn_cast<Constant>(V)) {
  932. EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
  933. if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
  934. return DAG.getConstant(*CI, getCurSDLoc(), VT);
  935. if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
  936. return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
  937. if (isa<ConstantPointerNull>(C)) {
  938. unsigned AS = V->getType()->getPointerAddressSpace();
  939. return DAG.getConstant(0, getCurSDLoc(),
  940. TLI.getPointerTy(DAG.getDataLayout(), AS));
  941. }
  942. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
  943. return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
  944. if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
  945. return DAG.getUNDEF(VT);
  946. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  947. visit(CE->getOpcode(), *CE);
  948. SDValue N1 = NodeMap[V];
  949. assert(N1.getNode() && "visit didn't populate the NodeMap!");
  950. return N1;
  951. }
  952. if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
  953. SmallVector<SDValue, 4> Constants;
  954. for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
  955. OI != OE; ++OI) {
  956. SDNode *Val = getValue(*OI).getNode();
  957. // If the operand is an empty aggregate, there are no values.
  958. if (!Val) continue;
  959. // Add each leaf value from the operand to the Constants list
  960. // to form a flattened list of all the values.
  961. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  962. Constants.push_back(SDValue(Val, i));
  963. }
  964. return DAG.getMergeValues(Constants, getCurSDLoc());
  965. }
  966. if (const ConstantDataSequential *CDS =
  967. dyn_cast<ConstantDataSequential>(C)) {
  968. SmallVector<SDValue, 4> Ops;
  969. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  970. SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
  971. // Add each leaf value from the operand to the Constants list
  972. // to form a flattened list of all the values.
  973. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  974. Ops.push_back(SDValue(Val, i));
  975. }
  976. if (isa<ArrayType>(CDS->getType()))
  977. return DAG.getMergeValues(Ops, getCurSDLoc());
  978. return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
  979. VT, Ops);
  980. }
  981. if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
  982. assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
  983. "Unknown struct or array constant!");
  984. SmallVector<EVT, 4> ValueVTs;
  985. ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
  986. unsigned NumElts = ValueVTs.size();
  987. if (NumElts == 0)
  988. return SDValue(); // empty struct
  989. SmallVector<SDValue, 4> Constants(NumElts);
  990. for (unsigned i = 0; i != NumElts; ++i) {
  991. EVT EltVT = ValueVTs[i];
  992. if (isa<UndefValue>(C))
  993. Constants[i] = DAG.getUNDEF(EltVT);
  994. else if (EltVT.isFloatingPoint())
  995. Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  996. else
  997. Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
  998. }
  999. return DAG.getMergeValues(Constants, getCurSDLoc());
  1000. }
  1001. if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
  1002. return DAG.getBlockAddress(BA, VT);
  1003. VectorType *VecTy = cast<VectorType>(V->getType());
  1004. unsigned NumElements = VecTy->getNumElements();
  1005. // Now that we know the number and type of the elements, get that number of
  1006. // elements into the Ops array based on what kind of constant it is.
  1007. SmallVector<SDValue, 16> Ops;
  1008. if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
  1009. for (unsigned i = 0; i != NumElements; ++i)
  1010. Ops.push_back(getValue(CV->getOperand(i)));
  1011. } else {
  1012. assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
  1013. EVT EltVT =
  1014. TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
  1015. SDValue Op;
  1016. if (EltVT.isFloatingPoint())
  1017. Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  1018. else
  1019. Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
  1020. Ops.assign(NumElements, Op);
  1021. }
  1022. // Create a BUILD_VECTOR node.
  1023. return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops);
  1024. }
  1025. // If this is a static alloca, generate it as the frameindex instead of
  1026. // computation.
  1027. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  1028. DenseMap<const AllocaInst*, int>::iterator SI =
  1029. FuncInfo.StaticAllocaMap.find(AI);
  1030. if (SI != FuncInfo.StaticAllocaMap.end())
  1031. return DAG.getFrameIndex(SI->second,
  1032. TLI.getPointerTy(DAG.getDataLayout()));
  1033. }
  1034. // If this is an instruction which fast-isel has deferred, select it now.
  1035. if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
  1036. unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
  1037. RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
  1038. Inst->getType());
  1039. SDValue Chain = DAG.getEntryNode();
  1040. return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
  1041. }
  1042. llvm_unreachable("Can't get register for value!");
  1043. }
  1044. void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
  1045. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1046. bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
  1047. bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
  1048. MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
  1049. // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
  1050. if (IsMSVCCXX || IsCoreCLR)
  1051. CatchPadMBB->setIsEHFuncletEntry();
  1052. DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, getControlRoot()));
  1053. }
  1054. void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
  1055. // Update machine-CFG edge.
  1056. MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
  1057. FuncInfo.MBB->addSuccessor(TargetMBB);
  1058. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1059. bool IsSEH = isAsynchronousEHPersonality(Pers);
  1060. if (IsSEH) {
  1061. // If this is not a fall-through branch or optimizations are switched off,
  1062. // emit the branch.
  1063. if (TargetMBB != NextBlock(FuncInfo.MBB) ||
  1064. TM.getOptLevel() == CodeGenOpt::None)
  1065. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  1066. getControlRoot(), DAG.getBasicBlock(TargetMBB)));
  1067. return;
  1068. }
  1069. // Figure out the funclet membership for the catchret's successor.
  1070. // This will be used by the FuncletLayout pass to determine how to order the
  1071. // BB's.
  1072. // A 'catchret' returns to the outer scope's color.
  1073. Value *ParentPad = I.getCatchSwitchParentPad();
  1074. const BasicBlock *SuccessorColor;
  1075. if (isa<ConstantTokenNone>(ParentPad))
  1076. SuccessorColor = &FuncInfo.Fn->getEntryBlock();
  1077. else
  1078. SuccessorColor = cast<Instruction>(ParentPad)->getParent();
  1079. assert(SuccessorColor && "No parent funclet for catchret!");
  1080. MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
  1081. assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
  1082. // Create the terminator node.
  1083. SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
  1084. getControlRoot(), DAG.getBasicBlock(TargetMBB),
  1085. DAG.getBasicBlock(SuccessorColorMBB));
  1086. DAG.setRoot(Ret);
  1087. }
  1088. void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
  1089. // Don't emit any special code for the cleanuppad instruction. It just marks
  1090. // the start of a funclet.
  1091. FuncInfo.MBB->setIsEHFuncletEntry();
  1092. FuncInfo.MBB->setIsCleanupFuncletEntry();
  1093. }
  1094. /// When an invoke or a cleanupret unwinds to the next EH pad, there are
  1095. /// many places it could ultimately go. In the IR, we have a single unwind
  1096. /// destination, but in the machine CFG, we enumerate all the possible blocks.
  1097. /// This function skips over imaginary basic blocks that hold catchswitch
  1098. /// instructions, and finds all the "real" machine
  1099. /// basic block destinations. As those destinations may not be successors of
  1100. /// EHPadBB, here we also calculate the edge probability to those destinations.
  1101. /// The passed-in Prob is the edge probability to EHPadBB.
  1102. static void findUnwindDestinations(
  1103. FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
  1104. BranchProbability Prob,
  1105. SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
  1106. &UnwindDests) {
  1107. EHPersonality Personality =
  1108. classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1109. bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
  1110. bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
  1111. while (EHPadBB) {
  1112. const Instruction *Pad = EHPadBB->getFirstNonPHI();
  1113. BasicBlock *NewEHPadBB = nullptr;
  1114. if (isa<LandingPadInst>(Pad)) {
  1115. // Stop on landingpads. They are not funclets.
  1116. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1117. break;
  1118. } else if (isa<CleanupPadInst>(Pad)) {
  1119. // Stop on cleanup pads. Cleanups are always funclet entries for all known
  1120. // personalities.
  1121. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1122. UnwindDests.back().first->setIsEHFuncletEntry();
  1123. break;
  1124. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
  1125. // Add the catchpad handlers to the possible destinations.
  1126. for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
  1127. UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
  1128. // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
  1129. if (IsMSVCCXX || IsCoreCLR)
  1130. UnwindDests.back().first->setIsEHFuncletEntry();
  1131. }
  1132. NewEHPadBB = CatchSwitch->getUnwindDest();
  1133. } else {
  1134. continue;
  1135. }
  1136. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1137. if (BPI && NewEHPadBB)
  1138. Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
  1139. EHPadBB = NewEHPadBB;
  1140. }
  1141. }
  1142. void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
  1143. // Update successor info.
  1144. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  1145. auto UnwindDest = I.getUnwindDest();
  1146. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1147. BranchProbability UnwindDestProb =
  1148. (BPI && UnwindDest)
  1149. ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
  1150. : BranchProbability::getZero();
  1151. findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
  1152. for (auto &UnwindDest : UnwindDests) {
  1153. UnwindDest.first->setIsEHPad();
  1154. addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
  1155. }
  1156. FuncInfo.MBB->normalizeSuccProbs();
  1157. // Create the terminator node.
  1158. SDValue Ret =
  1159. DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
  1160. DAG.setRoot(Ret);
  1161. }
  1162. void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
  1163. report_fatal_error("visitCatchSwitch not yet implemented!");
  1164. }
  1165. void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
  1166. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1167. auto &DL = DAG.getDataLayout();
  1168. SDValue Chain = getControlRoot();
  1169. SmallVector<ISD::OutputArg, 8> Outs;
  1170. SmallVector<SDValue, 8> OutVals;
  1171. // Calls to @llvm.experimental.deoptimize don't generate a return value, so
  1172. // lower
  1173. //
  1174. // %val = call <ty> @llvm.experimental.deoptimize()
  1175. // ret <ty> %val
  1176. //
  1177. // differently.
  1178. if (I.getParent()->getTerminatingDeoptimizeCall()) {
  1179. LowerDeoptimizingReturn();
  1180. return;
  1181. }
  1182. if (!FuncInfo.CanLowerReturn) {
  1183. unsigned DemoteReg = FuncInfo.DemoteRegister;
  1184. const Function *F = I.getParent()->getParent();
  1185. // Emit a store of the return value through the virtual register.
  1186. // Leave Outs empty so that LowerReturn won't try to load return
  1187. // registers the usual way.
  1188. SmallVector<EVT, 1> PtrValueVTs;
  1189. ComputeValueVTs(TLI, DL, PointerType::getUnqual(F->getReturnType()),
  1190. PtrValueVTs);
  1191. SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
  1192. DemoteReg, PtrValueVTs[0]);
  1193. SDValue RetOp = getValue(I.getOperand(0));
  1194. SmallVector<EVT, 4> ValueVTs;
  1195. SmallVector<uint64_t, 4> Offsets;
  1196. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets);
  1197. unsigned NumValues = ValueVTs.size();
  1198. // An aggregate return value cannot wrap around the address space, so
  1199. // offsets to its parts don't wrap either.
  1200. SDNodeFlags Flags;
  1201. Flags.setNoUnsignedWrap(true);
  1202. SmallVector<SDValue, 4> Chains(NumValues);
  1203. for (unsigned i = 0; i != NumValues; ++i) {
  1204. SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(),
  1205. RetPtr.getValueType(), RetPtr,
  1206. DAG.getIntPtrConstant(Offsets[i],
  1207. getCurSDLoc()),
  1208. &Flags);
  1209. Chains[i] = DAG.getStore(Chain, getCurSDLoc(),
  1210. SDValue(RetOp.getNode(), RetOp.getResNo() + i),
  1211. // FIXME: better loc info would be nice.
  1212. Add, MachinePointerInfo());
  1213. }
  1214. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
  1215. MVT::Other, Chains);
  1216. } else if (I.getNumOperands() != 0) {
  1217. SmallVector<EVT, 4> ValueVTs;
  1218. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
  1219. unsigned NumValues = ValueVTs.size();
  1220. if (NumValues) {
  1221. SDValue RetOp = getValue(I.getOperand(0));
  1222. const Function *F = I.getParent()->getParent();
  1223. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  1224. if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
  1225. Attribute::SExt))
  1226. ExtendKind = ISD::SIGN_EXTEND;
  1227. else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
  1228. Attribute::ZExt))
  1229. ExtendKind = ISD::ZERO_EXTEND;
  1230. LLVMContext &Context = F->getContext();
  1231. bool RetInReg = F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
  1232. Attribute::InReg);
  1233. for (unsigned j = 0; j != NumValues; ++j) {
  1234. EVT VT = ValueVTs[j];
  1235. if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
  1236. VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
  1237. unsigned NumParts = TLI.getNumRegisters(Context, VT);
  1238. MVT PartVT = TLI.getRegisterType(Context, VT);
  1239. SmallVector<SDValue, 4> Parts(NumParts);
  1240. getCopyToParts(DAG, getCurSDLoc(),
  1241. SDValue(RetOp.getNode(), RetOp.getResNo() + j),
  1242. &Parts[0], NumParts, PartVT, &I, ExtendKind);
  1243. // 'inreg' on function refers to return value
  1244. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1245. if (RetInReg)
  1246. Flags.setInReg();
  1247. // Propagate extension type if any
  1248. if (ExtendKind == ISD::SIGN_EXTEND)
  1249. Flags.setSExt();
  1250. else if (ExtendKind == ISD::ZERO_EXTEND)
  1251. Flags.setZExt();
  1252. for (unsigned i = 0; i < NumParts; ++i) {
  1253. Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
  1254. VT, /*isfixed=*/true, 0, 0));
  1255. OutVals.push_back(Parts[i]);
  1256. }
  1257. }
  1258. }
  1259. }
  1260. // Push in swifterror virtual register as the last element of Outs. This makes
  1261. // sure swifterror virtual register will be returned in the swifterror
  1262. // physical register.
  1263. const Function *F = I.getParent()->getParent();
  1264. if (TLI.supportSwiftError() &&
  1265. F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
  1266. assert(FuncInfo.SwiftErrorArg && "Need a swift error argument");
  1267. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1268. Flags.setSwiftError();
  1269. Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
  1270. EVT(TLI.getPointerTy(DL)) /*argvt*/,
  1271. true /*isfixed*/, 1 /*origidx*/,
  1272. 0 /*partOffs*/));
  1273. // Create SDNode for the swifterror virtual register.
  1274. OutVals.push_back(DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVReg(
  1275. FuncInfo.MBB, FuncInfo.SwiftErrorArg),
  1276. EVT(TLI.getPointerTy(DL))));
  1277. }
  1278. bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
  1279. CallingConv::ID CallConv =
  1280. DAG.getMachineFunction().getFunction()->getCallingConv();
  1281. Chain = DAG.getTargetLoweringInfo().LowerReturn(
  1282. Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
  1283. // Verify that the target's LowerReturn behaved as expected.
  1284. assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
  1285. "LowerReturn didn't return a valid chain!");
  1286. // Update the DAG with the new chain value resulting from return lowering.
  1287. DAG.setRoot(Chain);
  1288. }
  1289. /// CopyToExportRegsIfNeeded - If the given value has virtual registers
  1290. /// created for it, emit nodes to copy the value into the virtual
  1291. /// registers.
  1292. void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
  1293. // Skip empty types
  1294. if (V->getType()->isEmptyTy())
  1295. return;
  1296. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  1297. if (VMI != FuncInfo.ValueMap.end()) {
  1298. assert(!V->use_empty() && "Unused value assigned virtual registers!");
  1299. CopyValueToVirtualRegister(V, VMI->second);
  1300. }
  1301. }
  1302. /// ExportFromCurrentBlock - If this condition isn't known to be exported from
  1303. /// the current basic block, add it to ValueMap now so that we'll get a
  1304. /// CopyTo/FromReg.
  1305. void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
  1306. // No need to export constants.
  1307. if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
  1308. // Already exported?
  1309. if (FuncInfo.isExportedInst(V)) return;
  1310. unsigned Reg = FuncInfo.InitializeRegForValue(V);
  1311. CopyValueToVirtualRegister(V, Reg);
  1312. }
  1313. bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
  1314. const BasicBlock *FromBB) {
  1315. // The operands of the setcc have to be in this block. We don't know
  1316. // how to export them from some other block.
  1317. if (const Instruction *VI = dyn_cast<Instruction>(V)) {
  1318. // Can export from current BB.
  1319. if (VI->getParent() == FromBB)
  1320. return true;
  1321. // Is already exported, noop.
  1322. return FuncInfo.isExportedInst(V);
  1323. }
  1324. // If this is an argument, we can export it if the BB is the entry block or
  1325. // if it is already exported.
  1326. if (isa<Argument>(V)) {
  1327. if (FromBB == &FromBB->getParent()->getEntryBlock())
  1328. return true;
  1329. // Otherwise, can only export this if it is already exported.
  1330. return FuncInfo.isExportedInst(V);
  1331. }
  1332. // Otherwise, constants can always be exported.
  1333. return true;
  1334. }
  1335. /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
  1336. BranchProbability
  1337. SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
  1338. const MachineBasicBlock *Dst) const {
  1339. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1340. const BasicBlock *SrcBB = Src->getBasicBlock();
  1341. const BasicBlock *DstBB = Dst->getBasicBlock();
  1342. if (!BPI) {
  1343. // If BPI is not available, set the default probability as 1 / N, where N is
  1344. // the number of successors.
  1345. auto SuccSize = std::max<uint32_t>(
  1346. std::distance(succ_begin(SrcBB), succ_end(SrcBB)), 1);
  1347. return BranchProbability(1, SuccSize);
  1348. }
  1349. return BPI->getEdgeProbability(SrcBB, DstBB);
  1350. }
  1351. void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
  1352. MachineBasicBlock *Dst,
  1353. BranchProbability Prob) {
  1354. if (!FuncInfo.BPI)
  1355. Src->addSuccessorWithoutProb(Dst);
  1356. else {
  1357. if (Prob.isUnknown())
  1358. Prob = getEdgeProbability(Src, Dst);
  1359. Src->addSuccessor(Dst, Prob);
  1360. }
  1361. }
  1362. static bool InBlock(const Value *V, const BasicBlock *BB) {
  1363. if (const Instruction *I = dyn_cast<Instruction>(V))
  1364. return I->getParent() == BB;
  1365. return true;
  1366. }
  1367. /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
  1368. /// This function emits a branch and is used at the leaves of an OR or an
  1369. /// AND operator tree.
  1370. ///
  1371. void
  1372. SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
  1373. MachineBasicBlock *TBB,
  1374. MachineBasicBlock *FBB,
  1375. MachineBasicBlock *CurBB,
  1376. MachineBasicBlock *SwitchBB,
  1377. BranchProbability TProb,
  1378. BranchProbability FProb) {
  1379. const BasicBlock *BB = CurBB->getBasicBlock();
  1380. // If the leaf of the tree is a comparison, merge the condition into
  1381. // the caseblock.
  1382. if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
  1383. // The operands of the cmp have to be in this block. We don't know
  1384. // how to export them from some other block. If this is the first block
  1385. // of the sequence, no exporting is needed.
  1386. if (CurBB == SwitchBB ||
  1387. (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
  1388. isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
  1389. ISD::CondCode Condition;
  1390. if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
  1391. Condition = getICmpCondCode(IC->getPredicate());
  1392. } else {
  1393. const FCmpInst *FC = cast<FCmpInst>(Cond);
  1394. Condition = getFCmpCondCode(FC->getPredicate());
  1395. if (TM.Options.NoNaNsFPMath)
  1396. Condition = getFCmpCodeWithoutNaN(Condition);
  1397. }
  1398. CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
  1399. TBB, FBB, CurBB, TProb, FProb);
  1400. SwitchCases.push_back(CB);
  1401. return;
  1402. }
  1403. }
  1404. // Create a CaseBlock record representing this branch.
  1405. CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
  1406. nullptr, TBB, FBB, CurBB, TProb, FProb);
  1407. SwitchCases.push_back(CB);
  1408. }
  1409. /// FindMergedConditions - If Cond is an expression like
  1410. void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
  1411. MachineBasicBlock *TBB,
  1412. MachineBasicBlock *FBB,
  1413. MachineBasicBlock *CurBB,
  1414. MachineBasicBlock *SwitchBB,
  1415. Instruction::BinaryOps Opc,
  1416. BranchProbability TProb,
  1417. BranchProbability FProb) {
  1418. // If this node is not part of the or/and tree, emit it as a branch.
  1419. const Instruction *BOp = dyn_cast<Instruction>(Cond);
  1420. if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
  1421. (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
  1422. BOp->getParent() != CurBB->getBasicBlock() ||
  1423. !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
  1424. !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
  1425. EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
  1426. TProb, FProb);
  1427. return;
  1428. }
  1429. // Create TmpBB after CurBB.
  1430. MachineFunction::iterator BBI(CurBB);
  1431. MachineFunction &MF = DAG.getMachineFunction();
  1432. MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
  1433. CurBB->getParent()->insert(++BBI, TmpBB);
  1434. if (Opc == Instruction::Or) {
  1435. // Codegen X | Y as:
  1436. // BB1:
  1437. // jmp_if_X TBB
  1438. // jmp TmpBB
  1439. // TmpBB:
  1440. // jmp_if_Y TBB
  1441. // jmp FBB
  1442. //
  1443. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1444. // The requirement is that
  1445. // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
  1446. // = TrueProb for original BB.
  1447. // Assuming the original probabilities are A and B, one choice is to set
  1448. // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
  1449. // A/(1+B) and 2B/(1+B). This choice assumes that
  1450. // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
  1451. // Another choice is to assume TrueProb for BB1 equals to TrueProb for
  1452. // TmpBB, but the math is more complicated.
  1453. auto NewTrueProb = TProb / 2;
  1454. auto NewFalseProb = TProb / 2 + FProb;
  1455. // Emit the LHS condition.
  1456. FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
  1457. NewTrueProb, NewFalseProb);
  1458. // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
  1459. SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
  1460. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  1461. // Emit the RHS condition into TmpBB.
  1462. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
  1463. Probs[0], Probs[1]);
  1464. } else {
  1465. assert(Opc == Instruction::And && "Unknown merge op!");
  1466. // Codegen X & Y as:
  1467. // BB1:
  1468. // jmp_if_X TmpBB
  1469. // jmp FBB
  1470. // TmpBB:
  1471. // jmp_if_Y TBB
  1472. // jmp FBB
  1473. //
  1474. // This requires creation of TmpBB after CurBB.
  1475. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1476. // The requirement is that
  1477. // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
  1478. // = FalseProb for original BB.
  1479. // Assuming the original probabilities are A and B, one choice is to set
  1480. // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
  1481. // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
  1482. // TrueProb for BB1 * FalseProb for TmpBB.
  1483. auto NewTrueProb = TProb + FProb / 2;
  1484. auto NewFalseProb = FProb / 2;
  1485. // Emit the LHS condition.
  1486. FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
  1487. NewTrueProb, NewFalseProb);
  1488. // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
  1489. SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
  1490. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  1491. // Emit the RHS condition into TmpBB.
  1492. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
  1493. Probs[0], Probs[1]);
  1494. }
  1495. }
  1496. /// If the set of cases should be emitted as a series of branches, return true.
  1497. /// If we should emit this as a bunch of and/or'd together conditions, return
  1498. /// false.
  1499. bool
  1500. SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
  1501. if (Cases.size() != 2) return true;
  1502. // If this is two comparisons of the same values or'd or and'd together, they
  1503. // will get folded into a single comparison, so don't emit two blocks.
  1504. if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
  1505. Cases[0].CmpRHS == Cases[1].CmpRHS) ||
  1506. (Cases[0].CmpRHS == Cases[1].CmpLHS &&
  1507. Cases[0].CmpLHS == Cases[1].CmpRHS)) {
  1508. return false;
  1509. }
  1510. // Handle: (X != null) | (Y != null) --> (X|Y) != 0
  1511. // Handle: (X == null) & (Y == null) --> (X|Y) == 0
  1512. if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
  1513. Cases[0].CC == Cases[1].CC &&
  1514. isa<Constant>(Cases[0].CmpRHS) &&
  1515. cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
  1516. if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
  1517. return false;
  1518. if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
  1519. return false;
  1520. }
  1521. return true;
  1522. }
  1523. void SelectionDAGBuilder::visitBr(const BranchInst &I) {
  1524. MachineBasicBlock *BrMBB = FuncInfo.MBB;
  1525. // Update machine-CFG edges.
  1526. MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
  1527. if (I.isUnconditional()) {
  1528. // Update machine-CFG edges.
  1529. BrMBB->addSuccessor(Succ0MBB);
  1530. // If this is not a fall-through branch or optimizations are switched off,
  1531. // emit the branch.
  1532. if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
  1533. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  1534. MVT::Other, getControlRoot(),
  1535. DAG.getBasicBlock(Succ0MBB)));
  1536. return;
  1537. }
  1538. // If this condition is one of the special cases we handle, do special stuff
  1539. // now.
  1540. const Value *CondVal = I.getCondition();
  1541. MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
  1542. // If this is a series of conditions that are or'd or and'd together, emit
  1543. // this as a sequence of branches instead of setcc's with and/or operations.
  1544. // As long as jumps are not expensive, this should improve performance.
  1545. // For example, instead of something like:
  1546. // cmp A, B
  1547. // C = seteq
  1548. // cmp D, E
  1549. // F = setle
  1550. // or C, F
  1551. // jnz foo
  1552. // Emit:
  1553. // cmp A, B
  1554. // je foo
  1555. // cmp D, E
  1556. // jle foo
  1557. //
  1558. if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
  1559. Instruction::BinaryOps Opcode = BOp->getOpcode();
  1560. if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
  1561. !I.getMetadata(LLVMContext::MD_unpredictable) &&
  1562. (Opcode == Instruction::And || Opcode == Instruction::Or)) {
  1563. FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
  1564. Opcode,
  1565. getEdgeProbability(BrMBB, Succ0MBB),
  1566. getEdgeProbability(BrMBB, Succ1MBB));
  1567. // If the compares in later blocks need to use values not currently
  1568. // exported from this block, export them now. This block should always
  1569. // be the first entry.
  1570. assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
  1571. // Allow some cases to be rejected.
  1572. if (ShouldEmitAsBranches(SwitchCases)) {
  1573. for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
  1574. ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
  1575. ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
  1576. }
  1577. // Emit the branch for this block.
  1578. visitSwitchCase(SwitchCases[0], BrMBB);
  1579. SwitchCases.erase(SwitchCases.begin());
  1580. return;
  1581. }
  1582. // Okay, we decided not to do this, remove any inserted MBB's and clear
  1583. // SwitchCases.
  1584. for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
  1585. FuncInfo.MF->erase(SwitchCases[i].ThisBB);
  1586. SwitchCases.clear();
  1587. }
  1588. }
  1589. // Create a CaseBlock record representing this branch.
  1590. CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
  1591. nullptr, Succ0MBB, Succ1MBB, BrMBB);
  1592. // Use visitSwitchCase to actually insert the fast branch sequence for this
  1593. // cond branch.
  1594. visitSwitchCase(CB, BrMBB);
  1595. }
  1596. /// visitSwitchCase - Emits the necessary code to represent a single node in
  1597. /// the binary search tree resulting from lowering a switch instruction.
  1598. void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
  1599. MachineBasicBlock *SwitchBB) {
  1600. SDValue Cond;
  1601. SDValue CondLHS = getValue(CB.CmpLHS);
  1602. SDLoc dl = getCurSDLoc();
  1603. // Build the setcc now.
  1604. if (!CB.CmpMHS) {
  1605. // Fold "(X == true)" to X and "(X == false)" to !X to
  1606. // handle common cases produced by branch lowering.
  1607. if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
  1608. CB.CC == ISD::SETEQ)
  1609. Cond = CondLHS;
  1610. else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
  1611. CB.CC == ISD::SETEQ) {
  1612. SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
  1613. Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
  1614. } else
  1615. Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
  1616. } else {
  1617. assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
  1618. const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
  1619. const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
  1620. SDValue CmpOp = getValue(CB.CmpMHS);
  1621. EVT VT = CmpOp.getValueType();
  1622. if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
  1623. Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
  1624. ISD::SETLE);
  1625. } else {
  1626. SDValue SUB = DAG.getNode(ISD::SUB, dl,
  1627. VT, CmpOp, DAG.getConstant(Low, dl, VT));
  1628. Cond = DAG.getSetCC(dl, MVT::i1, SUB,
  1629. DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
  1630. }
  1631. }
  1632. // Update successor info
  1633. addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
  1634. // TrueBB and FalseBB are always different unless the incoming IR is
  1635. // degenerate. This only happens when running llc on weird IR.
  1636. if (CB.TrueBB != CB.FalseBB)
  1637. addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
  1638. SwitchBB->normalizeSuccProbs();
  1639. // If the lhs block is the next block, invert the condition so that we can
  1640. // fall through to the lhs instead of the rhs block.
  1641. if (CB.TrueBB == NextBlock(SwitchBB)) {
  1642. std::swap(CB.TrueBB, CB.FalseBB);
  1643. SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
  1644. Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
  1645. }
  1646. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  1647. MVT::Other, getControlRoot(), Cond,
  1648. DAG.getBasicBlock(CB.TrueBB));
  1649. // Insert the false branch. Do this even if it's a fall through branch,
  1650. // this makes it easier to do DAG optimizations which require inverting
  1651. // the branch condition.
  1652. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  1653. DAG.getBasicBlock(CB.FalseBB));
  1654. DAG.setRoot(BrCond);
  1655. }
  1656. /// visitJumpTable - Emit JumpTable node in the current MBB
  1657. void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
  1658. // Emit the code for the jump table
  1659. assert(JT.Reg != -1U && "Should lower JT Header first!");
  1660. EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
  1661. SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
  1662. JT.Reg, PTy);
  1663. SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
  1664. SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
  1665. MVT::Other, Index.getValue(1),
  1666. Table, Index);
  1667. DAG.setRoot(BrJumpTable);
  1668. }
  1669. /// visitJumpTableHeader - This function emits necessary code to produce index
  1670. /// in the JumpTable from switch case.
  1671. void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
  1672. JumpTableHeader &JTH,
  1673. MachineBasicBlock *SwitchBB) {
  1674. SDLoc dl = getCurSDLoc();
  1675. // Subtract the lowest switch case value from the value being switched on and
  1676. // conditional branch to default mbb if the result is greater than the
  1677. // difference between smallest and largest cases.
  1678. SDValue SwitchOp = getValue(JTH.SValue);
  1679. EVT VT = SwitchOp.getValueType();
  1680. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
  1681. DAG.getConstant(JTH.First, dl, VT));
  1682. // The SDNode we just created, which holds the value being switched on minus
  1683. // the smallest case value, needs to be copied to a virtual register so it
  1684. // can be used as an index into the jump table in a subsequent basic block.
  1685. // This value may be smaller or larger than the target's pointer type, and
  1686. // therefore require extension or truncating.
  1687. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1688. SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
  1689. unsigned JumpTableReg =
  1690. FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
  1691. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
  1692. JumpTableReg, SwitchOp);
  1693. JT.Reg = JumpTableReg;
  1694. // Emit the range check for the jump table, and branch to the default block
  1695. // for the switch statement if the value being switched on exceeds the largest
  1696. // case in the switch.
  1697. SDValue CMP = DAG.getSetCC(
  1698. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  1699. Sub.getValueType()),
  1700. Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
  1701. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  1702. MVT::Other, CopyTo, CMP,
  1703. DAG.getBasicBlock(JT.Default));
  1704. // Avoid emitting unnecessary branches to the next block.
  1705. if (JT.MBB != NextBlock(SwitchBB))
  1706. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  1707. DAG.getBasicBlock(JT.MBB));
  1708. DAG.setRoot(BrCond);
  1709. }
  1710. /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
  1711. /// variable if there exists one.
  1712. static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
  1713. SDValue &Chain) {
  1714. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1715. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  1716. MachineFunction &MF = DAG.getMachineFunction();
  1717. Value *Global = TLI.getSDagStackGuard(*MF.getFunction()->getParent());
  1718. MachineSDNode *Node =
  1719. DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
  1720. if (Global) {
  1721. MachinePointerInfo MPInfo(Global);
  1722. MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
  1723. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
  1724. MachineMemOperand::MODereferenceable;
  1725. *MemRefs = MF.getMachineMemOperand(MPInfo, Flags, PtrTy.getSizeInBits() / 8,
  1726. DAG.getEVTAlignment(PtrTy));
  1727. Node->setMemRefs(MemRefs, MemRefs + 1);
  1728. }
  1729. return SDValue(Node, 0);
  1730. }
  1731. /// Codegen a new tail for a stack protector check ParentMBB which has had its
  1732. /// tail spliced into a stack protector check success bb.
  1733. ///
  1734. /// For a high level explanation of how this fits into the stack protector
  1735. /// generation see the comment on the declaration of class
  1736. /// StackProtectorDescriptor.
  1737. void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
  1738. MachineBasicBlock *ParentBB) {
  1739. // First create the loads to the guard/stack slot for the comparison.
  1740. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1741. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  1742. MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
  1743. int FI = MFI.getStackProtectorIndex();
  1744. SDValue Guard;
  1745. SDLoc dl = getCurSDLoc();
  1746. SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
  1747. const Module &M = *ParentBB->getParent()->getFunction()->getParent();
  1748. unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
  1749. // Generate code to load the content of the guard slot.
  1750. SDValue StackSlot = DAG.getLoad(
  1751. PtrTy, dl, DAG.getEntryNode(), StackSlotPtr,
  1752. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
  1753. MachineMemOperand::MOVolatile);
  1754. // Retrieve guard check function, nullptr if instrumentation is inlined.
  1755. if (const Value *GuardCheck = TLI.getSSPStackGuardCheck(M)) {
  1756. // The target provides a guard check function to validate the guard value.
  1757. // Generate a call to that function with the content of the guard slot as
  1758. // argument.
  1759. auto *Fn = cast<Function>(GuardCheck);
  1760. FunctionType *FnTy = Fn->getFunctionType();
  1761. assert(FnTy->getNumParams() == 1 && "Invalid function signature");
  1762. TargetLowering::ArgListTy Args;
  1763. TargetLowering::ArgListEntry Entry;
  1764. Entry.Node = StackSlot;
  1765. Entry.Ty = FnTy->getParamType(0);
  1766. if (Fn->hasAttribute(1, Attribute::AttrKind::InReg))
  1767. Entry.isInReg = true;
  1768. Args.push_back(Entry);
  1769. TargetLowering::CallLoweringInfo CLI(DAG);
  1770. CLI.setDebugLoc(getCurSDLoc())
  1771. .setChain(DAG.getEntryNode())
  1772. .setCallee(Fn->getCallingConv(), FnTy->getReturnType(),
  1773. getValue(GuardCheck), std::move(Args));
  1774. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  1775. DAG.setRoot(Result.second);
  1776. return;
  1777. }
  1778. // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
  1779. // Otherwise, emit a volatile load to retrieve the stack guard value.
  1780. SDValue Chain = DAG.getEntryNode();
  1781. if (TLI.useLoadStackGuardNode()) {
  1782. Guard = getLoadStackGuard(DAG, dl, Chain);
  1783. } else {
  1784. const Value *IRGuard = TLI.getSDagStackGuard(M);
  1785. SDValue GuardPtr = getValue(IRGuard);
  1786. Guard =
  1787. DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0),
  1788. Align, MachineMemOperand::MOVolatile);
  1789. }
  1790. // Perform the comparison via a subtract/getsetcc.
  1791. EVT VT = Guard.getValueType();
  1792. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, StackSlot);
  1793. SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
  1794. *DAG.getContext(),
  1795. Sub.getValueType()),
  1796. Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
  1797. // If the sub is not 0, then we know the guard/stackslot do not equal, so
  1798. // branch to failure MBB.
  1799. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  1800. MVT::Other, StackSlot.getOperand(0),
  1801. Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
  1802. // Otherwise branch to success MBB.
  1803. SDValue Br = DAG.getNode(ISD::BR, dl,
  1804. MVT::Other, BrCond,
  1805. DAG.getBasicBlock(SPD.getSuccessMBB()));
  1806. DAG.setRoot(Br);
  1807. }
  1808. /// Codegen the failure basic block for a stack protector check.
  1809. ///
  1810. /// A failure stack protector machine basic block consists simply of a call to
  1811. /// __stack_chk_fail().
  1812. ///
  1813. /// For a high level explanation of how this fits into the stack protector
  1814. /// generation see the comment on the declaration of class
  1815. /// StackProtectorDescriptor.
  1816. void
  1817. SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
  1818. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1819. SDValue Chain =
  1820. TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
  1821. None, false, getCurSDLoc(), false, false).second;
  1822. DAG.setRoot(Chain);
  1823. }
  1824. /// visitBitTestHeader - This function emits necessary code to produce value
  1825. /// suitable for "bit tests"
  1826. void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
  1827. MachineBasicBlock *SwitchBB) {
  1828. SDLoc dl = getCurSDLoc();
  1829. // Subtract the minimum value
  1830. SDValue SwitchOp = getValue(B.SValue);
  1831. EVT VT = SwitchOp.getValueType();
  1832. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
  1833. DAG.getConstant(B.First, dl, VT));
  1834. // Check range
  1835. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1836. SDValue RangeCmp = DAG.getSetCC(
  1837. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  1838. Sub.getValueType()),
  1839. Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
  1840. // Determine the type of the test operands.
  1841. bool UsePtrType = false;
  1842. if (!TLI.isTypeLegal(VT))
  1843. UsePtrType = true;
  1844. else {
  1845. for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
  1846. if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
  1847. // Switch table case range are encoded into series of masks.
  1848. // Just use pointer type, it's guaranteed to fit.
  1849. UsePtrType = true;
  1850. break;
  1851. }
  1852. }
  1853. if (UsePtrType) {
  1854. VT = TLI.getPointerTy(DAG.getDataLayout());
  1855. Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
  1856. }
  1857. B.RegVT = VT.getSimpleVT();
  1858. B.Reg = FuncInfo.CreateReg(B.RegVT);
  1859. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
  1860. MachineBasicBlock* MBB = B.Cases[0].ThisBB;
  1861. addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
  1862. addSuccessorWithProb(SwitchBB, MBB, B.Prob);
  1863. SwitchBB->normalizeSuccProbs();
  1864. SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
  1865. MVT::Other, CopyTo, RangeCmp,
  1866. DAG.getBasicBlock(B.Default));
  1867. // Avoid emitting unnecessary branches to the next block.
  1868. if (MBB != NextBlock(SwitchBB))
  1869. BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
  1870. DAG.getBasicBlock(MBB));
  1871. DAG.setRoot(BrRange);
  1872. }
  1873. /// visitBitTestCase - this function produces one "bit test"
  1874. void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
  1875. MachineBasicBlock* NextMBB,
  1876. BranchProbability BranchProbToNext,
  1877. unsigned Reg,
  1878. BitTestCase &B,
  1879. MachineBasicBlock *SwitchBB) {
  1880. SDLoc dl = getCurSDLoc();
  1881. MVT VT = BB.RegVT;
  1882. SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
  1883. SDValue Cmp;
  1884. unsigned PopCount = countPopulation(B.Mask);
  1885. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1886. if (PopCount == 1) {
  1887. // Testing for a single bit; just compare the shift count with what it
  1888. // would need to be to shift a 1 bit in that position.
  1889. Cmp = DAG.getSetCC(
  1890. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  1891. ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
  1892. ISD::SETEQ);
  1893. } else if (PopCount == BB.Range) {
  1894. // There is only one zero bit in the range, test for it directly.
  1895. Cmp = DAG.getSetCC(
  1896. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  1897. ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
  1898. ISD::SETNE);
  1899. } else {
  1900. // Make desired shift
  1901. SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
  1902. DAG.getConstant(1, dl, VT), ShiftOp);
  1903. // Emit bit tests and jumps
  1904. SDValue AndOp = DAG.getNode(ISD::AND, dl,
  1905. VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
  1906. Cmp = DAG.getSetCC(
  1907. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  1908. AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
  1909. }
  1910. // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
  1911. addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
  1912. // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
  1913. addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
  1914. // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
  1915. // one as they are relative probabilities (and thus work more like weights),
  1916. // and hence we need to normalize them to let the sum of them become one.
  1917. SwitchBB->normalizeSuccProbs();
  1918. SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
  1919. MVT::Other, getControlRoot(),
  1920. Cmp, DAG.getBasicBlock(B.TargetBB));
  1921. // Avoid emitting unnecessary branches to the next block.
  1922. if (NextMBB != NextBlock(SwitchBB))
  1923. BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
  1924. DAG.getBasicBlock(NextMBB));
  1925. DAG.setRoot(BrAnd);
  1926. }
  1927. void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
  1928. MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
  1929. // Retrieve successors. Look through artificial IR level blocks like
  1930. // catchswitch for successors.
  1931. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
  1932. const BasicBlock *EHPadBB = I.getSuccessor(1);
  1933. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  1934. // have to do anything here to lower funclet bundles.
  1935. assert(!I.hasOperandBundlesOtherThan(
  1936. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  1937. "Cannot lower invokes with arbitrary operand bundles yet!");
  1938. const Value *Callee(I.getCalledValue());
  1939. const Function *Fn = dyn_cast<Function>(Callee);
  1940. if (isa<InlineAsm>(Callee))
  1941. visitInlineAsm(&I);
  1942. else if (Fn && Fn->isIntrinsic()) {
  1943. switch (Fn->getIntrinsicID()) {
  1944. default:
  1945. llvm_unreachable("Cannot invoke this intrinsic");
  1946. case Intrinsic::donothing:
  1947. // Ignore invokes to @llvm.donothing: jump directly to the next BB.
  1948. break;
  1949. case Intrinsic::experimental_patchpoint_void:
  1950. case Intrinsic::experimental_patchpoint_i64:
  1951. visitPatchpoint(&I, EHPadBB);
  1952. break;
  1953. case Intrinsic::experimental_gc_statepoint:
  1954. LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
  1955. break;
  1956. }
  1957. } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
  1958. // Currently we do not lower any intrinsic calls with deopt operand bundles.
  1959. // Eventually we will support lowering the @llvm.experimental.deoptimize
  1960. // intrinsic, and right now there are no plans to support other intrinsics
  1961. // with deopt state.
  1962. LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
  1963. } else {
  1964. LowerCallTo(&I, getValue(Callee), false, EHPadBB);
  1965. }
  1966. // If the value of the invoke is used outside of its defining block, make it
  1967. // available as a virtual register.
  1968. // We already took care of the exported value for the statepoint instruction
  1969. // during call to the LowerStatepoint.
  1970. if (!isStatepoint(I)) {
  1971. CopyToExportRegsIfNeeded(&I);
  1972. }
  1973. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  1974. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1975. BranchProbability EHPadBBProb =
  1976. BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
  1977. : BranchProbability::getZero();
  1978. findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
  1979. // Update successor info.
  1980. addSuccessorWithProb(InvokeMBB, Return);
  1981. for (auto &UnwindDest : UnwindDests) {
  1982. UnwindDest.first->setIsEHPad();
  1983. addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
  1984. }
  1985. InvokeMBB->normalizeSuccProbs();
  1986. // Drop into normal successor.
  1987. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  1988. MVT::Other, getControlRoot(),
  1989. DAG.getBasicBlock(Return)));
  1990. }
  1991. void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
  1992. llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
  1993. }
  1994. void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
  1995. assert(FuncInfo.MBB->isEHPad() &&
  1996. "Call to landingpad not in landing pad!");
  1997. MachineBasicBlock *MBB = FuncInfo.MBB;
  1998. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  1999. addLandingPadInfo(LP, MMI, *MBB);
  2000. // If there aren't registers to copy the values into (e.g., during SjLj
  2001. // exceptions), then don't bother to create these DAG nodes.
  2002. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2003. const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
  2004. if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
  2005. TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
  2006. return;
  2007. // If landingpad's return type is token type, we don't create DAG nodes
  2008. // for its exception pointer and selector value. The extraction of exception
  2009. // pointer or selector value from token type landingpads is not currently
  2010. // supported.
  2011. if (LP.getType()->isTokenTy())
  2012. return;
  2013. SmallVector<EVT, 2> ValueVTs;
  2014. SDLoc dl = getCurSDLoc();
  2015. ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
  2016. assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
  2017. // Get the two live-in registers as SDValues. The physregs have already been
  2018. // copied into virtual registers.
  2019. SDValue Ops[2];
  2020. if (FuncInfo.ExceptionPointerVirtReg) {
  2021. Ops[0] = DAG.getZExtOrTrunc(
  2022. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2023. FuncInfo.ExceptionPointerVirtReg,
  2024. TLI.getPointerTy(DAG.getDataLayout())),
  2025. dl, ValueVTs[0]);
  2026. } else {
  2027. Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
  2028. }
  2029. Ops[1] = DAG.getZExtOrTrunc(
  2030. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2031. FuncInfo.ExceptionSelectorVirtReg,
  2032. TLI.getPointerTy(DAG.getDataLayout())),
  2033. dl, ValueVTs[1]);
  2034. // Merge into one.
  2035. SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
  2036. DAG.getVTList(ValueVTs), Ops);
  2037. setValue(&LP, Res);
  2038. }
  2039. void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
  2040. #ifndef NDEBUG
  2041. for (const CaseCluster &CC : Clusters)
  2042. assert(CC.Low == CC.High && "Input clusters must be single-case");
  2043. #endif
  2044. std::sort(Clusters.begin(), Clusters.end(),
  2045. [](const CaseCluster &a, const CaseCluster &b) {
  2046. return a.Low->getValue().slt(b.Low->getValue());
  2047. });
  2048. // Merge adjacent clusters with the same destination.
  2049. const unsigned N = Clusters.size();
  2050. unsigned DstIndex = 0;
  2051. for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
  2052. CaseCluster &CC = Clusters[SrcIndex];
  2053. const ConstantInt *CaseVal = CC.Low;
  2054. MachineBasicBlock *Succ = CC.MBB;
  2055. if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
  2056. (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
  2057. // If this case has the same successor and is a neighbour, merge it into
  2058. // the previous cluster.
  2059. Clusters[DstIndex - 1].High = CaseVal;
  2060. Clusters[DstIndex - 1].Prob += CC.Prob;
  2061. } else {
  2062. std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
  2063. sizeof(Clusters[SrcIndex]));
  2064. }
  2065. }
  2066. Clusters.resize(DstIndex);
  2067. }
  2068. void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
  2069. MachineBasicBlock *Last) {
  2070. // Update JTCases.
  2071. for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
  2072. if (JTCases[i].first.HeaderBB == First)
  2073. JTCases[i].first.HeaderBB = Last;
  2074. // Update BitTestCases.
  2075. for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
  2076. if (BitTestCases[i].Parent == First)
  2077. BitTestCases[i].Parent = Last;
  2078. }
  2079. void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
  2080. MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
  2081. // Update machine-CFG edges with unique successors.
  2082. SmallSet<BasicBlock*, 32> Done;
  2083. for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
  2084. BasicBlock *BB = I.getSuccessor(i);
  2085. bool Inserted = Done.insert(BB).second;
  2086. if (!Inserted)
  2087. continue;
  2088. MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
  2089. addSuccessorWithProb(IndirectBrMBB, Succ);
  2090. }
  2091. IndirectBrMBB->normalizeSuccProbs();
  2092. DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
  2093. MVT::Other, getControlRoot(),
  2094. getValue(I.getAddress())));
  2095. }
  2096. void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
  2097. if (DAG.getTarget().Options.TrapUnreachable)
  2098. DAG.setRoot(
  2099. DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
  2100. }
  2101. void SelectionDAGBuilder::visitFSub(const User &I) {
  2102. // -0.0 - X --> fneg
  2103. Type *Ty = I.getType();
  2104. if (isa<Constant>(I.getOperand(0)) &&
  2105. I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
  2106. SDValue Op2 = getValue(I.getOperand(1));
  2107. setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
  2108. Op2.getValueType(), Op2));
  2109. return;
  2110. }
  2111. visitBinary(I, ISD::FSUB);
  2112. }
  2113. /// Checks if the given instruction performs a vector reduction, in which case
  2114. /// we have the freedom to alter the elements in the result as long as the
  2115. /// reduction of them stays unchanged.
  2116. static bool isVectorReductionOp(const User *I) {
  2117. const Instruction *Inst = dyn_cast<Instruction>(I);
  2118. if (!Inst || !Inst->getType()->isVectorTy())
  2119. return false;
  2120. auto OpCode = Inst->getOpcode();
  2121. switch (OpCode) {
  2122. case Instruction::Add:
  2123. case Instruction::Mul:
  2124. case Instruction::And:
  2125. case Instruction::Or:
  2126. case Instruction::Xor:
  2127. break;
  2128. case Instruction::FAdd:
  2129. case Instruction::FMul:
  2130. if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
  2131. if (FPOp->getFastMathFlags().unsafeAlgebra())
  2132. break;
  2133. LLVM_FALLTHROUGH;
  2134. default:
  2135. return false;
  2136. }
  2137. unsigned ElemNum = Inst->getType()->getVectorNumElements();
  2138. unsigned ElemNumToReduce = ElemNum;
  2139. // Do DFS search on the def-use chain from the given instruction. We only
  2140. // allow four kinds of operations during the search until we reach the
  2141. // instruction that extracts the first element from the vector:
  2142. //
  2143. // 1. The reduction operation of the same opcode as the given instruction.
  2144. //
  2145. // 2. PHI node.
  2146. //
  2147. // 3. ShuffleVector instruction together with a reduction operation that
  2148. // does a partial reduction.
  2149. //
  2150. // 4. ExtractElement that extracts the first element from the vector, and we
  2151. // stop searching the def-use chain here.
  2152. //
  2153. // 3 & 4 above perform a reduction on all elements of the vector. We push defs
  2154. // from 1-3 to the stack to continue the DFS. The given instruction is not
  2155. // a reduction operation if we meet any other instructions other than those
  2156. // listed above.
  2157. SmallVector<const User *, 16> UsersToVisit{Inst};
  2158. SmallPtrSet<const User *, 16> Visited;
  2159. bool ReduxExtracted = false;
  2160. while (!UsersToVisit.empty()) {
  2161. auto User = UsersToVisit.back();
  2162. UsersToVisit.pop_back();
  2163. if (!Visited.insert(User).second)
  2164. continue;
  2165. for (const auto &U : User->users()) {
  2166. auto Inst = dyn_cast<Instruction>(U);
  2167. if (!Inst)
  2168. return false;
  2169. if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
  2170. if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
  2171. if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().unsafeAlgebra())
  2172. return false;
  2173. UsersToVisit.push_back(U);
  2174. } else if (const ShuffleVectorInst *ShufInst =
  2175. dyn_cast<ShuffleVectorInst>(U)) {
  2176. // Detect the following pattern: A ShuffleVector instruction together
  2177. // with a reduction that do partial reduction on the first and second
  2178. // ElemNumToReduce / 2 elements, and store the result in
  2179. // ElemNumToReduce / 2 elements in another vector.
  2180. unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
  2181. if (ResultElements < ElemNum)
  2182. return false;
  2183. if (ElemNumToReduce == 1)
  2184. return false;
  2185. if (!isa<UndefValue>(U->getOperand(1)))
  2186. return false;
  2187. for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
  2188. if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
  2189. return false;
  2190. for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
  2191. if (ShufInst->getMaskValue(i) != -1)
  2192. return false;
  2193. // There is only one user of this ShuffleVector instruction, which
  2194. // must be a reduction operation.
  2195. if (!U->hasOneUse())
  2196. return false;
  2197. auto U2 = dyn_cast<Instruction>(*U->user_begin());
  2198. if (!U2 || U2->getOpcode() != OpCode)
  2199. return false;
  2200. // Check operands of the reduction operation.
  2201. if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
  2202. (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
  2203. UsersToVisit.push_back(U2);
  2204. ElemNumToReduce /= 2;
  2205. } else
  2206. return false;
  2207. } else if (isa<ExtractElementInst>(U)) {
  2208. // At this moment we should have reduced all elements in the vector.
  2209. if (ElemNumToReduce != 1)
  2210. return false;
  2211. const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
  2212. if (!Val || Val->getZExtValue() != 0)
  2213. return false;
  2214. ReduxExtracted = true;
  2215. } else
  2216. return false;
  2217. }
  2218. }
  2219. return ReduxExtracted;
  2220. }
  2221. void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
  2222. SDValue Op1 = getValue(I.getOperand(0));
  2223. SDValue Op2 = getValue(I.getOperand(1));
  2224. bool nuw = false;
  2225. bool nsw = false;
  2226. bool exact = false;
  2227. bool vec_redux = false;
  2228. FastMathFlags FMF;
  2229. if (const OverflowingBinaryOperator *OFBinOp =
  2230. dyn_cast<const OverflowingBinaryOperator>(&I)) {
  2231. nuw = OFBinOp->hasNoUnsignedWrap();
  2232. nsw = OFBinOp->hasNoSignedWrap();
  2233. }
  2234. if (const PossiblyExactOperator *ExactOp =
  2235. dyn_cast<const PossiblyExactOperator>(&I))
  2236. exact = ExactOp->isExact();
  2237. if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(&I))
  2238. FMF = FPOp->getFastMathFlags();
  2239. if (isVectorReductionOp(&I)) {
  2240. vec_redux = true;
  2241. DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
  2242. }
  2243. SDNodeFlags Flags;
  2244. Flags.setExact(exact);
  2245. Flags.setNoSignedWrap(nsw);
  2246. Flags.setNoUnsignedWrap(nuw);
  2247. Flags.setVectorReduction(vec_redux);
  2248. if (EnableFMFInDAG) {
  2249. Flags.setAllowReciprocal(FMF.allowReciprocal());
  2250. Flags.setNoInfs(FMF.noInfs());
  2251. Flags.setNoNaNs(FMF.noNaNs());
  2252. Flags.setNoSignedZeros(FMF.noSignedZeros());
  2253. Flags.setUnsafeAlgebra(FMF.unsafeAlgebra());
  2254. }
  2255. SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(),
  2256. Op1, Op2, &Flags);
  2257. setValue(&I, BinNodeValue);
  2258. }
  2259. void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
  2260. SDValue Op1 = getValue(I.getOperand(0));
  2261. SDValue Op2 = getValue(I.getOperand(1));
  2262. EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
  2263. Op2.getValueType(), DAG.getDataLayout());
  2264. // Coerce the shift amount to the right type if we can.
  2265. if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
  2266. unsigned ShiftSize = ShiftTy.getSizeInBits();
  2267. unsigned Op2Size = Op2.getValueSizeInBits();
  2268. SDLoc DL = getCurSDLoc();
  2269. // If the operand is smaller than the shift count type, promote it.
  2270. if (ShiftSize > Op2Size)
  2271. Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
  2272. // If the operand is larger than the shift count type but the shift
  2273. // count type has enough bits to represent any shift value, truncate
  2274. // it now. This is a common case and it exposes the truncate to
  2275. // optimization early.
  2276. else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
  2277. Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
  2278. // Otherwise we'll need to temporarily settle for some other convenient
  2279. // type. Type legalization will make adjustments once the shiftee is split.
  2280. else
  2281. Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
  2282. }
  2283. bool nuw = false;
  2284. bool nsw = false;
  2285. bool exact = false;
  2286. if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
  2287. if (const OverflowingBinaryOperator *OFBinOp =
  2288. dyn_cast<const OverflowingBinaryOperator>(&I)) {
  2289. nuw = OFBinOp->hasNoUnsignedWrap();
  2290. nsw = OFBinOp->hasNoSignedWrap();
  2291. }
  2292. if (const PossiblyExactOperator *ExactOp =
  2293. dyn_cast<const PossiblyExactOperator>(&I))
  2294. exact = ExactOp->isExact();
  2295. }
  2296. SDNodeFlags Flags;
  2297. Flags.setExact(exact);
  2298. Flags.setNoSignedWrap(nsw);
  2299. Flags.setNoUnsignedWrap(nuw);
  2300. SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
  2301. &Flags);
  2302. setValue(&I, Res);
  2303. }
  2304. void SelectionDAGBuilder::visitSDiv(const User &I) {
  2305. SDValue Op1 = getValue(I.getOperand(0));
  2306. SDValue Op2 = getValue(I.getOperand(1));
  2307. SDNodeFlags Flags;
  2308. Flags.setExact(isa<PossiblyExactOperator>(&I) &&
  2309. cast<PossiblyExactOperator>(&I)->isExact());
  2310. setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
  2311. Op2, &Flags));
  2312. }
  2313. void SelectionDAGBuilder::visitICmp(const User &I) {
  2314. ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
  2315. if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
  2316. predicate = IC->getPredicate();
  2317. else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
  2318. predicate = ICmpInst::Predicate(IC->getPredicate());
  2319. SDValue Op1 = getValue(I.getOperand(0));
  2320. SDValue Op2 = getValue(I.getOperand(1));
  2321. ISD::CondCode Opcode = getICmpCondCode(predicate);
  2322. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2323. I.getType());
  2324. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
  2325. }
  2326. void SelectionDAGBuilder::visitFCmp(const User &I) {
  2327. FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
  2328. if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
  2329. predicate = FC->getPredicate();
  2330. else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
  2331. predicate = FCmpInst::Predicate(FC->getPredicate());
  2332. SDValue Op1 = getValue(I.getOperand(0));
  2333. SDValue Op2 = getValue(I.getOperand(1));
  2334. ISD::CondCode Condition = getFCmpCondCode(predicate);
  2335. // FIXME: Fcmp instructions have fast-math-flags in IR, so we should use them.
  2336. // FIXME: We should propagate the fast-math-flags to the DAG node itself for
  2337. // further optimization, but currently FMF is only applicable to binary nodes.
  2338. if (TM.Options.NoNaNsFPMath)
  2339. Condition = getFCmpCodeWithoutNaN(Condition);
  2340. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2341. I.getType());
  2342. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
  2343. }
  2344. // Check if the condition of the select has one use or two users that are both
  2345. // selects with the same condition.
  2346. static bool hasOnlySelectUsers(const Value *Cond) {
  2347. return all_of(Cond->users(), [](const Value *V) {
  2348. return isa<SelectInst>(V);
  2349. });
  2350. }
  2351. void SelectionDAGBuilder::visitSelect(const User &I) {
  2352. SmallVector<EVT, 4> ValueVTs;
  2353. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
  2354. ValueVTs);
  2355. unsigned NumValues = ValueVTs.size();
  2356. if (NumValues == 0) return;
  2357. SmallVector<SDValue, 4> Values(NumValues);
  2358. SDValue Cond = getValue(I.getOperand(0));
  2359. SDValue LHSVal = getValue(I.getOperand(1));
  2360. SDValue RHSVal = getValue(I.getOperand(2));
  2361. auto BaseOps = {Cond};
  2362. ISD::NodeType OpCode = Cond.getValueType().isVector() ?
  2363. ISD::VSELECT : ISD::SELECT;
  2364. // Min/max matching is only viable if all output VTs are the same.
  2365. if (std::equal(ValueVTs.begin(), ValueVTs.end(), ValueVTs.begin())) {
  2366. EVT VT = ValueVTs[0];
  2367. LLVMContext &Ctx = *DAG.getContext();
  2368. auto &TLI = DAG.getTargetLoweringInfo();
  2369. // We care about the legality of the operation after it has been type
  2370. // legalized.
  2371. while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
  2372. VT != TLI.getTypeToTransformTo(Ctx, VT))
  2373. VT = TLI.getTypeToTransformTo(Ctx, VT);
  2374. // If the vselect is legal, assume we want to leave this as a vector setcc +
  2375. // vselect. Otherwise, if this is going to be scalarized, we want to see if
  2376. // min/max is legal on the scalar type.
  2377. bool UseScalarMinMax = VT.isVector() &&
  2378. !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
  2379. Value *LHS, *RHS;
  2380. auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
  2381. ISD::NodeType Opc = ISD::DELETED_NODE;
  2382. switch (SPR.Flavor) {
  2383. case SPF_UMAX: Opc = ISD::UMAX; break;
  2384. case SPF_UMIN: Opc = ISD::UMIN; break;
  2385. case SPF_SMAX: Opc = ISD::SMAX; break;
  2386. case SPF_SMIN: Opc = ISD::SMIN; break;
  2387. case SPF_FMINNUM:
  2388. switch (SPR.NaNBehavior) {
  2389. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2390. case SPNB_RETURNS_NAN: Opc = ISD::FMINNAN; break;
  2391. case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
  2392. case SPNB_RETURNS_ANY: {
  2393. if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
  2394. Opc = ISD::FMINNUM;
  2395. else if (TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT))
  2396. Opc = ISD::FMINNAN;
  2397. else if (UseScalarMinMax)
  2398. Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
  2399. ISD::FMINNUM : ISD::FMINNAN;
  2400. break;
  2401. }
  2402. }
  2403. break;
  2404. case SPF_FMAXNUM:
  2405. switch (SPR.NaNBehavior) {
  2406. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2407. case SPNB_RETURNS_NAN: Opc = ISD::FMAXNAN; break;
  2408. case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
  2409. case SPNB_RETURNS_ANY:
  2410. if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
  2411. Opc = ISD::FMAXNUM;
  2412. else if (TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT))
  2413. Opc = ISD::FMAXNAN;
  2414. else if (UseScalarMinMax)
  2415. Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
  2416. ISD::FMAXNUM : ISD::FMAXNAN;
  2417. break;
  2418. }
  2419. break;
  2420. default: break;
  2421. }
  2422. if (Opc != ISD::DELETED_NODE &&
  2423. (TLI.isOperationLegalOrCustom(Opc, VT) ||
  2424. (UseScalarMinMax &&
  2425. TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
  2426. // If the underlying comparison instruction is used by any other
  2427. // instruction, the consumed instructions won't be destroyed, so it is
  2428. // not profitable to convert to a min/max.
  2429. hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
  2430. OpCode = Opc;
  2431. LHSVal = getValue(LHS);
  2432. RHSVal = getValue(RHS);
  2433. BaseOps = {};
  2434. }
  2435. }
  2436. for (unsigned i = 0; i != NumValues; ++i) {
  2437. SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
  2438. Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
  2439. Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
  2440. Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
  2441. LHSVal.getNode()->getValueType(LHSVal.getResNo()+i),
  2442. Ops);
  2443. }
  2444. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2445. DAG.getVTList(ValueVTs), Values));
  2446. }
  2447. void SelectionDAGBuilder::visitTrunc(const User &I) {
  2448. // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
  2449. SDValue N = getValue(I.getOperand(0));
  2450. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2451. I.getType());
  2452. setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
  2453. }
  2454. void SelectionDAGBuilder::visitZExt(const User &I) {
  2455. // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2456. // ZExt also can't be a cast to bool for same reason. So, nothing much to do
  2457. SDValue N = getValue(I.getOperand(0));
  2458. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2459. I.getType());
  2460. setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
  2461. }
  2462. void SelectionDAGBuilder::visitSExt(const User &I) {
  2463. // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2464. // SExt also can't be a cast to bool for same reason. So, nothing much to do
  2465. SDValue N = getValue(I.getOperand(0));
  2466. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2467. I.getType());
  2468. setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
  2469. }
  2470. void SelectionDAGBuilder::visitFPTrunc(const User &I) {
  2471. // FPTrunc is never a no-op cast, no need to check
  2472. SDValue N = getValue(I.getOperand(0));
  2473. SDLoc dl = getCurSDLoc();
  2474. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2475. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  2476. setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
  2477. DAG.getTargetConstant(
  2478. 0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
  2479. }
  2480. void SelectionDAGBuilder::visitFPExt(const User &I) {
  2481. // FPExt is never a no-op cast, no need to check
  2482. SDValue N = getValue(I.getOperand(0));
  2483. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2484. I.getType());
  2485. setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
  2486. }
  2487. void SelectionDAGBuilder::visitFPToUI(const User &I) {
  2488. // FPToUI is never a no-op cast, no need to check
  2489. SDValue N = getValue(I.getOperand(0));
  2490. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2491. I.getType());
  2492. setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
  2493. }
  2494. void SelectionDAGBuilder::visitFPToSI(const User &I) {
  2495. // FPToSI is never a no-op cast, no need to check
  2496. SDValue N = getValue(I.getOperand(0));
  2497. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2498. I.getType());
  2499. setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
  2500. }
  2501. void SelectionDAGBuilder::visitUIToFP(const User &I) {
  2502. // UIToFP is never a no-op cast, no need to check
  2503. SDValue N = getValue(I.getOperand(0));
  2504. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2505. I.getType());
  2506. setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
  2507. }
  2508. void SelectionDAGBuilder::visitSIToFP(const User &I) {
  2509. // SIToFP is never a no-op cast, no need to check
  2510. SDValue N = getValue(I.getOperand(0));
  2511. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2512. I.getType());
  2513. setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
  2514. }
  2515. void SelectionDAGBuilder::visitPtrToInt(const User &I) {
  2516. // What to do depends on the size of the integer and the size of the pointer.
  2517. // We can either truncate, zero extend, or no-op, accordingly.
  2518. SDValue N = getValue(I.getOperand(0));
  2519. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2520. I.getType());
  2521. setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
  2522. }
  2523. void SelectionDAGBuilder::visitIntToPtr(const User &I) {
  2524. // What to do depends on the size of the integer and the size of the pointer.
  2525. // We can either truncate, zero extend, or no-op, accordingly.
  2526. SDValue N = getValue(I.getOperand(0));
  2527. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2528. I.getType());
  2529. setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
  2530. }
  2531. void SelectionDAGBuilder::visitBitCast(const User &I) {
  2532. SDValue N = getValue(I.getOperand(0));
  2533. SDLoc dl = getCurSDLoc();
  2534. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2535. I.getType());
  2536. // BitCast assures us that source and destination are the same size so this is
  2537. // either a BITCAST or a no-op.
  2538. if (DestVT != N.getValueType())
  2539. setValue(&I, DAG.getNode(ISD::BITCAST, dl,
  2540. DestVT, N)); // convert types.
  2541. // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
  2542. // might fold any kind of constant expression to an integer constant and that
  2543. // is not what we are looking for. Only regcognize a bitcast of a genuine
  2544. // constant integer as an opaque constant.
  2545. else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
  2546. setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
  2547. /*isOpaque*/true));
  2548. else
  2549. setValue(&I, N); // noop cast.
  2550. }
  2551. void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
  2552. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2553. const Value *SV = I.getOperand(0);
  2554. SDValue N = getValue(SV);
  2555. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  2556. unsigned SrcAS = SV->getType()->getPointerAddressSpace();
  2557. unsigned DestAS = I.getType()->getPointerAddressSpace();
  2558. if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
  2559. N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
  2560. setValue(&I, N);
  2561. }
  2562. void SelectionDAGBuilder::visitInsertElement(const User &I) {
  2563. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2564. SDValue InVec = getValue(I.getOperand(0));
  2565. SDValue InVal = getValue(I.getOperand(1));
  2566. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
  2567. TLI.getVectorIdxTy(DAG.getDataLayout()));
  2568. setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
  2569. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  2570. InVec, InVal, InIdx));
  2571. }
  2572. void SelectionDAGBuilder::visitExtractElement(const User &I) {
  2573. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2574. SDValue InVec = getValue(I.getOperand(0));
  2575. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
  2576. TLI.getVectorIdxTy(DAG.getDataLayout()));
  2577. setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
  2578. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  2579. InVec, InIdx));
  2580. }
  2581. void SelectionDAGBuilder::visitShuffleVector(const User &I) {
  2582. SDValue Src1 = getValue(I.getOperand(0));
  2583. SDValue Src2 = getValue(I.getOperand(1));
  2584. SDLoc DL = getCurSDLoc();
  2585. SmallVector<int, 8> Mask;
  2586. ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
  2587. unsigned MaskNumElts = Mask.size();
  2588. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2589. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  2590. EVT SrcVT = Src1.getValueType();
  2591. unsigned SrcNumElts = SrcVT.getVectorNumElements();
  2592. if (SrcNumElts == MaskNumElts) {
  2593. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
  2594. return;
  2595. }
  2596. // Normalize the shuffle vector since mask and vector length don't match.
  2597. if (SrcNumElts < MaskNumElts) {
  2598. // Mask is longer than the source vectors. We can use concatenate vector to
  2599. // make the mask and vectors lengths match.
  2600. if (MaskNumElts % SrcNumElts == 0) {
  2601. // Mask length is a multiple of the source vector length.
  2602. // Check if the shuffle is some kind of concatenation of the input
  2603. // vectors.
  2604. unsigned NumConcat = MaskNumElts / SrcNumElts;
  2605. bool IsConcat = true;
  2606. SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
  2607. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2608. int Idx = Mask[i];
  2609. if (Idx < 0)
  2610. continue;
  2611. // Ensure the indices in each SrcVT sized piece are sequential and that
  2612. // the same source is used for the whole piece.
  2613. if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
  2614. (ConcatSrcs[i / SrcNumElts] >= 0 &&
  2615. ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
  2616. IsConcat = false;
  2617. break;
  2618. }
  2619. // Remember which source this index came from.
  2620. ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
  2621. }
  2622. // The shuffle is concatenating multiple vectors together. Just emit
  2623. // a CONCAT_VECTORS operation.
  2624. if (IsConcat) {
  2625. SmallVector<SDValue, 8> ConcatOps;
  2626. for (auto Src : ConcatSrcs) {
  2627. if (Src < 0)
  2628. ConcatOps.push_back(DAG.getUNDEF(SrcVT));
  2629. else if (Src == 0)
  2630. ConcatOps.push_back(Src1);
  2631. else
  2632. ConcatOps.push_back(Src2);
  2633. }
  2634. setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
  2635. return;
  2636. }
  2637. }
  2638. unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
  2639. unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
  2640. EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
  2641. PaddedMaskNumElts);
  2642. // Pad both vectors with undefs to make them the same length as the mask.
  2643. SDValue UndefVal = DAG.getUNDEF(SrcVT);
  2644. SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
  2645. SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
  2646. MOps1[0] = Src1;
  2647. MOps2[0] = Src2;
  2648. Src1 = Src1.isUndef()
  2649. ? DAG.getUNDEF(PaddedVT)
  2650. : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
  2651. Src2 = Src2.isUndef()
  2652. ? DAG.getUNDEF(PaddedVT)
  2653. : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
  2654. // Readjust mask for new input vector length.
  2655. SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
  2656. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2657. int Idx = Mask[i];
  2658. if (Idx >= (int)SrcNumElts)
  2659. Idx -= SrcNumElts - PaddedMaskNumElts;
  2660. MappedOps[i] = Idx;
  2661. }
  2662. SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
  2663. // If the concatenated vector was padded, extract a subvector with the
  2664. // correct number of elements.
  2665. if (MaskNumElts != PaddedMaskNumElts)
  2666. Result = DAG.getNode(
  2667. ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
  2668. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  2669. setValue(&I, Result);
  2670. return;
  2671. }
  2672. if (SrcNumElts > MaskNumElts) {
  2673. // Analyze the access pattern of the vector to see if we can extract
  2674. // two subvectors and do the shuffle. The analysis is done by calculating
  2675. // the range of elements the mask access on both vectors.
  2676. int MinRange[2] = { static_cast<int>(SrcNumElts),
  2677. static_cast<int>(SrcNumElts)};
  2678. int MaxRange[2] = {-1, -1};
  2679. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2680. int Idx = Mask[i];
  2681. unsigned Input = 0;
  2682. if (Idx < 0)
  2683. continue;
  2684. if (Idx >= (int)SrcNumElts) {
  2685. Input = 1;
  2686. Idx -= SrcNumElts;
  2687. }
  2688. if (Idx > MaxRange[Input])
  2689. MaxRange[Input] = Idx;
  2690. if (Idx < MinRange[Input])
  2691. MinRange[Input] = Idx;
  2692. }
  2693. // Check if the access is smaller than the vector size and can we find
  2694. // a reasonable extract index.
  2695. int RangeUse[2] = { -1, -1 }; // 0 = Unused, 1 = Extract, -1 = Can not
  2696. // Extract.
  2697. int StartIdx[2]; // StartIdx to extract from
  2698. for (unsigned Input = 0; Input < 2; ++Input) {
  2699. if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) {
  2700. RangeUse[Input] = 0; // Unused
  2701. StartIdx[Input] = 0;
  2702. continue;
  2703. }
  2704. // Find a good start index that is a multiple of the mask length. Then
  2705. // see if the rest of the elements are in range.
  2706. StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
  2707. if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
  2708. StartIdx[Input] + MaskNumElts <= SrcNumElts)
  2709. RangeUse[Input] = 1; // Extract from a multiple of the mask length.
  2710. }
  2711. if (RangeUse[0] == 0 && RangeUse[1] == 0) {
  2712. setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
  2713. return;
  2714. }
  2715. if (RangeUse[0] >= 0 && RangeUse[1] >= 0) {
  2716. // Extract appropriate subvector and generate a vector shuffle
  2717. for (unsigned Input = 0; Input < 2; ++Input) {
  2718. SDValue &Src = Input == 0 ? Src1 : Src2;
  2719. if (RangeUse[Input] == 0)
  2720. Src = DAG.getUNDEF(VT);
  2721. else {
  2722. Src = DAG.getNode(
  2723. ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
  2724. DAG.getConstant(StartIdx[Input], DL,
  2725. TLI.getVectorIdxTy(DAG.getDataLayout())));
  2726. }
  2727. }
  2728. // Calculate new mask.
  2729. SmallVector<int, 8> MappedOps;
  2730. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2731. int Idx = Mask[i];
  2732. if (Idx >= 0) {
  2733. if (Idx < (int)SrcNumElts)
  2734. Idx -= StartIdx[0];
  2735. else
  2736. Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
  2737. }
  2738. MappedOps.push_back(Idx);
  2739. }
  2740. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
  2741. return;
  2742. }
  2743. }
  2744. // We can't use either concat vectors or extract subvectors so fall back to
  2745. // replacing the shuffle with extract and build vector.
  2746. // to insert and build vector.
  2747. EVT EltVT = VT.getVectorElementType();
  2748. EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
  2749. SmallVector<SDValue,8> Ops;
  2750. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2751. int Idx = Mask[i];
  2752. SDValue Res;
  2753. if (Idx < 0) {
  2754. Res = DAG.getUNDEF(EltVT);
  2755. } else {
  2756. SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
  2757. if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
  2758. Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
  2759. EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
  2760. }
  2761. Ops.push_back(Res);
  2762. }
  2763. setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops));
  2764. }
  2765. void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
  2766. const Value *Op0 = I.getOperand(0);
  2767. const Value *Op1 = I.getOperand(1);
  2768. Type *AggTy = I.getType();
  2769. Type *ValTy = Op1->getType();
  2770. bool IntoUndef = isa<UndefValue>(Op0);
  2771. bool FromUndef = isa<UndefValue>(Op1);
  2772. unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
  2773. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2774. SmallVector<EVT, 4> AggValueVTs;
  2775. ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
  2776. SmallVector<EVT, 4> ValValueVTs;
  2777. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  2778. unsigned NumAggValues = AggValueVTs.size();
  2779. unsigned NumValValues = ValValueVTs.size();
  2780. SmallVector<SDValue, 4> Values(NumAggValues);
  2781. // Ignore an insertvalue that produces an empty object
  2782. if (!NumAggValues) {
  2783. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  2784. return;
  2785. }
  2786. SDValue Agg = getValue(Op0);
  2787. unsigned i = 0;
  2788. // Copy the beginning value(s) from the original aggregate.
  2789. for (; i != LinearIndex; ++i)
  2790. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2791. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2792. // Copy values from the inserted value(s).
  2793. if (NumValValues) {
  2794. SDValue Val = getValue(Op1);
  2795. for (; i != LinearIndex + NumValValues; ++i)
  2796. Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2797. SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
  2798. }
  2799. // Copy remaining value(s) from the original aggregate.
  2800. for (; i != NumAggValues; ++i)
  2801. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2802. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2803. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2804. DAG.getVTList(AggValueVTs), Values));
  2805. }
  2806. void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
  2807. const Value *Op0 = I.getOperand(0);
  2808. Type *AggTy = Op0->getType();
  2809. Type *ValTy = I.getType();
  2810. bool OutOfUndef = isa<UndefValue>(Op0);
  2811. unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
  2812. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2813. SmallVector<EVT, 4> ValValueVTs;
  2814. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  2815. unsigned NumValValues = ValValueVTs.size();
  2816. // Ignore a extractvalue that produces an empty object
  2817. if (!NumValValues) {
  2818. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  2819. return;
  2820. }
  2821. SmallVector<SDValue, 4> Values(NumValValues);
  2822. SDValue Agg = getValue(Op0);
  2823. // Copy out the selected value(s).
  2824. for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
  2825. Values[i - LinearIndex] =
  2826. OutOfUndef ?
  2827. DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
  2828. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2829. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2830. DAG.getVTList(ValValueVTs), Values));
  2831. }
  2832. void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
  2833. Value *Op0 = I.getOperand(0);
  2834. // Note that the pointer operand may be a vector of pointers. Take the scalar
  2835. // element which holds a pointer.
  2836. unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
  2837. SDValue N = getValue(Op0);
  2838. SDLoc dl = getCurSDLoc();
  2839. // Normalize Vector GEP - all scalar operands should be converted to the
  2840. // splat vector.
  2841. unsigned VectorWidth = I.getType()->isVectorTy() ?
  2842. cast<VectorType>(I.getType())->getVectorNumElements() : 0;
  2843. if (VectorWidth && !N.getValueType().isVector()) {
  2844. LLVMContext &Context = *DAG.getContext();
  2845. EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
  2846. SmallVector<SDValue, 16> Ops(VectorWidth, N);
  2847. N = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
  2848. }
  2849. for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
  2850. GTI != E; ++GTI) {
  2851. const Value *Idx = GTI.getOperand();
  2852. if (StructType *StTy = dyn_cast<StructType>(*GTI)) {
  2853. unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
  2854. if (Field) {
  2855. // N = N + Offset
  2856. uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
  2857. // In an inbouds GEP with an offset that is nonnegative even when
  2858. // interpreted as signed, assume there is no unsigned overflow.
  2859. SDNodeFlags Flags;
  2860. if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
  2861. Flags.setNoUnsignedWrap(true);
  2862. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
  2863. DAG.getConstant(Offset, dl, N.getValueType()), &Flags);
  2864. }
  2865. } else {
  2866. MVT PtrTy =
  2867. DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout(), AS);
  2868. unsigned PtrSize = PtrTy.getSizeInBits();
  2869. APInt ElementSize(PtrSize, DL->getTypeAllocSize(GTI.getIndexedType()));
  2870. // If this is a scalar constant or a splat vector of constants,
  2871. // handle it quickly.
  2872. const auto *CI = dyn_cast<ConstantInt>(Idx);
  2873. if (!CI && isa<ConstantDataVector>(Idx) &&
  2874. cast<ConstantDataVector>(Idx)->getSplatValue())
  2875. CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
  2876. if (CI) {
  2877. if (CI->isZero())
  2878. continue;
  2879. APInt Offs = ElementSize * CI->getValue().sextOrTrunc(PtrSize);
  2880. LLVMContext &Context = *DAG.getContext();
  2881. SDValue OffsVal = VectorWidth ?
  2882. DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, PtrTy, VectorWidth)) :
  2883. DAG.getConstant(Offs, dl, PtrTy);
  2884. // In an inbouds GEP with an offset that is nonnegative even when
  2885. // interpreted as signed, assume there is no unsigned overflow.
  2886. SDNodeFlags Flags;
  2887. if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
  2888. Flags.setNoUnsignedWrap(true);
  2889. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, &Flags);
  2890. continue;
  2891. }
  2892. // N = N + Idx * ElementSize;
  2893. SDValue IdxN = getValue(Idx);
  2894. if (!IdxN.getValueType().isVector() && VectorWidth) {
  2895. MVT VT = MVT::getVectorVT(IdxN.getValueType().getSimpleVT(), VectorWidth);
  2896. SmallVector<SDValue, 16> Ops(VectorWidth, IdxN);
  2897. IdxN = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
  2898. }
  2899. // If the index is smaller or larger than intptr_t, truncate or extend
  2900. // it.
  2901. IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
  2902. // If this is a multiply by a power of two, turn it into a shl
  2903. // immediately. This is a very common case.
  2904. if (ElementSize != 1) {
  2905. if (ElementSize.isPowerOf2()) {
  2906. unsigned Amt = ElementSize.logBase2();
  2907. IdxN = DAG.getNode(ISD::SHL, dl,
  2908. N.getValueType(), IdxN,
  2909. DAG.getConstant(Amt, dl, IdxN.getValueType()));
  2910. } else {
  2911. SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
  2912. IdxN = DAG.getNode(ISD::MUL, dl,
  2913. N.getValueType(), IdxN, Scale);
  2914. }
  2915. }
  2916. N = DAG.getNode(ISD::ADD, dl,
  2917. N.getValueType(), N, IdxN);
  2918. }
  2919. }
  2920. setValue(&I, N);
  2921. }
  2922. void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
  2923. // If this is a fixed sized alloca in the entry block of the function,
  2924. // allocate it statically on the stack.
  2925. if (FuncInfo.StaticAllocaMap.count(&I))
  2926. return; // getValue will auto-populate this.
  2927. SDLoc dl = getCurSDLoc();
  2928. Type *Ty = I.getAllocatedType();
  2929. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2930. auto &DL = DAG.getDataLayout();
  2931. uint64_t TySize = DL.getTypeAllocSize(Ty);
  2932. unsigned Align =
  2933. std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
  2934. SDValue AllocSize = getValue(I.getArraySize());
  2935. EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout());
  2936. if (AllocSize.getValueType() != IntPtr)
  2937. AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
  2938. AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
  2939. AllocSize,
  2940. DAG.getConstant(TySize, dl, IntPtr));
  2941. // Handle alignment. If the requested alignment is less than or equal to
  2942. // the stack alignment, ignore it. If the size is greater than or equal to
  2943. // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
  2944. unsigned StackAlign =
  2945. DAG.getSubtarget().getFrameLowering()->getStackAlignment();
  2946. if (Align <= StackAlign)
  2947. Align = 0;
  2948. // Round the size of the allocation up to the stack alignment size
  2949. // by add SA-1 to the size. This doesn't overflow because we're computing
  2950. // an address inside an alloca.
  2951. SDNodeFlags Flags;
  2952. Flags.setNoUnsignedWrap(true);
  2953. AllocSize = DAG.getNode(ISD::ADD, dl,
  2954. AllocSize.getValueType(), AllocSize,
  2955. DAG.getIntPtrConstant(StackAlign - 1, dl), &Flags);
  2956. // Mask out the low bits for alignment purposes.
  2957. AllocSize = DAG.getNode(ISD::AND, dl,
  2958. AllocSize.getValueType(), AllocSize,
  2959. DAG.getIntPtrConstant(~(uint64_t)(StackAlign - 1),
  2960. dl));
  2961. SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align, dl) };
  2962. SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
  2963. SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
  2964. setValue(&I, DSA);
  2965. DAG.setRoot(DSA.getValue(1));
  2966. assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
  2967. }
  2968. void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
  2969. if (I.isAtomic())
  2970. return visitAtomicLoad(I);
  2971. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2972. const Value *SV = I.getOperand(0);
  2973. if (TLI.supportSwiftError()) {
  2974. // Swifterror values can come from either a function parameter with
  2975. // swifterror attribute or an alloca with swifterror attribute.
  2976. if (const Argument *Arg = dyn_cast<Argument>(SV)) {
  2977. if (Arg->hasSwiftErrorAttr())
  2978. return visitLoadFromSwiftError(I);
  2979. }
  2980. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
  2981. if (Alloca->isSwiftError())
  2982. return visitLoadFromSwiftError(I);
  2983. }
  2984. }
  2985. SDValue Ptr = getValue(SV);
  2986. Type *Ty = I.getType();
  2987. bool isVolatile = I.isVolatile();
  2988. bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
  2989. bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
  2990. bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout());
  2991. unsigned Alignment = I.getAlignment();
  2992. AAMDNodes AAInfo;
  2993. I.getAAMetadata(AAInfo);
  2994. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  2995. SmallVector<EVT, 4> ValueVTs;
  2996. SmallVector<uint64_t, 4> Offsets;
  2997. ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets);
  2998. unsigned NumValues = ValueVTs.size();
  2999. if (NumValues == 0)
  3000. return;
  3001. SDValue Root;
  3002. bool ConstantMemory = false;
  3003. if (isVolatile || NumValues > MaxParallelChains)
  3004. // Serialize volatile loads with other side effects.
  3005. Root = getRoot();
  3006. else if (AA->pointsToConstantMemory(MemoryLocation(
  3007. SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) {
  3008. // Do not serialize (non-volatile) loads of constant memory with anything.
  3009. Root = DAG.getEntryNode();
  3010. ConstantMemory = true;
  3011. } else {
  3012. // Do not serialize non-volatile loads against each other.
  3013. Root = DAG.getRoot();
  3014. }
  3015. SDLoc dl = getCurSDLoc();
  3016. if (isVolatile)
  3017. Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
  3018. // An aggregate load cannot wrap around the address space, so offsets to its
  3019. // parts don't wrap either.
  3020. SDNodeFlags Flags;
  3021. Flags.setNoUnsignedWrap(true);
  3022. SmallVector<SDValue, 4> Values(NumValues);
  3023. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3024. EVT PtrVT = Ptr.getValueType();
  3025. unsigned ChainI = 0;
  3026. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3027. // Serializing loads here may result in excessive register pressure, and
  3028. // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
  3029. // could recover a bit by hoisting nodes upward in the chain by recognizing
  3030. // they are side-effect free or do not alias. The optimizer should really
  3031. // avoid this case by converting large object/array copies to llvm.memcpy
  3032. // (MaxParallelChains should always remain as failsafe).
  3033. if (ChainI == MaxParallelChains) {
  3034. assert(PendingLoads.empty() && "PendingLoads must be serialized first");
  3035. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3036. makeArrayRef(Chains.data(), ChainI));
  3037. Root = Chain;
  3038. ChainI = 0;
  3039. }
  3040. SDValue A = DAG.getNode(ISD::ADD, dl,
  3041. PtrVT, Ptr,
  3042. DAG.getConstant(Offsets[i], dl, PtrVT),
  3043. &Flags);
  3044. auto MMOFlags = MachineMemOperand::MONone;
  3045. if (isVolatile)
  3046. MMOFlags |= MachineMemOperand::MOVolatile;
  3047. if (isNonTemporal)
  3048. MMOFlags |= MachineMemOperand::MONonTemporal;
  3049. if (isInvariant)
  3050. MMOFlags |= MachineMemOperand::MOInvariant;
  3051. if (isDereferenceable)
  3052. MMOFlags |= MachineMemOperand::MODereferenceable;
  3053. SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A,
  3054. MachinePointerInfo(SV, Offsets[i]), Alignment,
  3055. MMOFlags, AAInfo, Ranges);
  3056. Values[i] = L;
  3057. Chains[ChainI] = L.getValue(1);
  3058. }
  3059. if (!ConstantMemory) {
  3060. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3061. makeArrayRef(Chains.data(), ChainI));
  3062. if (isVolatile)
  3063. DAG.setRoot(Chain);
  3064. else
  3065. PendingLoads.push_back(Chain);
  3066. }
  3067. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
  3068. DAG.getVTList(ValueVTs), Values));
  3069. }
  3070. void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
  3071. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3072. assert(TLI.supportSwiftError() &&
  3073. "call visitStoreToSwiftError when backend supports swifterror");
  3074. SmallVector<EVT, 4> ValueVTs;
  3075. SmallVector<uint64_t, 4> Offsets;
  3076. const Value *SrcV = I.getOperand(0);
  3077. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3078. SrcV->getType(), ValueVTs, &Offsets);
  3079. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3080. "expect a single EVT for swifterror");
  3081. SDValue Src = getValue(SrcV);
  3082. // Create a virtual register, then update the virtual register.
  3083. auto &DL = DAG.getDataLayout();
  3084. const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy(DL));
  3085. unsigned VReg = FuncInfo.MF->getRegInfo().createVirtualRegister(RC);
  3086. // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
  3087. // Chain can be getRoot or getControlRoot.
  3088. SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
  3089. SDValue(Src.getNode(), Src.getResNo()));
  3090. DAG.setRoot(CopyNode);
  3091. FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg);
  3092. }
  3093. void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
  3094. assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
  3095. "call visitLoadFromSwiftError when backend supports swifterror");
  3096. assert(!I.isVolatile() &&
  3097. I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&
  3098. I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&
  3099. "Support volatile, non temporal, invariant for load_from_swift_error");
  3100. const Value *SV = I.getOperand(0);
  3101. Type *Ty = I.getType();
  3102. AAMDNodes AAInfo;
  3103. I.getAAMetadata(AAInfo);
  3104. assert(!AA->pointsToConstantMemory(MemoryLocation(
  3105. SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo)) &&
  3106. "load_from_swift_error should not be constant memory");
  3107. SmallVector<EVT, 4> ValueVTs;
  3108. SmallVector<uint64_t, 4> Offsets;
  3109. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
  3110. ValueVTs, &Offsets);
  3111. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3112. "expect a single EVT for swifterror");
  3113. // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
  3114. SDValue L = DAG.getCopyFromReg(
  3115. getRoot(), getCurSDLoc(),
  3116. FuncInfo.getOrCreateSwiftErrorVReg(FuncInfo.MBB, SV), ValueVTs[0]);
  3117. setValue(&I, L);
  3118. }
  3119. void SelectionDAGBuilder::visitStore(const StoreInst &I) {
  3120. if (I.isAtomic())
  3121. return visitAtomicStore(I);
  3122. const Value *SrcV = I.getOperand(0);
  3123. const Value *PtrV = I.getOperand(1);
  3124. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3125. if (TLI.supportSwiftError()) {
  3126. // Swifterror values can come from either a function parameter with
  3127. // swifterror attribute or an alloca with swifterror attribute.
  3128. if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
  3129. if (Arg->hasSwiftErrorAttr())
  3130. return visitStoreToSwiftError(I);
  3131. }
  3132. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
  3133. if (Alloca->isSwiftError())
  3134. return visitStoreToSwiftError(I);
  3135. }
  3136. }
  3137. SmallVector<EVT, 4> ValueVTs;
  3138. SmallVector<uint64_t, 4> Offsets;
  3139. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3140. SrcV->getType(), ValueVTs, &Offsets);
  3141. unsigned NumValues = ValueVTs.size();
  3142. if (NumValues == 0)
  3143. return;
  3144. // Get the lowered operands. Note that we do this after
  3145. // checking if NumResults is zero, because with zero results
  3146. // the operands won't have values in the map.
  3147. SDValue Src = getValue(SrcV);
  3148. SDValue Ptr = getValue(PtrV);
  3149. SDValue Root = getRoot();
  3150. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3151. SDLoc dl = getCurSDLoc();
  3152. EVT PtrVT = Ptr.getValueType();
  3153. unsigned Alignment = I.getAlignment();
  3154. AAMDNodes AAInfo;
  3155. I.getAAMetadata(AAInfo);
  3156. auto MMOFlags = MachineMemOperand::MONone;
  3157. if (I.isVolatile())
  3158. MMOFlags |= MachineMemOperand::MOVolatile;
  3159. if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
  3160. MMOFlags |= MachineMemOperand::MONonTemporal;
  3161. // An aggregate load cannot wrap around the address space, so offsets to its
  3162. // parts don't wrap either.
  3163. SDNodeFlags Flags;
  3164. Flags.setNoUnsignedWrap(true);
  3165. unsigned ChainI = 0;
  3166. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3167. // See visitLoad comments.
  3168. if (ChainI == MaxParallelChains) {
  3169. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3170. makeArrayRef(Chains.data(), ChainI));
  3171. Root = Chain;
  3172. ChainI = 0;
  3173. }
  3174. SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
  3175. DAG.getConstant(Offsets[i], dl, PtrVT), &Flags);
  3176. SDValue St = DAG.getStore(
  3177. Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add,
  3178. MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo);
  3179. Chains[ChainI] = St;
  3180. }
  3181. SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3182. makeArrayRef(Chains.data(), ChainI));
  3183. DAG.setRoot(StoreNode);
  3184. }
  3185. void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
  3186. bool IsCompressing) {
  3187. SDLoc sdl = getCurSDLoc();
  3188. auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3189. unsigned& Alignment) {
  3190. // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
  3191. Src0 = I.getArgOperand(0);
  3192. Ptr = I.getArgOperand(1);
  3193. Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
  3194. Mask = I.getArgOperand(3);
  3195. };
  3196. auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3197. unsigned& Alignment) {
  3198. // llvm.masked.compressstore.*(Src0, Ptr, Mask)
  3199. Src0 = I.getArgOperand(0);
  3200. Ptr = I.getArgOperand(1);
  3201. Mask = I.getArgOperand(2);
  3202. Alignment = 0;
  3203. };
  3204. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3205. unsigned Alignment;
  3206. if (IsCompressing)
  3207. getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3208. else
  3209. getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3210. SDValue Ptr = getValue(PtrOperand);
  3211. SDValue Src0 = getValue(Src0Operand);
  3212. SDValue Mask = getValue(MaskOperand);
  3213. EVT VT = Src0.getValueType();
  3214. if (!Alignment)
  3215. Alignment = DAG.getEVTAlignment(VT);
  3216. AAMDNodes AAInfo;
  3217. I.getAAMetadata(AAInfo);
  3218. MachineMemOperand *MMO =
  3219. DAG.getMachineFunction().
  3220. getMachineMemOperand(MachinePointerInfo(PtrOperand),
  3221. MachineMemOperand::MOStore, VT.getStoreSize(),
  3222. Alignment, AAInfo);
  3223. SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
  3224. MMO, false /* Truncating */,
  3225. IsCompressing);
  3226. DAG.setRoot(StoreNode);
  3227. setValue(&I, StoreNode);
  3228. }
  3229. // Get a uniform base for the Gather/Scatter intrinsic.
  3230. // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
  3231. // We try to represent it as a base pointer + vector of indices.
  3232. // Usually, the vector of pointers comes from a 'getelementptr' instruction.
  3233. // The first operand of the GEP may be a single pointer or a vector of pointers
  3234. // Example:
  3235. // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
  3236. // or
  3237. // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
  3238. // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
  3239. //
  3240. // When the first GEP operand is a single pointer - it is the uniform base we
  3241. // are looking for. If first operand of the GEP is a splat vector - we
  3242. // extract the spalt value and use it as a uniform base.
  3243. // In all other cases the function returns 'false'.
  3244. //
  3245. static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index,
  3246. SelectionDAGBuilder* SDB) {
  3247. SelectionDAG& DAG = SDB->DAG;
  3248. LLVMContext &Context = *DAG.getContext();
  3249. assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
  3250. const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
  3251. if (!GEP || GEP->getNumOperands() > 2)
  3252. return false;
  3253. const Value *GEPPtr = GEP->getPointerOperand();
  3254. if (!GEPPtr->getType()->isVectorTy())
  3255. Ptr = GEPPtr;
  3256. else if (!(Ptr = getSplatValue(GEPPtr)))
  3257. return false;
  3258. Value *IndexVal = GEP->getOperand(1);
  3259. // The operands of the GEP may be defined in another basic block.
  3260. // In this case we'll not find nodes for the operands.
  3261. if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
  3262. return false;
  3263. Base = SDB->getValue(Ptr);
  3264. Index = SDB->getValue(IndexVal);
  3265. // Suppress sign extension.
  3266. if (SExtInst* Sext = dyn_cast<SExtInst>(IndexVal)) {
  3267. if (SDB->findValue(Sext->getOperand(0))) {
  3268. IndexVal = Sext->getOperand(0);
  3269. Index = SDB->getValue(IndexVal);
  3270. }
  3271. }
  3272. if (!Index.getValueType().isVector()) {
  3273. unsigned GEPWidth = GEP->getType()->getVectorNumElements();
  3274. EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
  3275. SmallVector<SDValue, 16> Ops(GEPWidth, Index);
  3276. Index = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Index), VT, Ops);
  3277. }
  3278. return true;
  3279. }
  3280. void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
  3281. SDLoc sdl = getCurSDLoc();
  3282. // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
  3283. const Value *Ptr = I.getArgOperand(1);
  3284. SDValue Src0 = getValue(I.getArgOperand(0));
  3285. SDValue Mask = getValue(I.getArgOperand(3));
  3286. EVT VT = Src0.getValueType();
  3287. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
  3288. if (!Alignment)
  3289. Alignment = DAG.getEVTAlignment(VT);
  3290. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3291. AAMDNodes AAInfo;
  3292. I.getAAMetadata(AAInfo);
  3293. SDValue Base;
  3294. SDValue Index;
  3295. const Value *BasePtr = Ptr;
  3296. bool UniformBase = getUniformBase(BasePtr, Base, Index, this);
  3297. const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
  3298. MachineMemOperand *MMO = DAG.getMachineFunction().
  3299. getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
  3300. MachineMemOperand::MOStore, VT.getStoreSize(),
  3301. Alignment, AAInfo);
  3302. if (!UniformBase) {
  3303. Base = DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3304. Index = getValue(Ptr);
  3305. }
  3306. SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index };
  3307. SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
  3308. Ops, MMO);
  3309. DAG.setRoot(Scatter);
  3310. setValue(&I, Scatter);
  3311. }
  3312. void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
  3313. SDLoc sdl = getCurSDLoc();
  3314. auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3315. unsigned& Alignment) {
  3316. // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
  3317. Ptr = I.getArgOperand(0);
  3318. Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  3319. Mask = I.getArgOperand(2);
  3320. Src0 = I.getArgOperand(3);
  3321. };
  3322. auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3323. unsigned& Alignment) {
  3324. // @llvm.masked.expandload.*(Ptr, Mask, Src0)
  3325. Ptr = I.getArgOperand(0);
  3326. Alignment = 0;
  3327. Mask = I.getArgOperand(1);
  3328. Src0 = I.getArgOperand(2);
  3329. };
  3330. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3331. unsigned Alignment;
  3332. if (IsExpanding)
  3333. getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3334. else
  3335. getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3336. SDValue Ptr = getValue(PtrOperand);
  3337. SDValue Src0 = getValue(Src0Operand);
  3338. SDValue Mask = getValue(MaskOperand);
  3339. EVT VT = Src0.getValueType();
  3340. if (!Alignment)
  3341. Alignment = DAG.getEVTAlignment(VT);
  3342. AAMDNodes AAInfo;
  3343. I.getAAMetadata(AAInfo);
  3344. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3345. // Do not serialize masked loads of constant memory with anything.
  3346. bool AddToChain = !AA->pointsToConstantMemory(MemoryLocation(
  3347. PtrOperand, DAG.getDataLayout().getTypeStoreSize(I.getType()), AAInfo));
  3348. SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
  3349. MachineMemOperand *MMO =
  3350. DAG.getMachineFunction().
  3351. getMachineMemOperand(MachinePointerInfo(PtrOperand),
  3352. MachineMemOperand::MOLoad, VT.getStoreSize(),
  3353. Alignment, AAInfo, Ranges);
  3354. SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
  3355. ISD::NON_EXTLOAD, IsExpanding);
  3356. if (AddToChain) {
  3357. SDValue OutChain = Load.getValue(1);
  3358. DAG.setRoot(OutChain);
  3359. }
  3360. setValue(&I, Load);
  3361. }
  3362. void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
  3363. SDLoc sdl = getCurSDLoc();
  3364. // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
  3365. const Value *Ptr = I.getArgOperand(0);
  3366. SDValue Src0 = getValue(I.getArgOperand(3));
  3367. SDValue Mask = getValue(I.getArgOperand(2));
  3368. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3369. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3370. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
  3371. if (!Alignment)
  3372. Alignment = DAG.getEVTAlignment(VT);
  3373. AAMDNodes AAInfo;
  3374. I.getAAMetadata(AAInfo);
  3375. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3376. SDValue Root = DAG.getRoot();
  3377. SDValue Base;
  3378. SDValue Index;
  3379. const Value *BasePtr = Ptr;
  3380. bool UniformBase = getUniformBase(BasePtr, Base, Index, this);
  3381. bool ConstantMemory = false;
  3382. if (UniformBase &&
  3383. AA->pointsToConstantMemory(MemoryLocation(
  3384. BasePtr, DAG.getDataLayout().getTypeStoreSize(I.getType()),
  3385. AAInfo))) {
  3386. // Do not serialize (non-volatile) loads of constant memory with anything.
  3387. Root = DAG.getEntryNode();
  3388. ConstantMemory = true;
  3389. }
  3390. MachineMemOperand *MMO =
  3391. DAG.getMachineFunction().
  3392. getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
  3393. MachineMemOperand::MOLoad, VT.getStoreSize(),
  3394. Alignment, AAInfo, Ranges);
  3395. if (!UniformBase) {
  3396. Base = DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3397. Index = getValue(Ptr);
  3398. }
  3399. SDValue Ops[] = { Root, Src0, Mask, Base, Index };
  3400. SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
  3401. Ops, MMO);
  3402. SDValue OutChain = Gather.getValue(1);
  3403. if (!ConstantMemory)
  3404. PendingLoads.push_back(OutChain);
  3405. setValue(&I, Gather);
  3406. }
  3407. void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
  3408. SDLoc dl = getCurSDLoc();
  3409. AtomicOrdering SuccessOrder = I.getSuccessOrdering();
  3410. AtomicOrdering FailureOrder = I.getFailureOrdering();
  3411. SynchronizationScope Scope = I.getSynchScope();
  3412. SDValue InChain = getRoot();
  3413. MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
  3414. SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
  3415. SDValue L = DAG.getAtomicCmpSwap(
  3416. ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
  3417. getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
  3418. getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
  3419. /*Alignment=*/ 0, SuccessOrder, FailureOrder, Scope);
  3420. SDValue OutChain = L.getValue(2);
  3421. setValue(&I, L);
  3422. DAG.setRoot(OutChain);
  3423. }
  3424. void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
  3425. SDLoc dl = getCurSDLoc();
  3426. ISD::NodeType NT;
  3427. switch (I.getOperation()) {
  3428. default: llvm_unreachable("Unknown atomicrmw operation");
  3429. case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
  3430. case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
  3431. case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
  3432. case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
  3433. case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
  3434. case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
  3435. case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
  3436. case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
  3437. case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
  3438. case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
  3439. case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
  3440. }
  3441. AtomicOrdering Order = I.getOrdering();
  3442. SynchronizationScope Scope = I.getSynchScope();
  3443. SDValue InChain = getRoot();
  3444. SDValue L =
  3445. DAG.getAtomic(NT, dl,
  3446. getValue(I.getValOperand()).getSimpleValueType(),
  3447. InChain,
  3448. getValue(I.getPointerOperand()),
  3449. getValue(I.getValOperand()),
  3450. I.getPointerOperand(),
  3451. /* Alignment=*/ 0, Order, Scope);
  3452. SDValue OutChain = L.getValue(1);
  3453. setValue(&I, L);
  3454. DAG.setRoot(OutChain);
  3455. }
  3456. void SelectionDAGBuilder::visitFence(const FenceInst &I) {
  3457. SDLoc dl = getCurSDLoc();
  3458. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3459. SDValue Ops[3];
  3460. Ops[0] = getRoot();
  3461. Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
  3462. TLI.getPointerTy(DAG.getDataLayout()));
  3463. Ops[2] = DAG.getConstant(I.getSynchScope(), dl,
  3464. TLI.getPointerTy(DAG.getDataLayout()));
  3465. DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
  3466. }
  3467. void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
  3468. SDLoc dl = getCurSDLoc();
  3469. AtomicOrdering Order = I.getOrdering();
  3470. SynchronizationScope Scope = I.getSynchScope();
  3471. SDValue InChain = getRoot();
  3472. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3473. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3474. if (I.getAlignment() < VT.getSizeInBits() / 8)
  3475. report_fatal_error("Cannot generate unaligned atomic load");
  3476. MachineMemOperand *MMO =
  3477. DAG.getMachineFunction().
  3478. getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
  3479. MachineMemOperand::MOVolatile |
  3480. MachineMemOperand::MOLoad,
  3481. VT.getStoreSize(),
  3482. I.getAlignment() ? I.getAlignment() :
  3483. DAG.getEVTAlignment(VT),
  3484. AAMDNodes(), nullptr, Scope, Order);
  3485. InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
  3486. SDValue L =
  3487. DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
  3488. getValue(I.getPointerOperand()), MMO);
  3489. SDValue OutChain = L.getValue(1);
  3490. setValue(&I, L);
  3491. DAG.setRoot(OutChain);
  3492. }
  3493. void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
  3494. SDLoc dl = getCurSDLoc();
  3495. AtomicOrdering Order = I.getOrdering();
  3496. SynchronizationScope Scope = I.getSynchScope();
  3497. SDValue InChain = getRoot();
  3498. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3499. EVT VT =
  3500. TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
  3501. if (I.getAlignment() < VT.getSizeInBits() / 8)
  3502. report_fatal_error("Cannot generate unaligned atomic store");
  3503. SDValue OutChain =
  3504. DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
  3505. InChain,
  3506. getValue(I.getPointerOperand()),
  3507. getValue(I.getValueOperand()),
  3508. I.getPointerOperand(), I.getAlignment(),
  3509. Order, Scope);
  3510. DAG.setRoot(OutChain);
  3511. }
  3512. /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
  3513. /// node.
  3514. void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
  3515. unsigned Intrinsic) {
  3516. // Ignore the callsite's attributes. A specific call site may be marked with
  3517. // readnone, but the lowering code will expect the chain based on the
  3518. // definition.
  3519. const Function *F = I.getCalledFunction();
  3520. bool HasChain = !F->doesNotAccessMemory();
  3521. bool OnlyLoad = HasChain && F->onlyReadsMemory();
  3522. // Build the operand list.
  3523. SmallVector<SDValue, 8> Ops;
  3524. if (HasChain) { // If this intrinsic has side-effects, chainify it.
  3525. if (OnlyLoad) {
  3526. // We don't need to serialize loads against other loads.
  3527. Ops.push_back(DAG.getRoot());
  3528. } else {
  3529. Ops.push_back(getRoot());
  3530. }
  3531. }
  3532. // Info is set by getTgtMemInstrinsic
  3533. TargetLowering::IntrinsicInfo Info;
  3534. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3535. bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
  3536. // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
  3537. if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
  3538. Info.opc == ISD::INTRINSIC_W_CHAIN)
  3539. Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
  3540. TLI.getPointerTy(DAG.getDataLayout())));
  3541. // Add all operands of the call to the operand list.
  3542. for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
  3543. SDValue Op = getValue(I.getArgOperand(i));
  3544. Ops.push_back(Op);
  3545. }
  3546. SmallVector<EVT, 4> ValueVTs;
  3547. ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
  3548. if (HasChain)
  3549. ValueVTs.push_back(MVT::Other);
  3550. SDVTList VTs = DAG.getVTList(ValueVTs);
  3551. // Create the node.
  3552. SDValue Result;
  3553. if (IsTgtIntrinsic) {
  3554. // This is target intrinsic that touches memory
  3555. Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(),
  3556. VTs, Ops, Info.memVT,
  3557. MachinePointerInfo(Info.ptrVal, Info.offset),
  3558. Info.align, Info.vol,
  3559. Info.readMem, Info.writeMem, Info.size);
  3560. } else if (!HasChain) {
  3561. Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
  3562. } else if (!I.getType()->isVoidTy()) {
  3563. Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
  3564. } else {
  3565. Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
  3566. }
  3567. if (HasChain) {
  3568. SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
  3569. if (OnlyLoad)
  3570. PendingLoads.push_back(Chain);
  3571. else
  3572. DAG.setRoot(Chain);
  3573. }
  3574. if (!I.getType()->isVoidTy()) {
  3575. if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
  3576. EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
  3577. Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
  3578. } else
  3579. Result = lowerRangeToAssertZExt(DAG, I, Result);
  3580. setValue(&I, Result);
  3581. }
  3582. }
  3583. /// GetSignificand - Get the significand and build it into a floating-point
  3584. /// number with exponent of 1:
  3585. ///
  3586. /// Op = (Op & 0x007fffff) | 0x3f800000;
  3587. ///
  3588. /// where Op is the hexadecimal representation of floating point value.
  3589. static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
  3590. SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  3591. DAG.getConstant(0x007fffff, dl, MVT::i32));
  3592. SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
  3593. DAG.getConstant(0x3f800000, dl, MVT::i32));
  3594. return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
  3595. }
  3596. /// GetExponent - Get the exponent:
  3597. ///
  3598. /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
  3599. ///
  3600. /// where Op is the hexadecimal representation of floating point value.
  3601. static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
  3602. const TargetLowering &TLI, const SDLoc &dl) {
  3603. SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  3604. DAG.getConstant(0x7f800000, dl, MVT::i32));
  3605. SDValue t1 = DAG.getNode(
  3606. ISD::SRL, dl, MVT::i32, t0,
  3607. DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
  3608. SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
  3609. DAG.getConstant(127, dl, MVT::i32));
  3610. return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
  3611. }
  3612. /// getF32Constant - Get 32-bit floating point constant.
  3613. static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
  3614. const SDLoc &dl) {
  3615. return DAG.getConstantFP(APFloat(APFloat::IEEEsingle, APInt(32, Flt)), dl,
  3616. MVT::f32);
  3617. }
  3618. static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
  3619. SelectionDAG &DAG) {
  3620. // TODO: What fast-math-flags should be set on the floating-point nodes?
  3621. // IntegerPartOfX = ((int32_t)(t0);
  3622. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
  3623. // FractionalPartOfX = t0 - (float)IntegerPartOfX;
  3624. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  3625. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
  3626. // IntegerPartOfX <<= 23;
  3627. IntegerPartOfX = DAG.getNode(
  3628. ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  3629. DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
  3630. DAG.getDataLayout())));
  3631. SDValue TwoToFractionalPartOfX;
  3632. if (LimitFloatPrecision <= 6) {
  3633. // For floating-point precision of 6:
  3634. //
  3635. // TwoToFractionalPartOfX =
  3636. // 0.997535578f +
  3637. // (0.735607626f + 0.252464424f * x) * x;
  3638. //
  3639. // error 0.0144103317, which is 6 bits
  3640. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3641. getF32Constant(DAG, 0x3e814304, dl));
  3642. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3643. getF32Constant(DAG, 0x3f3c50c8, dl));
  3644. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3645. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3646. getF32Constant(DAG, 0x3f7f5e7e, dl));
  3647. } else if (LimitFloatPrecision <= 12) {
  3648. // For floating-point precision of 12:
  3649. //
  3650. // TwoToFractionalPartOfX =
  3651. // 0.999892986f +
  3652. // (0.696457318f +
  3653. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  3654. //
  3655. // error 0.000107046256, which is 13 to 14 bits
  3656. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3657. getF32Constant(DAG, 0x3da235e3, dl));
  3658. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3659. getF32Constant(DAG, 0x3e65b8f3, dl));
  3660. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3661. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3662. getF32Constant(DAG, 0x3f324b07, dl));
  3663. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3664. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3665. getF32Constant(DAG, 0x3f7ff8fd, dl));
  3666. } else { // LimitFloatPrecision <= 18
  3667. // For floating-point precision of 18:
  3668. //
  3669. // TwoToFractionalPartOfX =
  3670. // 0.999999982f +
  3671. // (0.693148872f +
  3672. // (0.240227044f +
  3673. // (0.554906021e-1f +
  3674. // (0.961591928e-2f +
  3675. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  3676. // error 2.47208000*10^(-7), which is better than 18 bits
  3677. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3678. getF32Constant(DAG, 0x3924b03e, dl));
  3679. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3680. getF32Constant(DAG, 0x3ab24b87, dl));
  3681. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3682. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3683. getF32Constant(DAG, 0x3c1d8c17, dl));
  3684. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3685. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3686. getF32Constant(DAG, 0x3d634a1d, dl));
  3687. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3688. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3689. getF32Constant(DAG, 0x3e75fe14, dl));
  3690. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3691. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  3692. getF32Constant(DAG, 0x3f317234, dl));
  3693. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  3694. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  3695. getF32Constant(DAG, 0x3f800000, dl));
  3696. }
  3697. // Add the exponent into the result in integer domain.
  3698. SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
  3699. return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
  3700. DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
  3701. }
  3702. /// expandExp - Lower an exp intrinsic. Handles the special sequences for
  3703. /// limited-precision mode.
  3704. static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  3705. const TargetLowering &TLI) {
  3706. if (Op.getValueType() == MVT::f32 &&
  3707. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3708. // Put the exponent in the right bit position for later addition to the
  3709. // final result:
  3710. //
  3711. // #define LOG2OFe 1.4426950f
  3712. // t0 = Op * LOG2OFe
  3713. // TODO: What fast-math-flags should be set here?
  3714. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
  3715. getF32Constant(DAG, 0x3fb8aa3b, dl));
  3716. return getLimitedPrecisionExp2(t0, dl, DAG);
  3717. }
  3718. // No special expansion.
  3719. return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
  3720. }
  3721. /// expandLog - Lower a log intrinsic. Handles the special sequences for
  3722. /// limited-precision mode.
  3723. static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  3724. const TargetLowering &TLI) {
  3725. // TODO: What fast-math-flags should be set on the floating-point nodes?
  3726. if (Op.getValueType() == MVT::f32 &&
  3727. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3728. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  3729. // Scale the exponent by log(2) [0.69314718f].
  3730. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  3731. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  3732. getF32Constant(DAG, 0x3f317218, dl));
  3733. // Get the significand and build it into a floating-point number with
  3734. // exponent of 1.
  3735. SDValue X = GetSignificand(DAG, Op1, dl);
  3736. SDValue LogOfMantissa;
  3737. if (LimitFloatPrecision <= 6) {
  3738. // For floating-point precision of 6:
  3739. //
  3740. // LogofMantissa =
  3741. // -1.1609546f +
  3742. // (1.4034025f - 0.23903021f * x) * x;
  3743. //
  3744. // error 0.0034276066, which is better than 8 bits
  3745. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3746. getF32Constant(DAG, 0xbe74c456, dl));
  3747. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3748. getF32Constant(DAG, 0x3fb3a2b1, dl));
  3749. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3750. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3751. getF32Constant(DAG, 0x3f949a29, dl));
  3752. } else if (LimitFloatPrecision <= 12) {
  3753. // For floating-point precision of 12:
  3754. //
  3755. // LogOfMantissa =
  3756. // -1.7417939f +
  3757. // (2.8212026f +
  3758. // (-1.4699568f +
  3759. // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
  3760. //
  3761. // error 0.000061011436, which is 14 bits
  3762. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3763. getF32Constant(DAG, 0xbd67b6d6, dl));
  3764. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3765. getF32Constant(DAG, 0x3ee4f4b8, dl));
  3766. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3767. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3768. getF32Constant(DAG, 0x3fbc278b, dl));
  3769. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3770. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3771. getF32Constant(DAG, 0x40348e95, dl));
  3772. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3773. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3774. getF32Constant(DAG, 0x3fdef31a, dl));
  3775. } else { // LimitFloatPrecision <= 18
  3776. // For floating-point precision of 18:
  3777. //
  3778. // LogOfMantissa =
  3779. // -2.1072184f +
  3780. // (4.2372794f +
  3781. // (-3.7029485f +
  3782. // (2.2781945f +
  3783. // (-0.87823314f +
  3784. // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
  3785. //
  3786. // error 0.0000023660568, which is better than 18 bits
  3787. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3788. getF32Constant(DAG, 0xbc91e5ac, dl));
  3789. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3790. getF32Constant(DAG, 0x3e4350aa, dl));
  3791. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3792. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3793. getF32Constant(DAG, 0x3f60d3e3, dl));
  3794. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3795. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3796. getF32Constant(DAG, 0x4011cdf0, dl));
  3797. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3798. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3799. getF32Constant(DAG, 0x406cfd1c, dl));
  3800. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3801. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3802. getF32Constant(DAG, 0x408797cb, dl));
  3803. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3804. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  3805. getF32Constant(DAG, 0x4006dcab, dl));
  3806. }
  3807. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
  3808. }
  3809. // No special expansion.
  3810. return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
  3811. }
  3812. /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
  3813. /// limited-precision mode.
  3814. static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  3815. const TargetLowering &TLI) {
  3816. // TODO: What fast-math-flags should be set on the floating-point nodes?
  3817. if (Op.getValueType() == MVT::f32 &&
  3818. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3819. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  3820. // Get the exponent.
  3821. SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
  3822. // Get the significand and build it into a floating-point number with
  3823. // exponent of 1.
  3824. SDValue X = GetSignificand(DAG, Op1, dl);
  3825. // Different possible minimax approximations of significand in
  3826. // floating-point for various degrees of accuracy over [1,2].
  3827. SDValue Log2ofMantissa;
  3828. if (LimitFloatPrecision <= 6) {
  3829. // For floating-point precision of 6:
  3830. //
  3831. // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
  3832. //
  3833. // error 0.0049451742, which is more than 7 bits
  3834. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3835. getF32Constant(DAG, 0xbeb08fe0, dl));
  3836. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3837. getF32Constant(DAG, 0x40019463, dl));
  3838. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3839. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3840. getF32Constant(DAG, 0x3fd6633d, dl));
  3841. } else if (LimitFloatPrecision <= 12) {
  3842. // For floating-point precision of 12:
  3843. //
  3844. // Log2ofMantissa =
  3845. // -2.51285454f +
  3846. // (4.07009056f +
  3847. // (-2.12067489f +
  3848. // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
  3849. //
  3850. // error 0.0000876136000, which is better than 13 bits
  3851. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3852. getF32Constant(DAG, 0xbda7262e, dl));
  3853. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3854. getF32Constant(DAG, 0x3f25280b, dl));
  3855. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3856. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3857. getF32Constant(DAG, 0x4007b923, dl));
  3858. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3859. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3860. getF32Constant(DAG, 0x40823e2f, dl));
  3861. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3862. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3863. getF32Constant(DAG, 0x4020d29c, dl));
  3864. } else { // LimitFloatPrecision <= 18
  3865. // For floating-point precision of 18:
  3866. //
  3867. // Log2ofMantissa =
  3868. // -3.0400495f +
  3869. // (6.1129976f +
  3870. // (-5.3420409f +
  3871. // (3.2865683f +
  3872. // (-1.2669343f +
  3873. // (0.27515199f -
  3874. // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
  3875. //
  3876. // error 0.0000018516, which is better than 18 bits
  3877. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3878. getF32Constant(DAG, 0xbcd2769e, dl));
  3879. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3880. getF32Constant(DAG, 0x3e8ce0b9, dl));
  3881. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3882. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3883. getF32Constant(DAG, 0x3fa22ae7, dl));
  3884. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3885. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3886. getF32Constant(DAG, 0x40525723, dl));
  3887. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3888. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3889. getF32Constant(DAG, 0x40aaf200, dl));
  3890. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3891. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3892. getF32Constant(DAG, 0x40c39dad, dl));
  3893. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3894. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  3895. getF32Constant(DAG, 0x4042902c, dl));
  3896. }
  3897. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
  3898. }
  3899. // No special expansion.
  3900. return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
  3901. }
  3902. /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
  3903. /// limited-precision mode.
  3904. static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  3905. const TargetLowering &TLI) {
  3906. // TODO: What fast-math-flags should be set on the floating-point nodes?
  3907. if (Op.getValueType() == MVT::f32 &&
  3908. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3909. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  3910. // Scale the exponent by log10(2) [0.30102999f].
  3911. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  3912. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  3913. getF32Constant(DAG, 0x3e9a209a, dl));
  3914. // Get the significand and build it into a floating-point number with
  3915. // exponent of 1.
  3916. SDValue X = GetSignificand(DAG, Op1, dl);
  3917. SDValue Log10ofMantissa;
  3918. if (LimitFloatPrecision <= 6) {
  3919. // For floating-point precision of 6:
  3920. //
  3921. // Log10ofMantissa =
  3922. // -0.50419619f +
  3923. // (0.60948995f - 0.10380950f * x) * x;
  3924. //
  3925. // error 0.0014886165, which is 6 bits
  3926. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3927. getF32Constant(DAG, 0xbdd49a13, dl));
  3928. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3929. getF32Constant(DAG, 0x3f1c0789, dl));
  3930. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3931. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3932. getF32Constant(DAG, 0x3f011300, dl));
  3933. } else if (LimitFloatPrecision <= 12) {
  3934. // For floating-point precision of 12:
  3935. //
  3936. // Log10ofMantissa =
  3937. // -0.64831180f +
  3938. // (0.91751397f +
  3939. // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
  3940. //
  3941. // error 0.00019228036, which is better than 12 bits
  3942. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3943. getF32Constant(DAG, 0x3d431f31, dl));
  3944. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  3945. getF32Constant(DAG, 0x3ea21fb2, dl));
  3946. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3947. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3948. getF32Constant(DAG, 0x3f6ae232, dl));
  3949. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3950. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  3951. getF32Constant(DAG, 0x3f25f7c3, dl));
  3952. } else { // LimitFloatPrecision <= 18
  3953. // For floating-point precision of 18:
  3954. //
  3955. // Log10ofMantissa =
  3956. // -0.84299375f +
  3957. // (1.5327582f +
  3958. // (-1.0688956f +
  3959. // (0.49102474f +
  3960. // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
  3961. //
  3962. // error 0.0000037995730, which is better than 18 bits
  3963. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3964. getF32Constant(DAG, 0x3c5d51ce, dl));
  3965. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  3966. getF32Constant(DAG, 0x3e00685a, dl));
  3967. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3968. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3969. getF32Constant(DAG, 0x3efb6798, dl));
  3970. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3971. SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  3972. getF32Constant(DAG, 0x3f88d192, dl));
  3973. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3974. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3975. getF32Constant(DAG, 0x3fc4316c, dl));
  3976. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3977. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
  3978. getF32Constant(DAG, 0x3f57ce70, dl));
  3979. }
  3980. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
  3981. }
  3982. // No special expansion.
  3983. return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
  3984. }
  3985. /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
  3986. /// limited-precision mode.
  3987. static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  3988. const TargetLowering &TLI) {
  3989. if (Op.getValueType() == MVT::f32 &&
  3990. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
  3991. return getLimitedPrecisionExp2(Op, dl, DAG);
  3992. // No special expansion.
  3993. return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
  3994. }
  3995. /// visitPow - Lower a pow intrinsic. Handles the special sequences for
  3996. /// limited-precision mode with x == 10.0f.
  3997. static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
  3998. SelectionDAG &DAG, const TargetLowering &TLI) {
  3999. bool IsExp10 = false;
  4000. if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
  4001. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4002. if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
  4003. APFloat Ten(10.0f);
  4004. IsExp10 = LHSC->isExactlyValue(Ten);
  4005. }
  4006. }
  4007. // TODO: What fast-math-flags should be set on the FMUL node?
  4008. if (IsExp10) {
  4009. // Put the exponent in the right bit position for later addition to the
  4010. // final result:
  4011. //
  4012. // #define LOG2OF10 3.3219281f
  4013. // t0 = Op * LOG2OF10;
  4014. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
  4015. getF32Constant(DAG, 0x40549a78, dl));
  4016. return getLimitedPrecisionExp2(t0, dl, DAG);
  4017. }
  4018. // No special expansion.
  4019. return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
  4020. }
  4021. /// ExpandPowI - Expand a llvm.powi intrinsic.
  4022. static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
  4023. SelectionDAG &DAG) {
  4024. // If RHS is a constant, we can expand this out to a multiplication tree,
  4025. // otherwise we end up lowering to a call to __powidf2 (for example). When
  4026. // optimizing for size, we only want to do this if the expansion would produce
  4027. // a small number of multiplies, otherwise we do the full expansion.
  4028. if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
  4029. // Get the exponent as a positive value.
  4030. unsigned Val = RHSC->getSExtValue();
  4031. if ((int)Val < 0) Val = -Val;
  4032. // powi(x, 0) -> 1.0
  4033. if (Val == 0)
  4034. return DAG.getConstantFP(1.0, DL, LHS.getValueType());
  4035. const Function *F = DAG.getMachineFunction().getFunction();
  4036. if (!F->optForSize() ||
  4037. // If optimizing for size, don't insert too many multiplies.
  4038. // This inserts up to 5 multiplies.
  4039. countPopulation(Val) + Log2_32(Val) < 7) {
  4040. // We use the simple binary decomposition method to generate the multiply
  4041. // sequence. There are more optimal ways to do this (for example,
  4042. // powi(x,15) generates one more multiply than it should), but this has
  4043. // the benefit of being both really simple and much better than a libcall.
  4044. SDValue Res; // Logically starts equal to 1.0
  4045. SDValue CurSquare = LHS;
  4046. // TODO: Intrinsics should have fast-math-flags that propagate to these
  4047. // nodes.
  4048. while (Val) {
  4049. if (Val & 1) {
  4050. if (Res.getNode())
  4051. Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
  4052. else
  4053. Res = CurSquare; // 1.0*CurSquare.
  4054. }
  4055. CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
  4056. CurSquare, CurSquare);
  4057. Val >>= 1;
  4058. }
  4059. // If the original was negative, invert the result, producing 1/(x*x*x).
  4060. if (RHSC->getSExtValue() < 0)
  4061. Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
  4062. DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
  4063. return Res;
  4064. }
  4065. }
  4066. // Otherwise, expand to a libcall.
  4067. return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
  4068. }
  4069. // getUnderlyingArgReg - Find underlying register used for a truncated or
  4070. // bitcasted argument.
  4071. static unsigned getUnderlyingArgReg(const SDValue &N) {
  4072. switch (N.getOpcode()) {
  4073. case ISD::CopyFromReg:
  4074. return cast<RegisterSDNode>(N.getOperand(1))->getReg();
  4075. case ISD::BITCAST:
  4076. case ISD::AssertZext:
  4077. case ISD::AssertSext:
  4078. case ISD::TRUNCATE:
  4079. return getUnderlyingArgReg(N.getOperand(0));
  4080. default:
  4081. return 0;
  4082. }
  4083. }
  4084. /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
  4085. /// argument, create the corresponding DBG_VALUE machine instruction for it now.
  4086. /// At the end of instruction selection, they will be inserted to the entry BB.
  4087. bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
  4088. const Value *V, DILocalVariable *Variable, DIExpression *Expr,
  4089. DILocation *DL, int64_t Offset, bool IsIndirect, const SDValue &N) {
  4090. const Argument *Arg = dyn_cast<Argument>(V);
  4091. if (!Arg)
  4092. return false;
  4093. MachineFunction &MF = DAG.getMachineFunction();
  4094. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  4095. // Ignore inlined function arguments here.
  4096. //
  4097. // FIXME: Should we be checking DL->inlinedAt() to determine this?
  4098. if (!Variable->getScope()->getSubprogram()->describes(MF.getFunction()))
  4099. return false;
  4100. Optional<MachineOperand> Op;
  4101. // Some arguments' frame index is recorded during argument lowering.
  4102. if (int FI = FuncInfo.getArgumentFrameIndex(Arg))
  4103. Op = MachineOperand::CreateFI(FI);
  4104. if (!Op && N.getNode()) {
  4105. unsigned Reg = getUnderlyingArgReg(N);
  4106. if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
  4107. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  4108. unsigned PR = RegInfo.getLiveInPhysReg(Reg);
  4109. if (PR)
  4110. Reg = PR;
  4111. }
  4112. if (Reg)
  4113. Op = MachineOperand::CreateReg(Reg, false);
  4114. }
  4115. if (!Op) {
  4116. // Check if ValueMap has reg number.
  4117. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  4118. if (VMI != FuncInfo.ValueMap.end())
  4119. Op = MachineOperand::CreateReg(VMI->second, false);
  4120. }
  4121. if (!Op && N.getNode())
  4122. // Check if frame index is available.
  4123. if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
  4124. if (FrameIndexSDNode *FINode =
  4125. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  4126. Op = MachineOperand::CreateFI(FINode->getIndex());
  4127. if (!Op)
  4128. return false;
  4129. assert(Variable->isValidLocationForIntrinsic(DL) &&
  4130. "Expected inlined-at fields to agree");
  4131. if (Op->isReg())
  4132. FuncInfo.ArgDbgValues.push_back(
  4133. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
  4134. Op->getReg(), Offset, Variable, Expr));
  4135. else
  4136. FuncInfo.ArgDbgValues.push_back(
  4137. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE))
  4138. .addOperand(*Op)
  4139. .addImm(Offset)
  4140. .addMetadata(Variable)
  4141. .addMetadata(Expr));
  4142. return true;
  4143. }
  4144. /// Return the appropriate SDDbgValue based on N.
  4145. SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
  4146. DILocalVariable *Variable,
  4147. DIExpression *Expr, int64_t Offset,
  4148. DebugLoc dl,
  4149. unsigned DbgSDNodeOrder) {
  4150. SDDbgValue *SDV;
  4151. auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode());
  4152. if (FISDN && Expr->startsWithDeref()) {
  4153. // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
  4154. // stack slot locations as such instead of as indirectly addressed
  4155. // locations.
  4156. ArrayRef<uint64_t> TrailingElements(Expr->elements_begin() + 1,
  4157. Expr->elements_end());
  4158. DIExpression *DerefedDIExpr =
  4159. DIExpression::get(*DAG.getContext(), TrailingElements);
  4160. int FI = FISDN->getIndex();
  4161. SDV = DAG.getFrameIndexDbgValue(Variable, DerefedDIExpr, FI, 0, dl,
  4162. DbgSDNodeOrder);
  4163. } else {
  4164. SDV = DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), false,
  4165. Offset, dl, DbgSDNodeOrder);
  4166. }
  4167. return SDV;
  4168. }
  4169. // VisualStudio defines setjmp as _setjmp
  4170. #if defined(_MSC_VER) && defined(setjmp) && \
  4171. !defined(setjmp_undefined_for_msvc)
  4172. # pragma push_macro("setjmp")
  4173. # undef setjmp
  4174. # define setjmp_undefined_for_msvc
  4175. #endif
  4176. /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
  4177. /// we want to emit this as a call to a named external function, return the name
  4178. /// otherwise lower it and return null.
  4179. const char *
  4180. SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
  4181. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4182. SDLoc sdl = getCurSDLoc();
  4183. DebugLoc dl = getCurDebugLoc();
  4184. SDValue Res;
  4185. switch (Intrinsic) {
  4186. default:
  4187. // By default, turn this into a target intrinsic node.
  4188. visitTargetIntrinsic(I, Intrinsic);
  4189. return nullptr;
  4190. case Intrinsic::vastart: visitVAStart(I); return nullptr;
  4191. case Intrinsic::vaend: visitVAEnd(I); return nullptr;
  4192. case Intrinsic::vacopy: visitVACopy(I); return nullptr;
  4193. case Intrinsic::returnaddress:
  4194. setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
  4195. TLI.getPointerTy(DAG.getDataLayout()),
  4196. getValue(I.getArgOperand(0))));
  4197. return nullptr;
  4198. case Intrinsic::addressofreturnaddress:
  4199. setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
  4200. TLI.getPointerTy(DAG.getDataLayout())));
  4201. return nullptr;
  4202. case Intrinsic::frameaddress:
  4203. setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
  4204. TLI.getPointerTy(DAG.getDataLayout()),
  4205. getValue(I.getArgOperand(0))));
  4206. return nullptr;
  4207. case Intrinsic::read_register: {
  4208. Value *Reg = I.getArgOperand(0);
  4209. SDValue Chain = getRoot();
  4210. SDValue RegName =
  4211. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  4212. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4213. Res = DAG.getNode(ISD::READ_REGISTER, sdl,
  4214. DAG.getVTList(VT, MVT::Other), Chain, RegName);
  4215. setValue(&I, Res);
  4216. DAG.setRoot(Res.getValue(1));
  4217. return nullptr;
  4218. }
  4219. case Intrinsic::write_register: {
  4220. Value *Reg = I.getArgOperand(0);
  4221. Value *RegValue = I.getArgOperand(1);
  4222. SDValue Chain = getRoot();
  4223. SDValue RegName =
  4224. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  4225. DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
  4226. RegName, getValue(RegValue)));
  4227. return nullptr;
  4228. }
  4229. case Intrinsic::setjmp:
  4230. return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
  4231. case Intrinsic::longjmp:
  4232. return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
  4233. case Intrinsic::memcpy: {
  4234. SDValue Op1 = getValue(I.getArgOperand(0));
  4235. SDValue Op2 = getValue(I.getArgOperand(1));
  4236. SDValue Op3 = getValue(I.getArgOperand(2));
  4237. unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
  4238. if (!Align)
  4239. Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment.
  4240. bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
  4241. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4242. SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4243. false, isTC,
  4244. MachinePointerInfo(I.getArgOperand(0)),
  4245. MachinePointerInfo(I.getArgOperand(1)));
  4246. updateDAGForMaybeTailCall(MC);
  4247. return nullptr;
  4248. }
  4249. case Intrinsic::memset: {
  4250. SDValue Op1 = getValue(I.getArgOperand(0));
  4251. SDValue Op2 = getValue(I.getArgOperand(1));
  4252. SDValue Op3 = getValue(I.getArgOperand(2));
  4253. unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
  4254. if (!Align)
  4255. Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment.
  4256. bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
  4257. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4258. SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4259. isTC, MachinePointerInfo(I.getArgOperand(0)));
  4260. updateDAGForMaybeTailCall(MS);
  4261. return nullptr;
  4262. }
  4263. case Intrinsic::memmove: {
  4264. SDValue Op1 = getValue(I.getArgOperand(0));
  4265. SDValue Op2 = getValue(I.getArgOperand(1));
  4266. SDValue Op3 = getValue(I.getArgOperand(2));
  4267. unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
  4268. if (!Align)
  4269. Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment.
  4270. bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
  4271. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4272. SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4273. isTC, MachinePointerInfo(I.getArgOperand(0)),
  4274. MachinePointerInfo(I.getArgOperand(1)));
  4275. updateDAGForMaybeTailCall(MM);
  4276. return nullptr;
  4277. }
  4278. case Intrinsic::dbg_declare: {
  4279. const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
  4280. DILocalVariable *Variable = DI.getVariable();
  4281. DIExpression *Expression = DI.getExpression();
  4282. const Value *Address = DI.getAddress();
  4283. assert(Variable && "Missing variable");
  4284. if (!Address) {
  4285. DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  4286. return nullptr;
  4287. }
  4288. // Check if address has undef value.
  4289. if (isa<UndefValue>(Address) ||
  4290. (Address->use_empty() && !isa<Argument>(Address))) {
  4291. DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  4292. return nullptr;
  4293. }
  4294. SDValue &N = NodeMap[Address];
  4295. if (!N.getNode() && isa<Argument>(Address))
  4296. // Check unused arguments map.
  4297. N = UnusedArgNodeMap[Address];
  4298. SDDbgValue *SDV;
  4299. if (N.getNode()) {
  4300. if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
  4301. Address = BCI->getOperand(0);
  4302. // Parameters are handled specially.
  4303. bool isParameter = Variable->isParameter() || isa<Argument>(Address);
  4304. auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
  4305. if (isParameter && FINode) {
  4306. // Byval parameter. We have a frame index at this point.
  4307. SDV = DAG.getFrameIndexDbgValue(Variable, Expression,
  4308. FINode->getIndex(), 0, dl, SDNodeOrder);
  4309. } else if (isa<Argument>(Address)) {
  4310. // Address is an argument, so try to emit its dbg value using
  4311. // virtual register info from the FuncInfo.ValueMap.
  4312. EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 0, false,
  4313. N);
  4314. return nullptr;
  4315. } else {
  4316. SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
  4317. true, 0, dl, SDNodeOrder);
  4318. }
  4319. DAG.AddDbgValue(SDV, N.getNode(), isParameter);
  4320. } else {
  4321. // If Address is an argument then try to emit its dbg value using
  4322. // virtual register info from the FuncInfo.ValueMap.
  4323. if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 0, false,
  4324. N)) {
  4325. // If variable is pinned by a alloca in dominating bb then
  4326. // use StaticAllocaMap.
  4327. if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
  4328. if (AI->getParent() != DI.getParent()) {
  4329. DenseMap<const AllocaInst*, int>::iterator SI =
  4330. FuncInfo.StaticAllocaMap.find(AI);
  4331. if (SI != FuncInfo.StaticAllocaMap.end()) {
  4332. SDV = DAG.getFrameIndexDbgValue(Variable, Expression, SI->second,
  4333. 0, dl, SDNodeOrder);
  4334. DAG.AddDbgValue(SDV, nullptr, false);
  4335. return nullptr;
  4336. }
  4337. }
  4338. }
  4339. DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  4340. }
  4341. }
  4342. return nullptr;
  4343. }
  4344. case Intrinsic::dbg_value: {
  4345. const DbgValueInst &DI = cast<DbgValueInst>(I);
  4346. assert(DI.getVariable() && "Missing variable");
  4347. DILocalVariable *Variable = DI.getVariable();
  4348. DIExpression *Expression = DI.getExpression();
  4349. uint64_t Offset = DI.getOffset();
  4350. const Value *V = DI.getValue();
  4351. if (!V)
  4352. return nullptr;
  4353. SDDbgValue *SDV;
  4354. if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
  4355. SDV = DAG.getConstantDbgValue(Variable, Expression, V, Offset, dl,
  4356. SDNodeOrder);
  4357. DAG.AddDbgValue(SDV, nullptr, false);
  4358. } else {
  4359. // Do not use getValue() in here; we don't want to generate code at
  4360. // this point if it hasn't been done yet.
  4361. SDValue N = NodeMap[V];
  4362. if (!N.getNode() && isa<Argument>(V))
  4363. // Check unused arguments map.
  4364. N = UnusedArgNodeMap[V];
  4365. if (N.getNode()) {
  4366. if (!EmitFuncArgumentDbgValue(V, Variable, Expression, dl, Offset,
  4367. false, N)) {
  4368. SDV = getDbgValue(N, Variable, Expression, Offset, dl, SDNodeOrder);
  4369. DAG.AddDbgValue(SDV, N.getNode(), false);
  4370. }
  4371. } else if (!V->use_empty() ) {
  4372. // Do not call getValue(V) yet, as we don't want to generate code.
  4373. // Remember it for later.
  4374. DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
  4375. DanglingDebugInfoMap[V] = DDI;
  4376. } else {
  4377. // We may expand this to cover more cases. One case where we have no
  4378. // data available is an unreferenced parameter.
  4379. DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  4380. }
  4381. }
  4382. // Build a debug info table entry.
  4383. if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
  4384. V = BCI->getOperand(0);
  4385. const AllocaInst *AI = dyn_cast<AllocaInst>(V);
  4386. // Don't handle byval struct arguments or VLAs, for example.
  4387. if (!AI) {
  4388. DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n");
  4389. DEBUG(dbgs() << " Last seen at:\n " << *V << "\n");
  4390. return nullptr;
  4391. }
  4392. DenseMap<const AllocaInst*, int>::iterator SI =
  4393. FuncInfo.StaticAllocaMap.find(AI);
  4394. if (SI == FuncInfo.StaticAllocaMap.end())
  4395. return nullptr; // VLAs.
  4396. return nullptr;
  4397. }
  4398. case Intrinsic::eh_typeid_for: {
  4399. // Find the type id for the given typeinfo.
  4400. GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
  4401. unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
  4402. Res = DAG.getConstant(TypeID, sdl, MVT::i32);
  4403. setValue(&I, Res);
  4404. return nullptr;
  4405. }
  4406. case Intrinsic::eh_return_i32:
  4407. case Intrinsic::eh_return_i64:
  4408. DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
  4409. DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
  4410. MVT::Other,
  4411. getControlRoot(),
  4412. getValue(I.getArgOperand(0)),
  4413. getValue(I.getArgOperand(1))));
  4414. return nullptr;
  4415. case Intrinsic::eh_unwind_init:
  4416. DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
  4417. return nullptr;
  4418. case Intrinsic::eh_dwarf_cfa: {
  4419. setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
  4420. TLI.getPointerTy(DAG.getDataLayout()),
  4421. getValue(I.getArgOperand(0))));
  4422. return nullptr;
  4423. }
  4424. case Intrinsic::eh_sjlj_callsite: {
  4425. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  4426. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
  4427. assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
  4428. assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
  4429. MMI.setCurrentCallSite(CI->getZExtValue());
  4430. return nullptr;
  4431. }
  4432. case Intrinsic::eh_sjlj_functioncontext: {
  4433. // Get and store the index of the function context.
  4434. MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
  4435. AllocaInst *FnCtx =
  4436. cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
  4437. int FI = FuncInfo.StaticAllocaMap[FnCtx];
  4438. MFI.setFunctionContextIndex(FI);
  4439. return nullptr;
  4440. }
  4441. case Intrinsic::eh_sjlj_setjmp: {
  4442. SDValue Ops[2];
  4443. Ops[0] = getRoot();
  4444. Ops[1] = getValue(I.getArgOperand(0));
  4445. SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
  4446. DAG.getVTList(MVT::i32, MVT::Other), Ops);
  4447. setValue(&I, Op.getValue(0));
  4448. DAG.setRoot(Op.getValue(1));
  4449. return nullptr;
  4450. }
  4451. case Intrinsic::eh_sjlj_longjmp: {
  4452. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
  4453. getRoot(), getValue(I.getArgOperand(0))));
  4454. return nullptr;
  4455. }
  4456. case Intrinsic::eh_sjlj_setup_dispatch: {
  4457. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
  4458. getRoot()));
  4459. return nullptr;
  4460. }
  4461. case Intrinsic::masked_gather:
  4462. visitMaskedGather(I);
  4463. return nullptr;
  4464. case Intrinsic::masked_load:
  4465. visitMaskedLoad(I);
  4466. return nullptr;
  4467. case Intrinsic::masked_scatter:
  4468. visitMaskedScatter(I);
  4469. return nullptr;
  4470. case Intrinsic::masked_store:
  4471. visitMaskedStore(I);
  4472. return nullptr;
  4473. case Intrinsic::masked_expandload:
  4474. visitMaskedLoad(I, true /* IsExpanding */);
  4475. return nullptr;
  4476. case Intrinsic::masked_compressstore:
  4477. visitMaskedStore(I, true /* IsCompressing */);
  4478. return nullptr;
  4479. case Intrinsic::x86_mmx_pslli_w:
  4480. case Intrinsic::x86_mmx_pslli_d:
  4481. case Intrinsic::x86_mmx_pslli_q:
  4482. case Intrinsic::x86_mmx_psrli_w:
  4483. case Intrinsic::x86_mmx_psrli_d:
  4484. case Intrinsic::x86_mmx_psrli_q:
  4485. case Intrinsic::x86_mmx_psrai_w:
  4486. case Intrinsic::x86_mmx_psrai_d: {
  4487. SDValue ShAmt = getValue(I.getArgOperand(1));
  4488. if (isa<ConstantSDNode>(ShAmt)) {
  4489. visitTargetIntrinsic(I, Intrinsic);
  4490. return nullptr;
  4491. }
  4492. unsigned NewIntrinsic = 0;
  4493. EVT ShAmtVT = MVT::v2i32;
  4494. switch (Intrinsic) {
  4495. case Intrinsic::x86_mmx_pslli_w:
  4496. NewIntrinsic = Intrinsic::x86_mmx_psll_w;
  4497. break;
  4498. case Intrinsic::x86_mmx_pslli_d:
  4499. NewIntrinsic = Intrinsic::x86_mmx_psll_d;
  4500. break;
  4501. case Intrinsic::x86_mmx_pslli_q:
  4502. NewIntrinsic = Intrinsic::x86_mmx_psll_q;
  4503. break;
  4504. case Intrinsic::x86_mmx_psrli_w:
  4505. NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
  4506. break;
  4507. case Intrinsic::x86_mmx_psrli_d:
  4508. NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
  4509. break;
  4510. case Intrinsic::x86_mmx_psrli_q:
  4511. NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
  4512. break;
  4513. case Intrinsic::x86_mmx_psrai_w:
  4514. NewIntrinsic = Intrinsic::x86_mmx_psra_w;
  4515. break;
  4516. case Intrinsic::x86_mmx_psrai_d:
  4517. NewIntrinsic = Intrinsic::x86_mmx_psra_d;
  4518. break;
  4519. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  4520. }
  4521. // The vector shift intrinsics with scalars uses 32b shift amounts but
  4522. // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
  4523. // to be zero.
  4524. // We must do this early because v2i32 is not a legal type.
  4525. SDValue ShOps[2];
  4526. ShOps[0] = ShAmt;
  4527. ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
  4528. ShAmt = DAG.getNode(ISD::BUILD_VECTOR, sdl, ShAmtVT, ShOps);
  4529. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4530. ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
  4531. Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
  4532. DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
  4533. getValue(I.getArgOperand(0)), ShAmt);
  4534. setValue(&I, Res);
  4535. return nullptr;
  4536. }
  4537. case Intrinsic::convertff:
  4538. case Intrinsic::convertfsi:
  4539. case Intrinsic::convertfui:
  4540. case Intrinsic::convertsif:
  4541. case Intrinsic::convertuif:
  4542. case Intrinsic::convertss:
  4543. case Intrinsic::convertsu:
  4544. case Intrinsic::convertus:
  4545. case Intrinsic::convertuu: {
  4546. ISD::CvtCode Code = ISD::CVT_INVALID;
  4547. switch (Intrinsic) {
  4548. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  4549. case Intrinsic::convertff: Code = ISD::CVT_FF; break;
  4550. case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
  4551. case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
  4552. case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
  4553. case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
  4554. case Intrinsic::convertss: Code = ISD::CVT_SS; break;
  4555. case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
  4556. case Intrinsic::convertus: Code = ISD::CVT_US; break;
  4557. case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
  4558. }
  4559. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4560. const Value *Op1 = I.getArgOperand(0);
  4561. Res = DAG.getConvertRndSat(DestVT, sdl, getValue(Op1),
  4562. DAG.getValueType(DestVT),
  4563. DAG.getValueType(getValue(Op1).getValueType()),
  4564. getValue(I.getArgOperand(1)),
  4565. getValue(I.getArgOperand(2)),
  4566. Code);
  4567. setValue(&I, Res);
  4568. return nullptr;
  4569. }
  4570. case Intrinsic::powi:
  4571. setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
  4572. getValue(I.getArgOperand(1)), DAG));
  4573. return nullptr;
  4574. case Intrinsic::log:
  4575. setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  4576. return nullptr;
  4577. case Intrinsic::log2:
  4578. setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  4579. return nullptr;
  4580. case Intrinsic::log10:
  4581. setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  4582. return nullptr;
  4583. case Intrinsic::exp:
  4584. setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  4585. return nullptr;
  4586. case Intrinsic::exp2:
  4587. setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  4588. return nullptr;
  4589. case Intrinsic::pow:
  4590. setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
  4591. getValue(I.getArgOperand(1)), DAG, TLI));
  4592. return nullptr;
  4593. case Intrinsic::sqrt:
  4594. case Intrinsic::fabs:
  4595. case Intrinsic::sin:
  4596. case Intrinsic::cos:
  4597. case Intrinsic::floor:
  4598. case Intrinsic::ceil:
  4599. case Intrinsic::trunc:
  4600. case Intrinsic::rint:
  4601. case Intrinsic::nearbyint:
  4602. case Intrinsic::round:
  4603. case Intrinsic::canonicalize: {
  4604. unsigned Opcode;
  4605. switch (Intrinsic) {
  4606. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  4607. case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
  4608. case Intrinsic::fabs: Opcode = ISD::FABS; break;
  4609. case Intrinsic::sin: Opcode = ISD::FSIN; break;
  4610. case Intrinsic::cos: Opcode = ISD::FCOS; break;
  4611. case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
  4612. case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
  4613. case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
  4614. case Intrinsic::rint: Opcode = ISD::FRINT; break;
  4615. case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
  4616. case Intrinsic::round: Opcode = ISD::FROUND; break;
  4617. case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
  4618. }
  4619. setValue(&I, DAG.getNode(Opcode, sdl,
  4620. getValue(I.getArgOperand(0)).getValueType(),
  4621. getValue(I.getArgOperand(0))));
  4622. return nullptr;
  4623. }
  4624. case Intrinsic::minnum: {
  4625. auto VT = getValue(I.getArgOperand(0)).getValueType();
  4626. unsigned Opc =
  4627. I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT)
  4628. ? ISD::FMINNAN
  4629. : ISD::FMINNUM;
  4630. setValue(&I, DAG.getNode(Opc, sdl, VT,
  4631. getValue(I.getArgOperand(0)),
  4632. getValue(I.getArgOperand(1))));
  4633. return nullptr;
  4634. }
  4635. case Intrinsic::maxnum: {
  4636. auto VT = getValue(I.getArgOperand(0)).getValueType();
  4637. unsigned Opc =
  4638. I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT)
  4639. ? ISD::FMAXNAN
  4640. : ISD::FMAXNUM;
  4641. setValue(&I, DAG.getNode(Opc, sdl, VT,
  4642. getValue(I.getArgOperand(0)),
  4643. getValue(I.getArgOperand(1))));
  4644. return nullptr;
  4645. }
  4646. case Intrinsic::copysign:
  4647. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
  4648. getValue(I.getArgOperand(0)).getValueType(),
  4649. getValue(I.getArgOperand(0)),
  4650. getValue(I.getArgOperand(1))));
  4651. return nullptr;
  4652. case Intrinsic::fma:
  4653. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  4654. getValue(I.getArgOperand(0)).getValueType(),
  4655. getValue(I.getArgOperand(0)),
  4656. getValue(I.getArgOperand(1)),
  4657. getValue(I.getArgOperand(2))));
  4658. return nullptr;
  4659. case Intrinsic::fmuladd: {
  4660. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4661. if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
  4662. TLI.isFMAFasterThanFMulAndFAdd(VT)) {
  4663. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  4664. getValue(I.getArgOperand(0)).getValueType(),
  4665. getValue(I.getArgOperand(0)),
  4666. getValue(I.getArgOperand(1)),
  4667. getValue(I.getArgOperand(2))));
  4668. } else {
  4669. // TODO: Intrinsic calls should have fast-math-flags.
  4670. SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
  4671. getValue(I.getArgOperand(0)).getValueType(),
  4672. getValue(I.getArgOperand(0)),
  4673. getValue(I.getArgOperand(1)));
  4674. SDValue Add = DAG.getNode(ISD::FADD, sdl,
  4675. getValue(I.getArgOperand(0)).getValueType(),
  4676. Mul,
  4677. getValue(I.getArgOperand(2)));
  4678. setValue(&I, Add);
  4679. }
  4680. return nullptr;
  4681. }
  4682. case Intrinsic::convert_to_fp16:
  4683. setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
  4684. DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
  4685. getValue(I.getArgOperand(0)),
  4686. DAG.getTargetConstant(0, sdl,
  4687. MVT::i32))));
  4688. return nullptr;
  4689. case Intrinsic::convert_from_fp16:
  4690. setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
  4691. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  4692. DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
  4693. getValue(I.getArgOperand(0)))));
  4694. return nullptr;
  4695. case Intrinsic::pcmarker: {
  4696. SDValue Tmp = getValue(I.getArgOperand(0));
  4697. DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
  4698. return nullptr;
  4699. }
  4700. case Intrinsic::readcyclecounter: {
  4701. SDValue Op = getRoot();
  4702. Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
  4703. DAG.getVTList(MVT::i64, MVT::Other), Op);
  4704. setValue(&I, Res);
  4705. DAG.setRoot(Res.getValue(1));
  4706. return nullptr;
  4707. }
  4708. case Intrinsic::bitreverse:
  4709. setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
  4710. getValue(I.getArgOperand(0)).getValueType(),
  4711. getValue(I.getArgOperand(0))));
  4712. return nullptr;
  4713. case Intrinsic::bswap:
  4714. setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
  4715. getValue(I.getArgOperand(0)).getValueType(),
  4716. getValue(I.getArgOperand(0))));
  4717. return nullptr;
  4718. case Intrinsic::cttz: {
  4719. SDValue Arg = getValue(I.getArgOperand(0));
  4720. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  4721. EVT Ty = Arg.getValueType();
  4722. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
  4723. sdl, Ty, Arg));
  4724. return nullptr;
  4725. }
  4726. case Intrinsic::ctlz: {
  4727. SDValue Arg = getValue(I.getArgOperand(0));
  4728. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  4729. EVT Ty = Arg.getValueType();
  4730. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
  4731. sdl, Ty, Arg));
  4732. return nullptr;
  4733. }
  4734. case Intrinsic::ctpop: {
  4735. SDValue Arg = getValue(I.getArgOperand(0));
  4736. EVT Ty = Arg.getValueType();
  4737. setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
  4738. return nullptr;
  4739. }
  4740. case Intrinsic::stacksave: {
  4741. SDValue Op = getRoot();
  4742. Res = DAG.getNode(
  4743. ISD::STACKSAVE, sdl,
  4744. DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
  4745. setValue(&I, Res);
  4746. DAG.setRoot(Res.getValue(1));
  4747. return nullptr;
  4748. }
  4749. case Intrinsic::stackrestore: {
  4750. Res = getValue(I.getArgOperand(0));
  4751. DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
  4752. return nullptr;
  4753. }
  4754. case Intrinsic::get_dynamic_area_offset: {
  4755. SDValue Op = getRoot();
  4756. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  4757. EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4758. // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
  4759. // target.
  4760. if (PtrTy != ResTy)
  4761. report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
  4762. " intrinsic!");
  4763. Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
  4764. Op);
  4765. DAG.setRoot(Op);
  4766. setValue(&I, Res);
  4767. return nullptr;
  4768. }
  4769. case Intrinsic::stackguard: {
  4770. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  4771. MachineFunction &MF = DAG.getMachineFunction();
  4772. const Module &M = *MF.getFunction()->getParent();
  4773. SDValue Chain = getRoot();
  4774. if (TLI.useLoadStackGuardNode()) {
  4775. Res = getLoadStackGuard(DAG, sdl, Chain);
  4776. } else {
  4777. const Value *Global = TLI.getSDagStackGuard(M);
  4778. unsigned Align = DL->getPrefTypeAlignment(Global->getType());
  4779. Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
  4780. MachinePointerInfo(Global, 0), Align,
  4781. MachineMemOperand::MOVolatile);
  4782. }
  4783. DAG.setRoot(Chain);
  4784. setValue(&I, Res);
  4785. return nullptr;
  4786. }
  4787. case Intrinsic::stackprotector: {
  4788. // Emit code into the DAG to store the stack guard onto the stack.
  4789. MachineFunction &MF = DAG.getMachineFunction();
  4790. MachineFrameInfo &MFI = MF.getFrameInfo();
  4791. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  4792. SDValue Src, Chain = getRoot();
  4793. if (TLI.useLoadStackGuardNode())
  4794. Src = getLoadStackGuard(DAG, sdl, Chain);
  4795. else
  4796. Src = getValue(I.getArgOperand(0)); // The guard's value.
  4797. AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
  4798. int FI = FuncInfo.StaticAllocaMap[Slot];
  4799. MFI.setStackProtectorIndex(FI);
  4800. SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
  4801. // Store the stack protector onto the stack.
  4802. Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
  4803. DAG.getMachineFunction(), FI),
  4804. /* Alignment = */ 0, MachineMemOperand::MOVolatile);
  4805. setValue(&I, Res);
  4806. DAG.setRoot(Res);
  4807. return nullptr;
  4808. }
  4809. case Intrinsic::objectsize: {
  4810. // If we don't know by now, we're never going to know.
  4811. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
  4812. assert(CI && "Non-constant type in __builtin_object_size?");
  4813. SDValue Arg = getValue(I.getCalledValue());
  4814. EVT Ty = Arg.getValueType();
  4815. if (CI->isZero())
  4816. Res = DAG.getConstant(-1ULL, sdl, Ty);
  4817. else
  4818. Res = DAG.getConstant(0, sdl, Ty);
  4819. setValue(&I, Res);
  4820. return nullptr;
  4821. }
  4822. case Intrinsic::annotation:
  4823. case Intrinsic::ptr_annotation:
  4824. case Intrinsic::invariant_group_barrier:
  4825. // Drop the intrinsic, but forward the value
  4826. setValue(&I, getValue(I.getOperand(0)));
  4827. return nullptr;
  4828. case Intrinsic::assume:
  4829. case Intrinsic::var_annotation:
  4830. // Discard annotate attributes and assumptions
  4831. return nullptr;
  4832. case Intrinsic::init_trampoline: {
  4833. const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
  4834. SDValue Ops[6];
  4835. Ops[0] = getRoot();
  4836. Ops[1] = getValue(I.getArgOperand(0));
  4837. Ops[2] = getValue(I.getArgOperand(1));
  4838. Ops[3] = getValue(I.getArgOperand(2));
  4839. Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
  4840. Ops[5] = DAG.getSrcValue(F);
  4841. Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
  4842. DAG.setRoot(Res);
  4843. return nullptr;
  4844. }
  4845. case Intrinsic::adjust_trampoline: {
  4846. setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
  4847. TLI.getPointerTy(DAG.getDataLayout()),
  4848. getValue(I.getArgOperand(0))));
  4849. return nullptr;
  4850. }
  4851. case Intrinsic::gcroot: {
  4852. MachineFunction &MF = DAG.getMachineFunction();
  4853. const Function *F = MF.getFunction();
  4854. (void)F;
  4855. assert(F->hasGC() &&
  4856. "only valid in functions with gc specified, enforced by Verifier");
  4857. assert(GFI && "implied by previous");
  4858. const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
  4859. const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
  4860. FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
  4861. GFI->addStackRoot(FI->getIndex(), TypeMap);
  4862. return nullptr;
  4863. }
  4864. case Intrinsic::gcread:
  4865. case Intrinsic::gcwrite:
  4866. llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
  4867. case Intrinsic::flt_rounds:
  4868. setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
  4869. return nullptr;
  4870. case Intrinsic::expect: {
  4871. // Just replace __builtin_expect(exp, c) with EXP.
  4872. setValue(&I, getValue(I.getArgOperand(0)));
  4873. return nullptr;
  4874. }
  4875. case Intrinsic::debugtrap:
  4876. case Intrinsic::trap: {
  4877. StringRef TrapFuncName =
  4878. I.getAttributes()
  4879. .getAttribute(AttributeSet::FunctionIndex, "trap-func-name")
  4880. .getValueAsString();
  4881. if (TrapFuncName.empty()) {
  4882. ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
  4883. ISD::TRAP : ISD::DEBUGTRAP;
  4884. DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
  4885. return nullptr;
  4886. }
  4887. TargetLowering::ArgListTy Args;
  4888. TargetLowering::CallLoweringInfo CLI(DAG);
  4889. CLI.setDebugLoc(sdl).setChain(getRoot()).setCallee(
  4890. CallingConv::C, I.getType(),
  4891. DAG.getExternalSymbol(TrapFuncName.data(),
  4892. TLI.getPointerTy(DAG.getDataLayout())),
  4893. std::move(Args));
  4894. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  4895. DAG.setRoot(Result.second);
  4896. return nullptr;
  4897. }
  4898. case Intrinsic::uadd_with_overflow:
  4899. case Intrinsic::sadd_with_overflow:
  4900. case Intrinsic::usub_with_overflow:
  4901. case Intrinsic::ssub_with_overflow:
  4902. case Intrinsic::umul_with_overflow:
  4903. case Intrinsic::smul_with_overflow: {
  4904. ISD::NodeType Op;
  4905. switch (Intrinsic) {
  4906. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  4907. case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
  4908. case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
  4909. case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
  4910. case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
  4911. case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
  4912. case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
  4913. }
  4914. SDValue Op1 = getValue(I.getArgOperand(0));
  4915. SDValue Op2 = getValue(I.getArgOperand(1));
  4916. SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
  4917. setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
  4918. return nullptr;
  4919. }
  4920. case Intrinsic::prefetch: {
  4921. SDValue Ops[5];
  4922. unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  4923. Ops[0] = getRoot();
  4924. Ops[1] = getValue(I.getArgOperand(0));
  4925. Ops[2] = getValue(I.getArgOperand(1));
  4926. Ops[3] = getValue(I.getArgOperand(2));
  4927. Ops[4] = getValue(I.getArgOperand(3));
  4928. DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
  4929. DAG.getVTList(MVT::Other), Ops,
  4930. EVT::getIntegerVT(*Context, 8),
  4931. MachinePointerInfo(I.getArgOperand(0)),
  4932. 0, /* align */
  4933. false, /* volatile */
  4934. rw==0, /* read */
  4935. rw==1)); /* write */
  4936. return nullptr;
  4937. }
  4938. case Intrinsic::lifetime_start:
  4939. case Intrinsic::lifetime_end: {
  4940. bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
  4941. // Stack coloring is not enabled in O0, discard region information.
  4942. if (TM.getOptLevel() == CodeGenOpt::None)
  4943. return nullptr;
  4944. SmallVector<Value *, 4> Allocas;
  4945. GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL);
  4946. for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
  4947. E = Allocas.end(); Object != E; ++Object) {
  4948. AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
  4949. // Could not find an Alloca.
  4950. if (!LifetimeObject)
  4951. continue;
  4952. // First check that the Alloca is static, otherwise it won't have a
  4953. // valid frame index.
  4954. auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
  4955. if (SI == FuncInfo.StaticAllocaMap.end())
  4956. return nullptr;
  4957. int FI = SI->second;
  4958. SDValue Ops[2];
  4959. Ops[0] = getRoot();
  4960. Ops[1] =
  4961. DAG.getFrameIndex(FI, TLI.getPointerTy(DAG.getDataLayout()), true);
  4962. unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
  4963. Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
  4964. DAG.setRoot(Res);
  4965. }
  4966. return nullptr;
  4967. }
  4968. case Intrinsic::invariant_start:
  4969. // Discard region information.
  4970. setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
  4971. return nullptr;
  4972. case Intrinsic::invariant_end:
  4973. // Discard region information.
  4974. return nullptr;
  4975. case Intrinsic::clear_cache:
  4976. return TLI.getClearCacheBuiltinName();
  4977. case Intrinsic::donothing:
  4978. // ignore
  4979. return nullptr;
  4980. case Intrinsic::experimental_stackmap: {
  4981. visitStackmap(I);
  4982. return nullptr;
  4983. }
  4984. case Intrinsic::experimental_patchpoint_void:
  4985. case Intrinsic::experimental_patchpoint_i64: {
  4986. visitPatchpoint(&I);
  4987. return nullptr;
  4988. }
  4989. case Intrinsic::experimental_gc_statepoint: {
  4990. LowerStatepoint(ImmutableStatepoint(&I));
  4991. return nullptr;
  4992. }
  4993. case Intrinsic::experimental_gc_result: {
  4994. visitGCResult(cast<GCResultInst>(I));
  4995. return nullptr;
  4996. }
  4997. case Intrinsic::experimental_gc_relocate: {
  4998. visitGCRelocate(cast<GCRelocateInst>(I));
  4999. return nullptr;
  5000. }
  5001. case Intrinsic::instrprof_increment:
  5002. llvm_unreachable("instrprof failed to lower an increment");
  5003. case Intrinsic::instrprof_value_profile:
  5004. llvm_unreachable("instrprof failed to lower a value profiling call");
  5005. case Intrinsic::localescape: {
  5006. MachineFunction &MF = DAG.getMachineFunction();
  5007. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  5008. // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
  5009. // is the same on all targets.
  5010. for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
  5011. Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
  5012. if (isa<ConstantPointerNull>(Arg))
  5013. continue; // Skip null pointers. They represent a hole in index space.
  5014. AllocaInst *Slot = cast<AllocaInst>(Arg);
  5015. assert(FuncInfo.StaticAllocaMap.count(Slot) &&
  5016. "can only escape static allocas");
  5017. int FI = FuncInfo.StaticAllocaMap[Slot];
  5018. MCSymbol *FrameAllocSym =
  5019. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  5020. GlobalValue::getRealLinkageName(MF.getName()), Idx);
  5021. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
  5022. TII->get(TargetOpcode::LOCAL_ESCAPE))
  5023. .addSym(FrameAllocSym)
  5024. .addFrameIndex(FI);
  5025. }
  5026. return nullptr;
  5027. }
  5028. case Intrinsic::localrecover: {
  5029. // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
  5030. MachineFunction &MF = DAG.getMachineFunction();
  5031. MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
  5032. // Get the symbol that defines the frame offset.
  5033. auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
  5034. auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
  5035. unsigned IdxVal = unsigned(Idx->getLimitedValue(INT_MAX));
  5036. MCSymbol *FrameAllocSym =
  5037. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  5038. GlobalValue::getRealLinkageName(Fn->getName()), IdxVal);
  5039. // Create a MCSymbol for the label to avoid any target lowering
  5040. // that would make this PC relative.
  5041. SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
  5042. SDValue OffsetVal =
  5043. DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
  5044. // Add the offset to the FP.
  5045. Value *FP = I.getArgOperand(1);
  5046. SDValue FPVal = getValue(FP);
  5047. SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
  5048. setValue(&I, Add);
  5049. return nullptr;
  5050. }
  5051. case Intrinsic::eh_exceptionpointer:
  5052. case Intrinsic::eh_exceptioncode: {
  5053. // Get the exception pointer vreg, copy from it, and resize it to fit.
  5054. const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
  5055. MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
  5056. const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
  5057. unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
  5058. SDValue N =
  5059. DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
  5060. if (Intrinsic == Intrinsic::eh_exceptioncode)
  5061. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
  5062. setValue(&I, N);
  5063. return nullptr;
  5064. }
  5065. case Intrinsic::experimental_deoptimize:
  5066. LowerDeoptimizeCall(&I);
  5067. return nullptr;
  5068. }
  5069. }
  5070. std::pair<SDValue, SDValue>
  5071. SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
  5072. const BasicBlock *EHPadBB) {
  5073. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  5074. MCSymbol *BeginLabel = nullptr;
  5075. if (EHPadBB) {
  5076. // Insert a label before the invoke call to mark the try range. This can be
  5077. // used to detect deletion of the invoke via the MachineModuleInfo.
  5078. BeginLabel = MMI.getContext().createTempSymbol();
  5079. // For SjLj, keep track of which landing pads go with which invokes
  5080. // so as to maintain the ordering of pads in the LSDA.
  5081. unsigned CallSiteIndex = MMI.getCurrentCallSite();
  5082. if (CallSiteIndex) {
  5083. MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
  5084. LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
  5085. // Now that the call site is handled, stop tracking it.
  5086. MMI.setCurrentCallSite(0);
  5087. }
  5088. // Both PendingLoads and PendingExports must be flushed here;
  5089. // this call might not return.
  5090. (void)getRoot();
  5091. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
  5092. CLI.setChain(getRoot());
  5093. }
  5094. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5095. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  5096. assert((CLI.IsTailCall || Result.second.getNode()) &&
  5097. "Non-null chain expected with non-tail call!");
  5098. assert((Result.second.getNode() || !Result.first.getNode()) &&
  5099. "Null value expected with tail call!");
  5100. if (!Result.second.getNode()) {
  5101. // As a special case, a null chain means that a tail call has been emitted
  5102. // and the DAG root is already updated.
  5103. HasTailCall = true;
  5104. // Since there's no actual continuation from this block, nothing can be
  5105. // relying on us setting vregs for them.
  5106. PendingExports.clear();
  5107. } else {
  5108. DAG.setRoot(Result.second);
  5109. }
  5110. if (EHPadBB) {
  5111. // Insert a label at the end of the invoke call to mark the try range. This
  5112. // can be used to detect deletion of the invoke via the MachineModuleInfo.
  5113. MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
  5114. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
  5115. // Inform MachineModuleInfo of range.
  5116. if (MMI.hasEHFunclets()) {
  5117. assert(CLI.CS);
  5118. WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
  5119. EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS->getInstruction()),
  5120. BeginLabel, EndLabel);
  5121. } else {
  5122. MMI.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
  5123. }
  5124. }
  5125. return Result;
  5126. }
  5127. void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
  5128. bool isTailCall,
  5129. const BasicBlock *EHPadBB) {
  5130. auto &DL = DAG.getDataLayout();
  5131. FunctionType *FTy = CS.getFunctionType();
  5132. Type *RetTy = CS.getType();
  5133. TargetLowering::ArgListTy Args;
  5134. TargetLowering::ArgListEntry Entry;
  5135. Args.reserve(CS.arg_size());
  5136. const Value *SwiftErrorVal = nullptr;
  5137. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5138. for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
  5139. i != e; ++i) {
  5140. const Value *V = *i;
  5141. // Skip empty types
  5142. if (V->getType()->isEmptyTy())
  5143. continue;
  5144. SDValue ArgNode = getValue(V);
  5145. Entry.Node = ArgNode; Entry.Ty = V->getType();
  5146. // Skip the first return-type Attribute to get to params.
  5147. Entry.setAttributes(&CS, i - CS.arg_begin() + 1);
  5148. // Use swifterror virtual register as input to the call.
  5149. if (Entry.isSwiftError && TLI.supportSwiftError()) {
  5150. SwiftErrorVal = V;
  5151. // We find the virtual register for the actual swifterror argument.
  5152. // Instead of using the Value, we use the virtual register instead.
  5153. Entry.Node =
  5154. DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVReg(FuncInfo.MBB, V),
  5155. EVT(TLI.getPointerTy(DL)));
  5156. }
  5157. Args.push_back(Entry);
  5158. // If we have an explicit sret argument that is an Instruction, (i.e., it
  5159. // might point to function-local memory), we can't meaningfully tail-call.
  5160. if (Entry.isSRet && isa<Instruction>(V))
  5161. isTailCall = false;
  5162. }
  5163. // Check if target-independent constraints permit a tail call here.
  5164. // Target-dependent constraints are checked within TLI->LowerCallTo.
  5165. if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
  5166. isTailCall = false;
  5167. // Disable tail calls if there is an swifterror argument. Targets have not
  5168. // been updated to support tail calls.
  5169. if (TLI.supportSwiftError() && SwiftErrorVal)
  5170. isTailCall = false;
  5171. TargetLowering::CallLoweringInfo CLI(DAG);
  5172. CLI.setDebugLoc(getCurSDLoc())
  5173. .setChain(getRoot())
  5174. .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
  5175. .setTailCall(isTailCall)
  5176. .setConvergent(CS.isConvergent());
  5177. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  5178. if (Result.first.getNode()) {
  5179. const Instruction *Inst = CS.getInstruction();
  5180. Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
  5181. setValue(Inst, Result.first);
  5182. }
  5183. // The last element of CLI.InVals has the SDValue for swifterror return.
  5184. // Here we copy it to a virtual register and update SwiftErrorMap for
  5185. // book-keeping.
  5186. if (SwiftErrorVal && TLI.supportSwiftError()) {
  5187. // Get the last element of InVals.
  5188. SDValue Src = CLI.InVals.back();
  5189. const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy(DL));
  5190. unsigned VReg = FuncInfo.MF->getRegInfo().createVirtualRegister(RC);
  5191. SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
  5192. // We update the virtual register for the actual swifterror argument.
  5193. FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg);
  5194. DAG.setRoot(CopyNode);
  5195. }
  5196. }
  5197. /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
  5198. /// value is equal or not-equal to zero.
  5199. static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
  5200. for (const User *U : V->users()) {
  5201. if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
  5202. if (IC->isEquality())
  5203. if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
  5204. if (C->isNullValue())
  5205. continue;
  5206. // Unknown instruction.
  5207. return false;
  5208. }
  5209. return true;
  5210. }
  5211. static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
  5212. Type *LoadTy,
  5213. SelectionDAGBuilder &Builder) {
  5214. // Check to see if this load can be trivially constant folded, e.g. if the
  5215. // input is from a string literal.
  5216. if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
  5217. // Cast pointer to the type we really want to load.
  5218. LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
  5219. PointerType::getUnqual(LoadTy));
  5220. if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
  5221. const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
  5222. return Builder.getValue(LoadCst);
  5223. }
  5224. // Otherwise, we have to emit the load. If the pointer is to unfoldable but
  5225. // still constant memory, the input chain can be the entry node.
  5226. SDValue Root;
  5227. bool ConstantMemory = false;
  5228. // Do not serialize (non-volatile) loads of constant memory with anything.
  5229. if (Builder.AA->pointsToConstantMemory(PtrVal)) {
  5230. Root = Builder.DAG.getEntryNode();
  5231. ConstantMemory = true;
  5232. } else {
  5233. // Do not serialize non-volatile loads against each other.
  5234. Root = Builder.DAG.getRoot();
  5235. }
  5236. SDValue Ptr = Builder.getValue(PtrVal);
  5237. SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
  5238. Ptr, MachinePointerInfo(PtrVal),
  5239. /* Alignment = */ 1);
  5240. if (!ConstantMemory)
  5241. Builder.PendingLoads.push_back(LoadVal.getValue(1));
  5242. return LoadVal;
  5243. }
  5244. /// processIntegerCallValue - Record the value for an instruction that
  5245. /// produces an integer result, converting the type where necessary.
  5246. void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
  5247. SDValue Value,
  5248. bool IsSigned) {
  5249. EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  5250. I.getType(), true);
  5251. if (IsSigned)
  5252. Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
  5253. else
  5254. Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
  5255. setValue(&I, Value);
  5256. }
  5257. /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
  5258. /// If so, return true and lower it, otherwise return false and it will be
  5259. /// lowered like a normal call.
  5260. bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
  5261. // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
  5262. if (I.getNumArgOperands() != 3)
  5263. return false;
  5264. const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
  5265. if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
  5266. !I.getArgOperand(2)->getType()->isIntegerTy() ||
  5267. !I.getType()->isIntegerTy())
  5268. return false;
  5269. const Value *Size = I.getArgOperand(2);
  5270. const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
  5271. if (CSize && CSize->getZExtValue() == 0) {
  5272. EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  5273. I.getType(), true);
  5274. setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
  5275. return true;
  5276. }
  5277. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  5278. std::pair<SDValue, SDValue> Res =
  5279. TSI.EmitTargetCodeForMemcmp(DAG, getCurSDLoc(), DAG.getRoot(),
  5280. getValue(LHS), getValue(RHS), getValue(Size),
  5281. MachinePointerInfo(LHS),
  5282. MachinePointerInfo(RHS));
  5283. if (Res.first.getNode()) {
  5284. processIntegerCallValue(I, Res.first, true);
  5285. PendingLoads.push_back(Res.second);
  5286. return true;
  5287. }
  5288. // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
  5289. // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
  5290. if (CSize && IsOnlyUsedInZeroEqualityComparison(&I)) {
  5291. bool ActuallyDoIt = true;
  5292. MVT LoadVT;
  5293. Type *LoadTy;
  5294. switch (CSize->getZExtValue()) {
  5295. default:
  5296. LoadVT = MVT::Other;
  5297. LoadTy = nullptr;
  5298. ActuallyDoIt = false;
  5299. break;
  5300. case 2:
  5301. LoadVT = MVT::i16;
  5302. LoadTy = Type::getInt16Ty(CSize->getContext());
  5303. break;
  5304. case 4:
  5305. LoadVT = MVT::i32;
  5306. LoadTy = Type::getInt32Ty(CSize->getContext());
  5307. break;
  5308. case 8:
  5309. LoadVT = MVT::i64;
  5310. LoadTy = Type::getInt64Ty(CSize->getContext());
  5311. break;
  5312. /*
  5313. case 16:
  5314. LoadVT = MVT::v4i32;
  5315. LoadTy = Type::getInt32Ty(CSize->getContext());
  5316. LoadTy = VectorType::get(LoadTy, 4);
  5317. break;
  5318. */
  5319. }
  5320. // This turns into unaligned loads. We only do this if the target natively
  5321. // supports the MVT we'll be loading or if it is small enough (<= 4) that
  5322. // we'll only produce a small number of byte loads.
  5323. // Require that we can find a legal MVT, and only do this if the target
  5324. // supports unaligned loads of that type. Expanding into byte loads would
  5325. // bloat the code.
  5326. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5327. if (ActuallyDoIt && CSize->getZExtValue() > 4) {
  5328. unsigned DstAS = LHS->getType()->getPointerAddressSpace();
  5329. unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
  5330. // TODO: Handle 5 byte compare as 4-byte + 1 byte.
  5331. // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
  5332. // TODO: Check alignment of src and dest ptrs.
  5333. if (!TLI.isTypeLegal(LoadVT) ||
  5334. !TLI.allowsMisalignedMemoryAccesses(LoadVT, SrcAS) ||
  5335. !TLI.allowsMisalignedMemoryAccesses(LoadVT, DstAS))
  5336. ActuallyDoIt = false;
  5337. }
  5338. if (ActuallyDoIt) {
  5339. SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
  5340. SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
  5341. SDValue Res = DAG.getSetCC(getCurSDLoc(), MVT::i1, LHSVal, RHSVal,
  5342. ISD::SETNE);
  5343. processIntegerCallValue(I, Res, false);
  5344. return true;
  5345. }
  5346. }
  5347. return false;
  5348. }
  5349. /// visitMemChrCall -- See if we can lower a memchr call into an optimized
  5350. /// form. If so, return true and lower it, otherwise return false and it
  5351. /// will be lowered like a normal call.
  5352. bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
  5353. // Verify that the prototype makes sense. void *memchr(void *, int, size_t)
  5354. if (I.getNumArgOperands() != 3)
  5355. return false;
  5356. const Value *Src = I.getArgOperand(0);
  5357. const Value *Char = I.getArgOperand(1);
  5358. const Value *Length = I.getArgOperand(2);
  5359. if (!Src->getType()->isPointerTy() ||
  5360. !Char->getType()->isIntegerTy() ||
  5361. !Length->getType()->isIntegerTy() ||
  5362. !I.getType()->isPointerTy())
  5363. return false;
  5364. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  5365. std::pair<SDValue, SDValue> Res =
  5366. TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
  5367. getValue(Src), getValue(Char), getValue(Length),
  5368. MachinePointerInfo(Src));
  5369. if (Res.first.getNode()) {
  5370. setValue(&I, Res.first);
  5371. PendingLoads.push_back(Res.second);
  5372. return true;
  5373. }
  5374. return false;
  5375. }
  5376. ///
  5377. /// visitMemPCpyCall -- lower a mempcpy call as a memcpy followed by code to
  5378. /// to adjust the dst pointer by the size of the copied memory.
  5379. bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
  5380. // Verify argument count: void *mempcpy(void *, const void *, size_t)
  5381. if (I.getNumArgOperands() != 3)
  5382. return false;
  5383. SDValue Dst = getValue(I.getArgOperand(0));
  5384. SDValue Src = getValue(I.getArgOperand(1));
  5385. SDValue Size = getValue(I.getArgOperand(2));
  5386. unsigned DstAlign = DAG.InferPtrAlignment(Dst);
  5387. unsigned SrcAlign = DAG.InferPtrAlignment(Src);
  5388. unsigned Align = std::min(DstAlign, SrcAlign);
  5389. if (Align == 0) // Alignment of one or both could not be inferred.
  5390. Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
  5391. bool isVol = false;
  5392. SDLoc sdl = getCurSDLoc();
  5393. // In the mempcpy context we need to pass in a false value for isTailCall
  5394. // because the return pointer needs to be adjusted by the size of
  5395. // the copied memory.
  5396. SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
  5397. false, /*isTailCall=*/false,
  5398. MachinePointerInfo(I.getArgOperand(0)),
  5399. MachinePointerInfo(I.getArgOperand(1)));
  5400. assert(MC.getNode() != nullptr &&
  5401. "** memcpy should not be lowered as TailCall in mempcpy context **");
  5402. DAG.setRoot(MC);
  5403. // Check if Size needs to be truncated or extended.
  5404. Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
  5405. // Adjust return pointer to point just past the last dst byte.
  5406. SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
  5407. Dst, Size);
  5408. setValue(&I, DstPlusSize);
  5409. return true;
  5410. }
  5411. /// visitStrCpyCall -- See if we can lower a strcpy or stpcpy call into an
  5412. /// optimized form. If so, return true and lower it, otherwise return false
  5413. /// and it will be lowered like a normal call.
  5414. bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
  5415. // Verify that the prototype makes sense. char *strcpy(char *, char *)
  5416. if (I.getNumArgOperands() != 2)
  5417. return false;
  5418. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  5419. if (!Arg0->getType()->isPointerTy() ||
  5420. !Arg1->getType()->isPointerTy() ||
  5421. !I.getType()->isPointerTy())
  5422. return false;
  5423. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  5424. std::pair<SDValue, SDValue> Res =
  5425. TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
  5426. getValue(Arg0), getValue(Arg1),
  5427. MachinePointerInfo(Arg0),
  5428. MachinePointerInfo(Arg1), isStpcpy);
  5429. if (Res.first.getNode()) {
  5430. setValue(&I, Res.first);
  5431. DAG.setRoot(Res.second);
  5432. return true;
  5433. }
  5434. return false;
  5435. }
  5436. /// visitStrCmpCall - See if we can lower a call to strcmp in an optimized form.
  5437. /// If so, return true and lower it, otherwise return false and it will be
  5438. /// lowered like a normal call.
  5439. bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
  5440. // Verify that the prototype makes sense. int strcmp(void*,void*)
  5441. if (I.getNumArgOperands() != 2)
  5442. return false;
  5443. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  5444. if (!Arg0->getType()->isPointerTy() ||
  5445. !Arg1->getType()->isPointerTy() ||
  5446. !I.getType()->isIntegerTy())
  5447. return false;
  5448. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  5449. std::pair<SDValue, SDValue> Res =
  5450. TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
  5451. getValue(Arg0), getValue(Arg1),
  5452. MachinePointerInfo(Arg0),
  5453. MachinePointerInfo(Arg1));
  5454. if (Res.first.getNode()) {
  5455. processIntegerCallValue(I, Res.first, true);
  5456. PendingLoads.push_back(Res.second);
  5457. return true;
  5458. }
  5459. return false;
  5460. }
  5461. /// visitStrLenCall -- See if we can lower a strlen call into an optimized
  5462. /// form. If so, return true and lower it, otherwise return false and it
  5463. /// will be lowered like a normal call.
  5464. bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
  5465. // Verify that the prototype makes sense. size_t strlen(char *)
  5466. if (I.getNumArgOperands() != 1)
  5467. return false;
  5468. const Value *Arg0 = I.getArgOperand(0);
  5469. if (!Arg0->getType()->isPointerTy() || !I.getType()->isIntegerTy())
  5470. return false;
  5471. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  5472. std::pair<SDValue, SDValue> Res =
  5473. TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
  5474. getValue(Arg0), MachinePointerInfo(Arg0));
  5475. if (Res.first.getNode()) {
  5476. processIntegerCallValue(I, Res.first, false);
  5477. PendingLoads.push_back(Res.second);
  5478. return true;
  5479. }
  5480. return false;
  5481. }
  5482. /// visitStrNLenCall -- See if we can lower a strnlen call into an optimized
  5483. /// form. If so, return true and lower it, otherwise return false and it
  5484. /// will be lowered like a normal call.
  5485. bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
  5486. // Verify that the prototype makes sense. size_t strnlen(char *, size_t)
  5487. if (I.getNumArgOperands() != 2)
  5488. return false;
  5489. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  5490. if (!Arg0->getType()->isPointerTy() ||
  5491. !Arg1->getType()->isIntegerTy() ||
  5492. !I.getType()->isIntegerTy())
  5493. return false;
  5494. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  5495. std::pair<SDValue, SDValue> Res =
  5496. TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
  5497. getValue(Arg0), getValue(Arg1),
  5498. MachinePointerInfo(Arg0));
  5499. if (Res.first.getNode()) {
  5500. processIntegerCallValue(I, Res.first, false);
  5501. PendingLoads.push_back(Res.second);
  5502. return true;
  5503. }
  5504. return false;
  5505. }
  5506. /// visitUnaryFloatCall - If a call instruction is a unary floating-point
  5507. /// operation (as expected), translate it to an SDNode with the specified opcode
  5508. /// and return true.
  5509. bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
  5510. unsigned Opcode) {
  5511. // Sanity check that it really is a unary floating-point call.
  5512. if (I.getNumArgOperands() != 1 ||
  5513. !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
  5514. I.getType() != I.getArgOperand(0)->getType() ||
  5515. !I.onlyReadsMemory())
  5516. return false;
  5517. SDValue Tmp = getValue(I.getArgOperand(0));
  5518. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
  5519. return true;
  5520. }
  5521. /// visitBinaryFloatCall - If a call instruction is a binary floating-point
  5522. /// operation (as expected), translate it to an SDNode with the specified opcode
  5523. /// and return true.
  5524. bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
  5525. unsigned Opcode) {
  5526. // Sanity check that it really is a binary floating-point call.
  5527. if (I.getNumArgOperands() != 2 ||
  5528. !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
  5529. I.getType() != I.getArgOperand(0)->getType() ||
  5530. I.getType() != I.getArgOperand(1)->getType() ||
  5531. !I.onlyReadsMemory())
  5532. return false;
  5533. SDValue Tmp0 = getValue(I.getArgOperand(0));
  5534. SDValue Tmp1 = getValue(I.getArgOperand(1));
  5535. EVT VT = Tmp0.getValueType();
  5536. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
  5537. return true;
  5538. }
  5539. void SelectionDAGBuilder::visitCall(const CallInst &I) {
  5540. // Handle inline assembly differently.
  5541. if (isa<InlineAsm>(I.getCalledValue())) {
  5542. visitInlineAsm(&I);
  5543. return;
  5544. }
  5545. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  5546. computeUsesVAFloatArgument(I, MMI);
  5547. const char *RenameFn = nullptr;
  5548. if (Function *F = I.getCalledFunction()) {
  5549. if (F->isDeclaration()) {
  5550. if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
  5551. if (unsigned IID = II->getIntrinsicID(F)) {
  5552. RenameFn = visitIntrinsicCall(I, IID);
  5553. if (!RenameFn)
  5554. return;
  5555. }
  5556. }
  5557. if (Intrinsic::ID IID = F->getIntrinsicID()) {
  5558. RenameFn = visitIntrinsicCall(I, IID);
  5559. if (!RenameFn)
  5560. return;
  5561. }
  5562. }
  5563. // Check for well-known libc/libm calls. If the function is internal, it
  5564. // can't be a library call. Don't do the check if marked as nobuiltin for
  5565. // some reason.
  5566. LibFunc::Func Func;
  5567. if (!I.isNoBuiltin() && !F->hasLocalLinkage() && F->hasName() &&
  5568. LibInfo->getLibFunc(F->getName(), Func) &&
  5569. LibInfo->hasOptimizedCodeGen(Func)) {
  5570. switch (Func) {
  5571. default: break;
  5572. case LibFunc::copysign:
  5573. case LibFunc::copysignf:
  5574. case LibFunc::copysignl:
  5575. if (I.getNumArgOperands() == 2 && // Basic sanity checks.
  5576. I.getArgOperand(0)->getType()->isFloatingPointTy() &&
  5577. I.getType() == I.getArgOperand(0)->getType() &&
  5578. I.getType() == I.getArgOperand(1)->getType() &&
  5579. I.onlyReadsMemory()) {
  5580. SDValue LHS = getValue(I.getArgOperand(0));
  5581. SDValue RHS = getValue(I.getArgOperand(1));
  5582. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
  5583. LHS.getValueType(), LHS, RHS));
  5584. return;
  5585. }
  5586. break;
  5587. case LibFunc::fabs:
  5588. case LibFunc::fabsf:
  5589. case LibFunc::fabsl:
  5590. if (visitUnaryFloatCall(I, ISD::FABS))
  5591. return;
  5592. break;
  5593. case LibFunc::fmin:
  5594. case LibFunc::fminf:
  5595. case LibFunc::fminl:
  5596. if (visitBinaryFloatCall(I, ISD::FMINNUM))
  5597. return;
  5598. break;
  5599. case LibFunc::fmax:
  5600. case LibFunc::fmaxf:
  5601. case LibFunc::fmaxl:
  5602. if (visitBinaryFloatCall(I, ISD::FMAXNUM))
  5603. return;
  5604. break;
  5605. case LibFunc::sin:
  5606. case LibFunc::sinf:
  5607. case LibFunc::sinl:
  5608. if (visitUnaryFloatCall(I, ISD::FSIN))
  5609. return;
  5610. break;
  5611. case LibFunc::cos:
  5612. case LibFunc::cosf:
  5613. case LibFunc::cosl:
  5614. if (visitUnaryFloatCall(I, ISD::FCOS))
  5615. return;
  5616. break;
  5617. case LibFunc::sqrt:
  5618. case LibFunc::sqrtf:
  5619. case LibFunc::sqrtl:
  5620. case LibFunc::sqrt_finite:
  5621. case LibFunc::sqrtf_finite:
  5622. case LibFunc::sqrtl_finite:
  5623. if (visitUnaryFloatCall(I, ISD::FSQRT))
  5624. return;
  5625. break;
  5626. case LibFunc::floor:
  5627. case LibFunc::floorf:
  5628. case LibFunc::floorl:
  5629. if (visitUnaryFloatCall(I, ISD::FFLOOR))
  5630. return;
  5631. break;
  5632. case LibFunc::nearbyint:
  5633. case LibFunc::nearbyintf:
  5634. case LibFunc::nearbyintl:
  5635. if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
  5636. return;
  5637. break;
  5638. case LibFunc::ceil:
  5639. case LibFunc::ceilf:
  5640. case LibFunc::ceill:
  5641. if (visitUnaryFloatCall(I, ISD::FCEIL))
  5642. return;
  5643. break;
  5644. case LibFunc::rint:
  5645. case LibFunc::rintf:
  5646. case LibFunc::rintl:
  5647. if (visitUnaryFloatCall(I, ISD::FRINT))
  5648. return;
  5649. break;
  5650. case LibFunc::round:
  5651. case LibFunc::roundf:
  5652. case LibFunc::roundl:
  5653. if (visitUnaryFloatCall(I, ISD::FROUND))
  5654. return;
  5655. break;
  5656. case LibFunc::trunc:
  5657. case LibFunc::truncf:
  5658. case LibFunc::truncl:
  5659. if (visitUnaryFloatCall(I, ISD::FTRUNC))
  5660. return;
  5661. break;
  5662. case LibFunc::log2:
  5663. case LibFunc::log2f:
  5664. case LibFunc::log2l:
  5665. if (visitUnaryFloatCall(I, ISD::FLOG2))
  5666. return;
  5667. break;
  5668. case LibFunc::exp2:
  5669. case LibFunc::exp2f:
  5670. case LibFunc::exp2l:
  5671. if (visitUnaryFloatCall(I, ISD::FEXP2))
  5672. return;
  5673. break;
  5674. case LibFunc::memcmp:
  5675. if (visitMemCmpCall(I))
  5676. return;
  5677. break;
  5678. case LibFunc::mempcpy:
  5679. if (visitMemPCpyCall(I))
  5680. return;
  5681. break;
  5682. case LibFunc::memchr:
  5683. if (visitMemChrCall(I))
  5684. return;
  5685. break;
  5686. case LibFunc::strcpy:
  5687. if (visitStrCpyCall(I, false))
  5688. return;
  5689. break;
  5690. case LibFunc::stpcpy:
  5691. if (visitStrCpyCall(I, true))
  5692. return;
  5693. break;
  5694. case LibFunc::strcmp:
  5695. if (visitStrCmpCall(I))
  5696. return;
  5697. break;
  5698. case LibFunc::strlen:
  5699. if (visitStrLenCall(I))
  5700. return;
  5701. break;
  5702. case LibFunc::strnlen:
  5703. if (visitStrNLenCall(I))
  5704. return;
  5705. break;
  5706. }
  5707. }
  5708. }
  5709. SDValue Callee;
  5710. if (!RenameFn)
  5711. Callee = getValue(I.getCalledValue());
  5712. else
  5713. Callee = DAG.getExternalSymbol(
  5714. RenameFn,
  5715. DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
  5716. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  5717. // have to do anything here to lower funclet bundles.
  5718. assert(!I.hasOperandBundlesOtherThan(
  5719. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  5720. "Cannot lower calls with arbitrary operand bundles!");
  5721. if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
  5722. LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
  5723. else
  5724. // Check if we can potentially perform a tail call. More detailed checking
  5725. // is be done within LowerCallTo, after more information about the call is
  5726. // known.
  5727. LowerCallTo(&I, Callee, I.isTailCall());
  5728. }
  5729. namespace {
  5730. /// AsmOperandInfo - This contains information for each constraint that we are
  5731. /// lowering.
  5732. class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
  5733. public:
  5734. /// CallOperand - If this is the result output operand or a clobber
  5735. /// this is null, otherwise it is the incoming operand to the CallInst.
  5736. /// This gets modified as the asm is processed.
  5737. SDValue CallOperand;
  5738. /// AssignedRegs - If this is a register or register class operand, this
  5739. /// contains the set of register corresponding to the operand.
  5740. RegsForValue AssignedRegs;
  5741. explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
  5742. : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr,0) {
  5743. }
  5744. /// Whether or not this operand accesses memory
  5745. bool hasMemory(const TargetLowering &TLI) const {
  5746. // Indirect operand accesses access memory.
  5747. if (isIndirect)
  5748. return true;
  5749. for (const auto &Code : Codes)
  5750. if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
  5751. return true;
  5752. return false;
  5753. }
  5754. /// getCallOperandValEVT - Return the EVT of the Value* that this operand
  5755. /// corresponds to. If there is no Value* for this operand, it returns
  5756. /// MVT::Other.
  5757. EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
  5758. const DataLayout &DL) const {
  5759. if (!CallOperandVal) return MVT::Other;
  5760. if (isa<BasicBlock>(CallOperandVal))
  5761. return TLI.getPointerTy(DL);
  5762. llvm::Type *OpTy = CallOperandVal->getType();
  5763. // FIXME: code duplicated from TargetLowering::ParseConstraints().
  5764. // If this is an indirect operand, the operand is a pointer to the
  5765. // accessed type.
  5766. if (isIndirect) {
  5767. llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
  5768. if (!PtrTy)
  5769. report_fatal_error("Indirect operand for inline asm not a pointer!");
  5770. OpTy = PtrTy->getElementType();
  5771. }
  5772. // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
  5773. if (StructType *STy = dyn_cast<StructType>(OpTy))
  5774. if (STy->getNumElements() == 1)
  5775. OpTy = STy->getElementType(0);
  5776. // If OpTy is not a single value, it may be a struct/union that we
  5777. // can tile with integers.
  5778. if (!OpTy->isSingleValueType() && OpTy->isSized()) {
  5779. unsigned BitSize = DL.getTypeSizeInBits(OpTy);
  5780. switch (BitSize) {
  5781. default: break;
  5782. case 1:
  5783. case 8:
  5784. case 16:
  5785. case 32:
  5786. case 64:
  5787. case 128:
  5788. OpTy = IntegerType::get(Context, BitSize);
  5789. break;
  5790. }
  5791. }
  5792. return TLI.getValueType(DL, OpTy, true);
  5793. }
  5794. };
  5795. typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
  5796. } // end anonymous namespace
  5797. /// Make sure that the output operand \p OpInfo and its corresponding input
  5798. /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
  5799. /// out).
  5800. static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
  5801. SDISelAsmOperandInfo &MatchingOpInfo,
  5802. SelectionDAG &DAG) {
  5803. if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
  5804. return;
  5805. const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
  5806. const auto &TLI = DAG.getTargetLoweringInfo();
  5807. std::pair<unsigned, const TargetRegisterClass *> MatchRC =
  5808. TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
  5809. OpInfo.ConstraintVT);
  5810. std::pair<unsigned, const TargetRegisterClass *> InputRC =
  5811. TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
  5812. MatchingOpInfo.ConstraintVT);
  5813. if ((OpInfo.ConstraintVT.isInteger() !=
  5814. MatchingOpInfo.ConstraintVT.isInteger()) ||
  5815. (MatchRC.second != InputRC.second)) {
  5816. // FIXME: error out in a more elegant fashion
  5817. report_fatal_error("Unsupported asm: input constraint"
  5818. " with a matching output constraint of"
  5819. " incompatible type!");
  5820. }
  5821. MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
  5822. }
  5823. /// Get a direct memory input to behave well as an indirect operand.
  5824. /// This may introduce stores, hence the need for a \p Chain.
  5825. /// \return The (possibly updated) chain.
  5826. static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
  5827. SDISelAsmOperandInfo &OpInfo,
  5828. SelectionDAG &DAG) {
  5829. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5830. // If we don't have an indirect input, put it in the constpool if we can,
  5831. // otherwise spill it to a stack slot.
  5832. // TODO: This isn't quite right. We need to handle these according to
  5833. // the addressing mode that the constraint wants. Also, this may take
  5834. // an additional register for the computation and we don't want that
  5835. // either.
  5836. // If the operand is a float, integer, or vector constant, spill to a
  5837. // constant pool entry to get its address.
  5838. const Value *OpVal = OpInfo.CallOperandVal;
  5839. if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
  5840. isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
  5841. OpInfo.CallOperand = DAG.getConstantPool(
  5842. cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
  5843. return Chain;
  5844. }
  5845. // Otherwise, create a stack slot and emit a store to it before the asm.
  5846. Type *Ty = OpVal->getType();
  5847. auto &DL = DAG.getDataLayout();
  5848. uint64_t TySize = DL.getTypeAllocSize(Ty);
  5849. unsigned Align = DL.getPrefTypeAlignment(Ty);
  5850. MachineFunction &MF = DAG.getMachineFunction();
  5851. int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
  5852. SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy(DL));
  5853. Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot,
  5854. MachinePointerInfo::getFixedStack(MF, SSFI));
  5855. OpInfo.CallOperand = StackSlot;
  5856. return Chain;
  5857. }
  5858. /// GetRegistersForValue - Assign registers (virtual or physical) for the
  5859. /// specified operand. We prefer to assign virtual registers, to allow the
  5860. /// register allocator to handle the assignment process. However, if the asm
  5861. /// uses features that we can't model on machineinstrs, we have SDISel do the
  5862. /// allocation. This produces generally horrible, but correct, code.
  5863. ///
  5864. /// OpInfo describes the operand.
  5865. ///
  5866. static void GetRegistersForValue(SelectionDAG &DAG, const TargetLowering &TLI,
  5867. const SDLoc &DL,
  5868. SDISelAsmOperandInfo &OpInfo) {
  5869. LLVMContext &Context = *DAG.getContext();
  5870. MachineFunction &MF = DAG.getMachineFunction();
  5871. SmallVector<unsigned, 4> Regs;
  5872. // If this is a constraint for a single physreg, or a constraint for a
  5873. // register class, find it.
  5874. std::pair<unsigned, const TargetRegisterClass *> PhysReg =
  5875. TLI.getRegForInlineAsmConstraint(MF.getSubtarget().getRegisterInfo(),
  5876. OpInfo.ConstraintCode,
  5877. OpInfo.ConstraintVT);
  5878. unsigned NumRegs = 1;
  5879. if (OpInfo.ConstraintVT != MVT::Other) {
  5880. // If this is a FP input in an integer register (or visa versa) insert a bit
  5881. // cast of the input value. More generally, handle any case where the input
  5882. // value disagrees with the register class we plan to stick this in.
  5883. if (OpInfo.Type == InlineAsm::isInput &&
  5884. PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
  5885. // Try to convert to the first EVT that the reg class contains. If the
  5886. // types are identical size, use a bitcast to convert (e.g. two differing
  5887. // vector types).
  5888. MVT RegVT = *PhysReg.second->vt_begin();
  5889. if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
  5890. OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
  5891. RegVT, OpInfo.CallOperand);
  5892. OpInfo.ConstraintVT = RegVT;
  5893. } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
  5894. // If the input is a FP value and we want it in FP registers, do a
  5895. // bitcast to the corresponding integer type. This turns an f64 value
  5896. // into i64, which can be passed with two i32 values on a 32-bit
  5897. // machine.
  5898. RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
  5899. OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
  5900. RegVT, OpInfo.CallOperand);
  5901. OpInfo.ConstraintVT = RegVT;
  5902. }
  5903. }
  5904. NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
  5905. }
  5906. MVT RegVT;
  5907. EVT ValueVT = OpInfo.ConstraintVT;
  5908. // If this is a constraint for a specific physical register, like {r17},
  5909. // assign it now.
  5910. if (unsigned AssignedReg = PhysReg.first) {
  5911. const TargetRegisterClass *RC = PhysReg.second;
  5912. if (OpInfo.ConstraintVT == MVT::Other)
  5913. ValueVT = *RC->vt_begin();
  5914. // Get the actual register value type. This is important, because the user
  5915. // may have asked for (e.g.) the AX register in i32 type. We need to
  5916. // remember that AX is actually i16 to get the right extension.
  5917. RegVT = *RC->vt_begin();
  5918. // This is a explicit reference to a physical register.
  5919. Regs.push_back(AssignedReg);
  5920. // If this is an expanded reference, add the rest of the regs to Regs.
  5921. if (NumRegs != 1) {
  5922. TargetRegisterClass::iterator I = RC->begin();
  5923. for (; *I != AssignedReg; ++I)
  5924. assert(I != RC->end() && "Didn't find reg!");
  5925. // Already added the first reg.
  5926. --NumRegs; ++I;
  5927. for (; NumRegs; --NumRegs, ++I) {
  5928. assert(I != RC->end() && "Ran out of registers to allocate!");
  5929. Regs.push_back(*I);
  5930. }
  5931. }
  5932. OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
  5933. return;
  5934. }
  5935. // Otherwise, if this was a reference to an LLVM register class, create vregs
  5936. // for this reference.
  5937. if (const TargetRegisterClass *RC = PhysReg.second) {
  5938. RegVT = *RC->vt_begin();
  5939. if (OpInfo.ConstraintVT == MVT::Other)
  5940. ValueVT = RegVT;
  5941. // Create the appropriate number of virtual registers.
  5942. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  5943. for (; NumRegs; --NumRegs)
  5944. Regs.push_back(RegInfo.createVirtualRegister(RC));
  5945. OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
  5946. return;
  5947. }
  5948. // Otherwise, we couldn't allocate enough registers for this.
  5949. }
  5950. static unsigned
  5951. findMatchingInlineAsmOperand(unsigned OperandNo,
  5952. const std::vector<SDValue> &AsmNodeOperands) {
  5953. // Scan until we find the definition we already emitted of this operand.
  5954. unsigned CurOp = InlineAsm::Op_FirstOperand;
  5955. for (; OperandNo; --OperandNo) {
  5956. // Advance to the next operand.
  5957. unsigned OpFlag =
  5958. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  5959. assert((InlineAsm::isRegDefKind(OpFlag) ||
  5960. InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
  5961. InlineAsm::isMemKind(OpFlag)) &&
  5962. "Skipped past definitions?");
  5963. CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
  5964. }
  5965. return CurOp;
  5966. }
  5967. /// Fill \p Regs with \p NumRegs new virtual registers of type \p RegVT
  5968. /// \return true if it has succeeded, false otherwise
  5969. static bool createVirtualRegs(SmallVector<unsigned, 4> &Regs, unsigned NumRegs,
  5970. MVT RegVT, SelectionDAG &DAG) {
  5971. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5972. MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
  5973. for (unsigned i = 0, e = NumRegs; i != e; ++i) {
  5974. if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT))
  5975. Regs.push_back(RegInfo.createVirtualRegister(RC));
  5976. else
  5977. return false;
  5978. }
  5979. return true;
  5980. }
  5981. class ExtraFlags {
  5982. unsigned Flags = 0;
  5983. public:
  5984. explicit ExtraFlags(ImmutableCallSite CS) {
  5985. const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  5986. if (IA->hasSideEffects())
  5987. Flags |= InlineAsm::Extra_HasSideEffects;
  5988. if (IA->isAlignStack())
  5989. Flags |= InlineAsm::Extra_IsAlignStack;
  5990. if (CS.isConvergent())
  5991. Flags |= InlineAsm::Extra_IsConvergent;
  5992. Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
  5993. }
  5994. void update(const llvm::TargetLowering::AsmOperandInfo &OpInfo) {
  5995. // Ideally, we would only check against memory constraints. However, the
  5996. // meaning of an Other constraint can be target-specific and we can't easily
  5997. // reason about it. Therefore, be conservative and set MayLoad/MayStore
  5998. // for Other constraints as well.
  5999. if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
  6000. OpInfo.ConstraintType == TargetLowering::C_Other) {
  6001. if (OpInfo.Type == InlineAsm::isInput)
  6002. Flags |= InlineAsm::Extra_MayLoad;
  6003. else if (OpInfo.Type == InlineAsm::isOutput)
  6004. Flags |= InlineAsm::Extra_MayStore;
  6005. else if (OpInfo.Type == InlineAsm::isClobber)
  6006. Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
  6007. }
  6008. }
  6009. unsigned get() const { return Flags; }
  6010. };
  6011. /// visitInlineAsm - Handle a call to an InlineAsm object.
  6012. ///
  6013. void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
  6014. const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  6015. /// ConstraintOperands - Information about all of the constraints.
  6016. SDISelAsmOperandInfoVector ConstraintOperands;
  6017. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6018. TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
  6019. DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
  6020. bool hasMemory = false;
  6021. // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
  6022. ExtraFlags ExtraInfo(CS);
  6023. unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
  6024. unsigned ResNo = 0; // ResNo - The result number of the next output.
  6025. for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
  6026. ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
  6027. SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
  6028. MVT OpVT = MVT::Other;
  6029. // Compute the value type for each operand.
  6030. if (OpInfo.Type == InlineAsm::isInput ||
  6031. (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
  6032. OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
  6033. // Process the call argument. BasicBlocks are labels, currently appearing
  6034. // only in asm's.
  6035. if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
  6036. OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
  6037. } else {
  6038. OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
  6039. }
  6040. OpVT =
  6041. OpInfo
  6042. .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
  6043. .getSimpleVT();
  6044. }
  6045. if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
  6046. // The return value of the call is this value. As such, there is no
  6047. // corresponding argument.
  6048. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  6049. if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
  6050. OpVT = TLI.getSimpleValueType(DAG.getDataLayout(),
  6051. STy->getElementType(ResNo));
  6052. } else {
  6053. assert(ResNo == 0 && "Asm only has one result!");
  6054. OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
  6055. }
  6056. ++ResNo;
  6057. }
  6058. OpInfo.ConstraintVT = OpVT;
  6059. if (!hasMemory)
  6060. hasMemory = OpInfo.hasMemory(TLI);
  6061. // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
  6062. // FIXME: Could we compute this on OpInfo rather than TargetConstraints[i]?
  6063. auto TargetConstraint = TargetConstraints[i];
  6064. // Compute the constraint code and ConstraintType to use.
  6065. TLI.ComputeConstraintToUse(TargetConstraint, SDValue());
  6066. ExtraInfo.update(TargetConstraint);
  6067. }
  6068. SDValue Chain, Flag;
  6069. // We won't need to flush pending loads if this asm doesn't touch
  6070. // memory and is nonvolatile.
  6071. if (hasMemory || IA->hasSideEffects())
  6072. Chain = getRoot();
  6073. else
  6074. Chain = DAG.getRoot();
  6075. // Second pass over the constraints: compute which constraint option to use
  6076. // and assign registers to constraints that want a specific physreg.
  6077. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  6078. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  6079. // If this is an output operand with a matching input operand, look up the
  6080. // matching input. If their types mismatch, e.g. one is an integer, the
  6081. // other is floating point, or their sizes are different, flag it as an
  6082. // error.
  6083. if (OpInfo.hasMatchingInput()) {
  6084. SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
  6085. patchMatchingInput(OpInfo, Input, DAG);
  6086. }
  6087. // Compute the constraint code and ConstraintType to use.
  6088. TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
  6089. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  6090. OpInfo.Type == InlineAsm::isClobber)
  6091. continue;
  6092. // If this is a memory input, and if the operand is not indirect, do what we
  6093. // need to to provide an address for the memory input.
  6094. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  6095. !OpInfo.isIndirect) {
  6096. assert((OpInfo.isMultipleAlternative ||
  6097. (OpInfo.Type == InlineAsm::isInput)) &&
  6098. "Can only indirectify direct input operands!");
  6099. // Memory operands really want the address of the value.
  6100. Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
  6101. // There is no longer a Value* corresponding to this operand.
  6102. OpInfo.CallOperandVal = nullptr;
  6103. // It is now an indirect operand.
  6104. OpInfo.isIndirect = true;
  6105. }
  6106. // If this constraint is for a specific register, allocate it before
  6107. // anything else.
  6108. if (OpInfo.ConstraintType == TargetLowering::C_Register)
  6109. GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
  6110. }
  6111. // Third pass - Loop over all of the operands, assigning virtual or physregs
  6112. // to register class operands.
  6113. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  6114. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  6115. // C_Register operands have already been allocated, Other/Memory don't need
  6116. // to be.
  6117. if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
  6118. GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
  6119. }
  6120. // AsmNodeOperands - The operands for the ISD::INLINEASM node.
  6121. std::vector<SDValue> AsmNodeOperands;
  6122. AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
  6123. AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
  6124. IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
  6125. // If we have a !srcloc metadata node associated with it, we want to attach
  6126. // this to the ultimately generated inline asm machineinstr. To do this, we
  6127. // pass in the third operand as this (potentially null) inline asm MDNode.
  6128. const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
  6129. AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
  6130. // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
  6131. // bits as operand 3.
  6132. AsmNodeOperands.push_back(DAG.getTargetConstant(
  6133. ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  6134. // Loop over all of the inputs, copying the operand values into the
  6135. // appropriate registers and processing the output regs.
  6136. RegsForValue RetValRegs;
  6137. // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
  6138. std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
  6139. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  6140. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  6141. switch (OpInfo.Type) {
  6142. case InlineAsm::isOutput: {
  6143. if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
  6144. OpInfo.ConstraintType != TargetLowering::C_Register) {
  6145. // Memory output, or 'other' output (e.g. 'X' constraint).
  6146. assert(OpInfo.isIndirect && "Memory output must be indirect operand");
  6147. unsigned ConstraintID =
  6148. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  6149. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  6150. "Failed to convert memory constraint code to constraint id.");
  6151. // Add information to the INLINEASM node to know about this output.
  6152. unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  6153. OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
  6154. AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
  6155. MVT::i32));
  6156. AsmNodeOperands.push_back(OpInfo.CallOperand);
  6157. break;
  6158. }
  6159. // Otherwise, this is a register or register class output.
  6160. // Copy the output from the appropriate register. Find a register that
  6161. // we can use.
  6162. if (OpInfo.AssignedRegs.Regs.empty()) {
  6163. emitInlineAsmError(
  6164. CS, "couldn't allocate output register for constraint '" +
  6165. Twine(OpInfo.ConstraintCode) + "'");
  6166. return;
  6167. }
  6168. // If this is an indirect operand, store through the pointer after the
  6169. // asm.
  6170. if (OpInfo.isIndirect) {
  6171. IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
  6172. OpInfo.CallOperandVal));
  6173. } else {
  6174. // This is the result value of the call.
  6175. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  6176. // Concatenate this output onto the outputs list.
  6177. RetValRegs.append(OpInfo.AssignedRegs);
  6178. }
  6179. // Add information to the INLINEASM node to know that this register is
  6180. // set.
  6181. OpInfo.AssignedRegs
  6182. .AddInlineAsmOperands(OpInfo.isEarlyClobber
  6183. ? InlineAsm::Kind_RegDefEarlyClobber
  6184. : InlineAsm::Kind_RegDef,
  6185. false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
  6186. break;
  6187. }
  6188. case InlineAsm::isInput: {
  6189. SDValue InOperandVal = OpInfo.CallOperand;
  6190. if (OpInfo.isMatchingInputConstraint()) {
  6191. // If this is required to match an output register we have already set,
  6192. // just use its register.
  6193. auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
  6194. AsmNodeOperands);
  6195. unsigned OpFlag =
  6196. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  6197. if (InlineAsm::isRegDefKind(OpFlag) ||
  6198. InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
  6199. // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
  6200. if (OpInfo.isIndirect) {
  6201. // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
  6202. emitInlineAsmError(CS, "inline asm not supported yet:"
  6203. " don't know how to handle tied "
  6204. "indirect register inputs");
  6205. return;
  6206. }
  6207. MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
  6208. SmallVector<unsigned, 4> Regs;
  6209. if (!createVirtualRegs(Regs,
  6210. InlineAsm::getNumOperandRegisters(OpFlag),
  6211. RegVT, DAG)) {
  6212. emitInlineAsmError(CS, "inline asm error: This value type register "
  6213. "class is not natively supported!");
  6214. return;
  6215. }
  6216. RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
  6217. SDLoc dl = getCurSDLoc();
  6218. // Use the produced MatchedRegs object to
  6219. MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl,
  6220. Chain, &Flag, CS.getInstruction());
  6221. MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
  6222. true, OpInfo.getMatchedOperand(), dl,
  6223. DAG, AsmNodeOperands);
  6224. break;
  6225. }
  6226. assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
  6227. assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
  6228. "Unexpected number of operands");
  6229. // Add information to the INLINEASM node to know about this input.
  6230. // See InlineAsm.h isUseOperandTiedToDef.
  6231. OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
  6232. OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
  6233. OpInfo.getMatchedOperand());
  6234. AsmNodeOperands.push_back(DAG.getTargetConstant(
  6235. OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  6236. AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
  6237. break;
  6238. }
  6239. // Treat indirect 'X' constraint as memory.
  6240. if (OpInfo.ConstraintType == TargetLowering::C_Other &&
  6241. OpInfo.isIndirect)
  6242. OpInfo.ConstraintType = TargetLowering::C_Memory;
  6243. if (OpInfo.ConstraintType == TargetLowering::C_Other) {
  6244. std::vector<SDValue> Ops;
  6245. TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
  6246. Ops, DAG);
  6247. if (Ops.empty()) {
  6248. emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
  6249. Twine(OpInfo.ConstraintCode) + "'");
  6250. return;
  6251. }
  6252. // Add information to the INLINEASM node to know about this input.
  6253. unsigned ResOpType =
  6254. InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
  6255. AsmNodeOperands.push_back(DAG.getTargetConstant(
  6256. ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  6257. AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
  6258. break;
  6259. }
  6260. if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
  6261. assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
  6262. assert(InOperandVal.getValueType() ==
  6263. TLI.getPointerTy(DAG.getDataLayout()) &&
  6264. "Memory operands expect pointer values");
  6265. unsigned ConstraintID =
  6266. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  6267. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  6268. "Failed to convert memory constraint code to constraint id.");
  6269. // Add information to the INLINEASM node to know about this input.
  6270. unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  6271. ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
  6272. AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
  6273. getCurSDLoc(),
  6274. MVT::i32));
  6275. AsmNodeOperands.push_back(InOperandVal);
  6276. break;
  6277. }
  6278. assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
  6279. OpInfo.ConstraintType == TargetLowering::C_Register) &&
  6280. "Unknown constraint type!");
  6281. // TODO: Support this.
  6282. if (OpInfo.isIndirect) {
  6283. emitInlineAsmError(
  6284. CS, "Don't know how to handle indirect register inputs yet "
  6285. "for constraint '" +
  6286. Twine(OpInfo.ConstraintCode) + "'");
  6287. return;
  6288. }
  6289. // Copy the input into the appropriate registers.
  6290. if (OpInfo.AssignedRegs.Regs.empty()) {
  6291. emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
  6292. Twine(OpInfo.ConstraintCode) + "'");
  6293. return;
  6294. }
  6295. SDLoc dl = getCurSDLoc();
  6296. OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
  6297. Chain, &Flag, CS.getInstruction());
  6298. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
  6299. dl, DAG, AsmNodeOperands);
  6300. break;
  6301. }
  6302. case InlineAsm::isClobber: {
  6303. // Add the clobbered value to the operand list, so that the register
  6304. // allocator is aware that the physreg got clobbered.
  6305. if (!OpInfo.AssignedRegs.Regs.empty())
  6306. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
  6307. false, 0, getCurSDLoc(), DAG,
  6308. AsmNodeOperands);
  6309. break;
  6310. }
  6311. }
  6312. }
  6313. // Finish up input operands. Set the input chain and add the flag last.
  6314. AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
  6315. if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
  6316. Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
  6317. DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
  6318. Flag = Chain.getValue(1);
  6319. // If this asm returns a register value, copy the result from that register
  6320. // and set it as the value of the call.
  6321. if (!RetValRegs.Regs.empty()) {
  6322. SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
  6323. Chain, &Flag, CS.getInstruction());
  6324. // FIXME: Why don't we do this for inline asms with MRVs?
  6325. if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
  6326. EVT ResultType = TLI.getValueType(DAG.getDataLayout(), CS.getType());
  6327. // If any of the results of the inline asm is a vector, it may have the
  6328. // wrong width/num elts. This can happen for register classes that can
  6329. // contain multiple different value types. The preg or vreg allocated may
  6330. // not have the same VT as was expected. Convert it to the right type
  6331. // with bit_convert.
  6332. if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
  6333. Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
  6334. ResultType, Val);
  6335. } else if (ResultType != Val.getValueType() &&
  6336. ResultType.isInteger() && Val.getValueType().isInteger()) {
  6337. // If a result value was tied to an input value, the computed result may
  6338. // have a wider width than the expected result. Extract the relevant
  6339. // portion.
  6340. Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
  6341. }
  6342. assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
  6343. }
  6344. setValue(CS.getInstruction(), Val);
  6345. // Don't need to use this as a chain in this case.
  6346. if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
  6347. return;
  6348. }
  6349. std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
  6350. // Process indirect outputs, first output all of the flagged copies out of
  6351. // physregs.
  6352. for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
  6353. RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
  6354. const Value *Ptr = IndirectStoresToEmit[i].second;
  6355. SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
  6356. Chain, &Flag, IA);
  6357. StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
  6358. }
  6359. // Emit the non-flagged stores from the physregs.
  6360. SmallVector<SDValue, 8> OutChains;
  6361. for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
  6362. SDValue Val = DAG.getStore(Chain, getCurSDLoc(), StoresToEmit[i].first,
  6363. getValue(StoresToEmit[i].second),
  6364. MachinePointerInfo(StoresToEmit[i].second));
  6365. OutChains.push_back(Val);
  6366. }
  6367. if (!OutChains.empty())
  6368. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
  6369. DAG.setRoot(Chain);
  6370. }
  6371. void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
  6372. const Twine &Message) {
  6373. LLVMContext &Ctx = *DAG.getContext();
  6374. Ctx.emitError(CS.getInstruction(), Message);
  6375. // Make sure we leave the DAG in a valid state
  6376. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6377. auto VT = TLI.getValueType(DAG.getDataLayout(), CS.getType());
  6378. setValue(CS.getInstruction(), DAG.getUNDEF(VT));
  6379. }
  6380. void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
  6381. DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
  6382. MVT::Other, getRoot(),
  6383. getValue(I.getArgOperand(0)),
  6384. DAG.getSrcValue(I.getArgOperand(0))));
  6385. }
  6386. void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
  6387. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6388. const DataLayout &DL = DAG.getDataLayout();
  6389. SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
  6390. getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
  6391. DAG.getSrcValue(I.getOperand(0)),
  6392. DL.getABITypeAlignment(I.getType()));
  6393. setValue(&I, V);
  6394. DAG.setRoot(V.getValue(1));
  6395. }
  6396. void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
  6397. DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
  6398. MVT::Other, getRoot(),
  6399. getValue(I.getArgOperand(0)),
  6400. DAG.getSrcValue(I.getArgOperand(0))));
  6401. }
  6402. void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
  6403. DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
  6404. MVT::Other, getRoot(),
  6405. getValue(I.getArgOperand(0)),
  6406. getValue(I.getArgOperand(1)),
  6407. DAG.getSrcValue(I.getArgOperand(0)),
  6408. DAG.getSrcValue(I.getArgOperand(1))));
  6409. }
  6410. SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
  6411. const Instruction &I,
  6412. SDValue Op) {
  6413. const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
  6414. if (!Range)
  6415. return Op;
  6416. Constant *Lo = cast<ConstantAsMetadata>(Range->getOperand(0))->getValue();
  6417. if (!Lo->isNullValue())
  6418. return Op;
  6419. Constant *Hi = cast<ConstantAsMetadata>(Range->getOperand(1))->getValue();
  6420. unsigned Bits = cast<ConstantInt>(Hi)->getValue().logBase2();
  6421. EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
  6422. SDLoc SL = getCurSDLoc();
  6423. SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(),
  6424. Op, DAG.getValueType(SmallVT));
  6425. unsigned NumVals = Op.getNode()->getNumValues();
  6426. if (NumVals == 1)
  6427. return ZExt;
  6428. SmallVector<SDValue, 4> Ops;
  6429. Ops.push_back(ZExt);
  6430. for (unsigned I = 1; I != NumVals; ++I)
  6431. Ops.push_back(Op.getValue(I));
  6432. return DAG.getMergeValues(Ops, SL);
  6433. }
  6434. /// \brief Populate a CallLowerinInfo (into \p CLI) based on the properties of
  6435. /// the call being lowered.
  6436. ///
  6437. /// This is a helper for lowering intrinsics that follow a target calling
  6438. /// convention or require stack pointer adjustment. Only a subset of the
  6439. /// intrinsic's operands need to participate in the calling convention.
  6440. void SelectionDAGBuilder::populateCallLoweringInfo(
  6441. TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS,
  6442. unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
  6443. bool IsPatchPoint) {
  6444. TargetLowering::ArgListTy Args;
  6445. Args.reserve(NumArgs);
  6446. // Populate the argument list.
  6447. // Attributes for args start at offset 1, after the return attribute.
  6448. for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs, AttrI = ArgIdx + 1;
  6449. ArgI != ArgE; ++ArgI) {
  6450. const Value *V = CS->getOperand(ArgI);
  6451. assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
  6452. TargetLowering::ArgListEntry Entry;
  6453. Entry.Node = getValue(V);
  6454. Entry.Ty = V->getType();
  6455. Entry.setAttributes(&CS, AttrI);
  6456. Args.push_back(Entry);
  6457. }
  6458. CLI.setDebugLoc(getCurSDLoc())
  6459. .setChain(getRoot())
  6460. .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args))
  6461. .setDiscardResult(CS->use_empty())
  6462. .setIsPatchPoint(IsPatchPoint);
  6463. }
  6464. /// \brief Add a stack map intrinsic call's live variable operands to a stackmap
  6465. /// or patchpoint target node's operand list.
  6466. ///
  6467. /// Constants are converted to TargetConstants purely as an optimization to
  6468. /// avoid constant materialization and register allocation.
  6469. ///
  6470. /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
  6471. /// generate addess computation nodes, and so ExpandISelPseudo can convert the
  6472. /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
  6473. /// address materialization and register allocation, but may also be required
  6474. /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
  6475. /// alloca in the entry block, then the runtime may assume that the alloca's
  6476. /// StackMap location can be read immediately after compilation and that the
  6477. /// location is valid at any point during execution (this is similar to the
  6478. /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
  6479. /// only available in a register, then the runtime would need to trap when
  6480. /// execution reaches the StackMap in order to read the alloca's location.
  6481. static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
  6482. const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
  6483. SelectionDAGBuilder &Builder) {
  6484. for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
  6485. SDValue OpVal = Builder.getValue(CS.getArgument(i));
  6486. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
  6487. Ops.push_back(
  6488. Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
  6489. Ops.push_back(
  6490. Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
  6491. } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
  6492. const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
  6493. Ops.push_back(Builder.DAG.getTargetFrameIndex(
  6494. FI->getIndex(), TLI.getPointerTy(Builder.DAG.getDataLayout())));
  6495. } else
  6496. Ops.push_back(OpVal);
  6497. }
  6498. }
  6499. /// \brief Lower llvm.experimental.stackmap directly to its target opcode.
  6500. void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
  6501. // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
  6502. // [live variables...])
  6503. assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
  6504. SDValue Chain, InFlag, Callee, NullPtr;
  6505. SmallVector<SDValue, 32> Ops;
  6506. SDLoc DL = getCurSDLoc();
  6507. Callee = getValue(CI.getCalledValue());
  6508. NullPtr = DAG.getIntPtrConstant(0, DL, true);
  6509. // The stackmap intrinsic only records the live variables (the arguemnts
  6510. // passed to it) and emits NOPS (if requested). Unlike the patchpoint
  6511. // intrinsic, this won't be lowered to a function call. This means we don't
  6512. // have to worry about calling conventions and target specific lowering code.
  6513. // Instead we perform the call lowering right here.
  6514. //
  6515. // chain, flag = CALLSEQ_START(chain, 0)
  6516. // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
  6517. // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
  6518. //
  6519. Chain = DAG.getCALLSEQ_START(getRoot(), NullPtr, DL);
  6520. InFlag = Chain.getValue(1);
  6521. // Add the <id> and <numBytes> constants.
  6522. SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
  6523. Ops.push_back(DAG.getTargetConstant(
  6524. cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
  6525. SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
  6526. Ops.push_back(DAG.getTargetConstant(
  6527. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
  6528. MVT::i32));
  6529. // Push live variables for the stack map.
  6530. addStackMapLiveVars(&CI, 2, DL, Ops, *this);
  6531. // We are not pushing any register mask info here on the operands list,
  6532. // because the stackmap doesn't clobber anything.
  6533. // Push the chain and the glue flag.
  6534. Ops.push_back(Chain);
  6535. Ops.push_back(InFlag);
  6536. // Create the STACKMAP node.
  6537. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  6538. SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
  6539. Chain = SDValue(SM, 0);
  6540. InFlag = Chain.getValue(1);
  6541. Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
  6542. // Stackmaps don't generate values, so nothing goes into the NodeMap.
  6543. // Set the root to the target-lowered call chain.
  6544. DAG.setRoot(Chain);
  6545. // Inform the Frame Information that we have a stackmap in this function.
  6546. FuncInfo.MF->getFrameInfo().setHasStackMap();
  6547. }
  6548. /// \brief Lower llvm.experimental.patchpoint directly to its target opcode.
  6549. void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
  6550. const BasicBlock *EHPadBB) {
  6551. // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
  6552. // i32 <numBytes>,
  6553. // i8* <target>,
  6554. // i32 <numArgs>,
  6555. // [Args...],
  6556. // [live variables...])
  6557. CallingConv::ID CC = CS.getCallingConv();
  6558. bool IsAnyRegCC = CC == CallingConv::AnyReg;
  6559. bool HasDef = !CS->getType()->isVoidTy();
  6560. SDLoc dl = getCurSDLoc();
  6561. SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
  6562. // Handle immediate and symbolic callees.
  6563. if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
  6564. Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
  6565. /*isTarget=*/true);
  6566. else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
  6567. Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
  6568. SDLoc(SymbolicCallee),
  6569. SymbolicCallee->getValueType(0));
  6570. // Get the real number of arguments participating in the call <numArgs>
  6571. SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
  6572. unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
  6573. // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
  6574. // Intrinsics include all meta-operands up to but not including CC.
  6575. unsigned NumMetaOpers = PatchPointOpers::CCPos;
  6576. assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
  6577. "Not enough arguments provided to the patchpoint intrinsic");
  6578. // For AnyRegCC the arguments are lowered later on manually.
  6579. unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
  6580. Type *ReturnTy =
  6581. IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
  6582. TargetLowering::CallLoweringInfo CLI(DAG);
  6583. populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy,
  6584. true);
  6585. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  6586. SDNode *CallEnd = Result.second.getNode();
  6587. if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
  6588. CallEnd = CallEnd->getOperand(0).getNode();
  6589. /// Get a call instruction from the call sequence chain.
  6590. /// Tail calls are not allowed.
  6591. assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
  6592. "Expected a callseq node.");
  6593. SDNode *Call = CallEnd->getOperand(0).getNode();
  6594. bool HasGlue = Call->getGluedNode();
  6595. // Replace the target specific call node with the patchable intrinsic.
  6596. SmallVector<SDValue, 8> Ops;
  6597. // Add the <id> and <numBytes> constants.
  6598. SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
  6599. Ops.push_back(DAG.getTargetConstant(
  6600. cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
  6601. SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
  6602. Ops.push_back(DAG.getTargetConstant(
  6603. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
  6604. MVT::i32));
  6605. // Add the callee.
  6606. Ops.push_back(Callee);
  6607. // Adjust <numArgs> to account for any arguments that have been passed on the
  6608. // stack instead.
  6609. // Call Node: Chain, Target, {Args}, RegMask, [Glue]
  6610. unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
  6611. NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
  6612. Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
  6613. // Add the calling convention
  6614. Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
  6615. // Add the arguments we omitted previously. The register allocator should
  6616. // place these in any free register.
  6617. if (IsAnyRegCC)
  6618. for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
  6619. Ops.push_back(getValue(CS.getArgument(i)));
  6620. // Push the arguments from the call instruction up to the register mask.
  6621. SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
  6622. Ops.append(Call->op_begin() + 2, e);
  6623. // Push live variables for the stack map.
  6624. addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
  6625. // Push the register mask info.
  6626. if (HasGlue)
  6627. Ops.push_back(*(Call->op_end()-2));
  6628. else
  6629. Ops.push_back(*(Call->op_end()-1));
  6630. // Push the chain (this is originally the first operand of the call, but
  6631. // becomes now the last or second to last operand).
  6632. Ops.push_back(*(Call->op_begin()));
  6633. // Push the glue flag (last operand).
  6634. if (HasGlue)
  6635. Ops.push_back(*(Call->op_end()-1));
  6636. SDVTList NodeTys;
  6637. if (IsAnyRegCC && HasDef) {
  6638. // Create the return types based on the intrinsic definition
  6639. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6640. SmallVector<EVT, 3> ValueVTs;
  6641. ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
  6642. assert(ValueVTs.size() == 1 && "Expected only one return value type.");
  6643. // There is always a chain and a glue type at the end
  6644. ValueVTs.push_back(MVT::Other);
  6645. ValueVTs.push_back(MVT::Glue);
  6646. NodeTys = DAG.getVTList(ValueVTs);
  6647. } else
  6648. NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  6649. // Replace the target specific call node with a PATCHPOINT node.
  6650. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
  6651. dl, NodeTys, Ops);
  6652. // Update the NodeMap.
  6653. if (HasDef) {
  6654. if (IsAnyRegCC)
  6655. setValue(CS.getInstruction(), SDValue(MN, 0));
  6656. else
  6657. setValue(CS.getInstruction(), Result.first);
  6658. }
  6659. // Fixup the consumers of the intrinsic. The chain and glue may be used in the
  6660. // call sequence. Furthermore the location of the chain and glue can change
  6661. // when the AnyReg calling convention is used and the intrinsic returns a
  6662. // value.
  6663. if (IsAnyRegCC && HasDef) {
  6664. SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
  6665. SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
  6666. DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
  6667. } else
  6668. DAG.ReplaceAllUsesWith(Call, MN);
  6669. DAG.DeleteNode(Call);
  6670. // Inform the Frame Information that we have a patchpoint in this function.
  6671. FuncInfo.MF->getFrameInfo().setHasPatchPoint();
  6672. }
  6673. /// Returns an AttributeSet representing the attributes applied to the return
  6674. /// value of the given call.
  6675. static AttributeSet getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
  6676. SmallVector<Attribute::AttrKind, 2> Attrs;
  6677. if (CLI.RetSExt)
  6678. Attrs.push_back(Attribute::SExt);
  6679. if (CLI.RetZExt)
  6680. Attrs.push_back(Attribute::ZExt);
  6681. if (CLI.IsInReg)
  6682. Attrs.push_back(Attribute::InReg);
  6683. return AttributeSet::get(CLI.RetTy->getContext(), AttributeSet::ReturnIndex,
  6684. Attrs);
  6685. }
  6686. /// TargetLowering::LowerCallTo - This is the default LowerCallTo
  6687. /// implementation, which just calls LowerCall.
  6688. /// FIXME: When all targets are
  6689. /// migrated to using LowerCall, this hook should be integrated into SDISel.
  6690. std::pair<SDValue, SDValue>
  6691. TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
  6692. // Handle the incoming return values from the call.
  6693. CLI.Ins.clear();
  6694. Type *OrigRetTy = CLI.RetTy;
  6695. SmallVector<EVT, 4> RetTys;
  6696. SmallVector<uint64_t, 4> Offsets;
  6697. auto &DL = CLI.DAG.getDataLayout();
  6698. ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
  6699. SmallVector<ISD::OutputArg, 4> Outs;
  6700. GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
  6701. bool CanLowerReturn =
  6702. this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
  6703. CLI.IsVarArg, Outs, CLI.RetTy->getContext());
  6704. SDValue DemoteStackSlot;
  6705. int DemoteStackIdx = -100;
  6706. if (!CanLowerReturn) {
  6707. // FIXME: equivalent assert?
  6708. // assert(!CS.hasInAllocaArgument() &&
  6709. // "sret demotion is incompatible with inalloca");
  6710. uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
  6711. unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
  6712. MachineFunction &MF = CLI.DAG.getMachineFunction();
  6713. DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
  6714. Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy);
  6715. DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getPointerTy(DL));
  6716. ArgListEntry Entry;
  6717. Entry.Node = DemoteStackSlot;
  6718. Entry.Ty = StackSlotPtrType;
  6719. Entry.isSExt = false;
  6720. Entry.isZExt = false;
  6721. Entry.isInReg = false;
  6722. Entry.isSRet = true;
  6723. Entry.isNest = false;
  6724. Entry.isByVal = false;
  6725. Entry.isReturned = false;
  6726. Entry.isSwiftSelf = false;
  6727. Entry.isSwiftError = false;
  6728. Entry.Alignment = Align;
  6729. CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
  6730. CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
  6731. // sret demotion isn't compatible with tail-calls, since the sret argument
  6732. // points into the callers stack frame.
  6733. CLI.IsTailCall = false;
  6734. } else {
  6735. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  6736. EVT VT = RetTys[I];
  6737. MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
  6738. unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
  6739. for (unsigned i = 0; i != NumRegs; ++i) {
  6740. ISD::InputArg MyFlags;
  6741. MyFlags.VT = RegisterVT;
  6742. MyFlags.ArgVT = VT;
  6743. MyFlags.Used = CLI.IsReturnValueUsed;
  6744. if (CLI.RetSExt)
  6745. MyFlags.Flags.setSExt();
  6746. if (CLI.RetZExt)
  6747. MyFlags.Flags.setZExt();
  6748. if (CLI.IsInReg)
  6749. MyFlags.Flags.setInReg();
  6750. CLI.Ins.push_back(MyFlags);
  6751. }
  6752. }
  6753. }
  6754. // We push in swifterror return as the last element of CLI.Ins.
  6755. ArgListTy &Args = CLI.getArgs();
  6756. if (supportSwiftError()) {
  6757. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  6758. if (Args[i].isSwiftError) {
  6759. ISD::InputArg MyFlags;
  6760. MyFlags.VT = getPointerTy(DL);
  6761. MyFlags.ArgVT = EVT(getPointerTy(DL));
  6762. MyFlags.Flags.setSwiftError();
  6763. CLI.Ins.push_back(MyFlags);
  6764. }
  6765. }
  6766. }
  6767. // Handle all of the outgoing arguments.
  6768. CLI.Outs.clear();
  6769. CLI.OutVals.clear();
  6770. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  6771. SmallVector<EVT, 4> ValueVTs;
  6772. ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
  6773. Type *FinalType = Args[i].Ty;
  6774. if (Args[i].isByVal)
  6775. FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
  6776. bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
  6777. FinalType, CLI.CallConv, CLI.IsVarArg);
  6778. for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
  6779. ++Value) {
  6780. EVT VT = ValueVTs[Value];
  6781. Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
  6782. SDValue Op = SDValue(Args[i].Node.getNode(),
  6783. Args[i].Node.getResNo() + Value);
  6784. ISD::ArgFlagsTy Flags;
  6785. unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
  6786. if (Args[i].isZExt)
  6787. Flags.setZExt();
  6788. if (Args[i].isSExt)
  6789. Flags.setSExt();
  6790. if (Args[i].isInReg)
  6791. Flags.setInReg();
  6792. if (Args[i].isSRet)
  6793. Flags.setSRet();
  6794. if (Args[i].isSwiftSelf)
  6795. Flags.setSwiftSelf();
  6796. if (Args[i].isSwiftError)
  6797. Flags.setSwiftError();
  6798. if (Args[i].isByVal)
  6799. Flags.setByVal();
  6800. if (Args[i].isInAlloca) {
  6801. Flags.setInAlloca();
  6802. // Set the byval flag for CCAssignFn callbacks that don't know about
  6803. // inalloca. This way we can know how many bytes we should've allocated
  6804. // and how many bytes a callee cleanup function will pop. If we port
  6805. // inalloca to more targets, we'll have to add custom inalloca handling
  6806. // in the various CC lowering callbacks.
  6807. Flags.setByVal();
  6808. }
  6809. if (Args[i].isByVal || Args[i].isInAlloca) {
  6810. PointerType *Ty = cast<PointerType>(Args[i].Ty);
  6811. Type *ElementTy = Ty->getElementType();
  6812. Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
  6813. // For ByVal, alignment should come from FE. BE will guess if this
  6814. // info is not there but there are cases it cannot get right.
  6815. unsigned FrameAlign;
  6816. if (Args[i].Alignment)
  6817. FrameAlign = Args[i].Alignment;
  6818. else
  6819. FrameAlign = getByValTypeAlignment(ElementTy, DL);
  6820. Flags.setByValAlign(FrameAlign);
  6821. }
  6822. if (Args[i].isNest)
  6823. Flags.setNest();
  6824. if (NeedsRegBlock)
  6825. Flags.setInConsecutiveRegs();
  6826. Flags.setOrigAlign(OriginalAlignment);
  6827. MVT PartVT = getRegisterType(CLI.RetTy->getContext(), VT);
  6828. unsigned NumParts = getNumRegisters(CLI.RetTy->getContext(), VT);
  6829. SmallVector<SDValue, 4> Parts(NumParts);
  6830. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  6831. if (Args[i].isSExt)
  6832. ExtendKind = ISD::SIGN_EXTEND;
  6833. else if (Args[i].isZExt)
  6834. ExtendKind = ISD::ZERO_EXTEND;
  6835. // Conservatively only handle 'returned' on non-vectors for now
  6836. if (Args[i].isReturned && !Op.getValueType().isVector()) {
  6837. assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
  6838. "unexpected use of 'returned'");
  6839. // Before passing 'returned' to the target lowering code, ensure that
  6840. // either the register MVT and the actual EVT are the same size or that
  6841. // the return value and argument are extended in the same way; in these
  6842. // cases it's safe to pass the argument register value unchanged as the
  6843. // return register value (although it's at the target's option whether
  6844. // to do so)
  6845. // TODO: allow code generation to take advantage of partially preserved
  6846. // registers rather than clobbering the entire register when the
  6847. // parameter extension method is not compatible with the return
  6848. // extension method
  6849. if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
  6850. (ExtendKind != ISD::ANY_EXTEND &&
  6851. CLI.RetSExt == Args[i].isSExt && CLI.RetZExt == Args[i].isZExt))
  6852. Flags.setReturned();
  6853. }
  6854. getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
  6855. CLI.CS ? CLI.CS->getInstruction() : nullptr, ExtendKind);
  6856. for (unsigned j = 0; j != NumParts; ++j) {
  6857. // if it isn't first piece, alignment must be 1
  6858. ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
  6859. i < CLI.NumFixedArgs,
  6860. i, j*Parts[j].getValueType().getStoreSize());
  6861. if (NumParts > 1 && j == 0)
  6862. MyFlags.Flags.setSplit();
  6863. else if (j != 0) {
  6864. MyFlags.Flags.setOrigAlign(1);
  6865. if (j == NumParts - 1)
  6866. MyFlags.Flags.setSplitEnd();
  6867. }
  6868. CLI.Outs.push_back(MyFlags);
  6869. CLI.OutVals.push_back(Parts[j]);
  6870. }
  6871. if (NeedsRegBlock && Value == NumValues - 1)
  6872. CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
  6873. }
  6874. }
  6875. SmallVector<SDValue, 4> InVals;
  6876. CLI.Chain = LowerCall(CLI, InVals);
  6877. // Update CLI.InVals to use outside of this function.
  6878. CLI.InVals = InVals;
  6879. // Verify that the target's LowerCall behaved as expected.
  6880. assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
  6881. "LowerCall didn't return a valid chain!");
  6882. assert((!CLI.IsTailCall || InVals.empty()) &&
  6883. "LowerCall emitted a return value for a tail call!");
  6884. assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
  6885. "LowerCall didn't emit the correct number of values!");
  6886. // For a tail call, the return value is merely live-out and there aren't
  6887. // any nodes in the DAG representing it. Return a special value to
  6888. // indicate that a tail call has been emitted and no more Instructions
  6889. // should be processed in the current block.
  6890. if (CLI.IsTailCall) {
  6891. CLI.DAG.setRoot(CLI.Chain);
  6892. return std::make_pair(SDValue(), SDValue());
  6893. }
  6894. #ifndef NDEBUG
  6895. for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
  6896. assert(InVals[i].getNode() && "LowerCall emitted a null value!");
  6897. assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
  6898. "LowerCall emitted a value with the wrong type!");
  6899. }
  6900. #endif
  6901. SmallVector<SDValue, 4> ReturnValues;
  6902. if (!CanLowerReturn) {
  6903. // The instruction result is the result of loading from the
  6904. // hidden sret parameter.
  6905. SmallVector<EVT, 1> PVTs;
  6906. Type *PtrRetTy = PointerType::getUnqual(OrigRetTy);
  6907. ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
  6908. assert(PVTs.size() == 1 && "Pointers should fit in one register");
  6909. EVT PtrVT = PVTs[0];
  6910. unsigned NumValues = RetTys.size();
  6911. ReturnValues.resize(NumValues);
  6912. SmallVector<SDValue, 4> Chains(NumValues);
  6913. // An aggregate return value cannot wrap around the address space, so
  6914. // offsets to its parts don't wrap either.
  6915. SDNodeFlags Flags;
  6916. Flags.setNoUnsignedWrap(true);
  6917. for (unsigned i = 0; i < NumValues; ++i) {
  6918. SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
  6919. CLI.DAG.getConstant(Offsets[i], CLI.DL,
  6920. PtrVT), &Flags);
  6921. SDValue L = CLI.DAG.getLoad(
  6922. RetTys[i], CLI.DL, CLI.Chain, Add,
  6923. MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
  6924. DemoteStackIdx, Offsets[i]),
  6925. /* Alignment = */ 1);
  6926. ReturnValues[i] = L;
  6927. Chains[i] = L.getValue(1);
  6928. }
  6929. CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
  6930. } else {
  6931. // Collect the legal value parts into potentially illegal values
  6932. // that correspond to the original function's return values.
  6933. Optional<ISD::NodeType> AssertOp;
  6934. if (CLI.RetSExt)
  6935. AssertOp = ISD::AssertSext;
  6936. else if (CLI.RetZExt)
  6937. AssertOp = ISD::AssertZext;
  6938. unsigned CurReg = 0;
  6939. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  6940. EVT VT = RetTys[I];
  6941. MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
  6942. unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
  6943. ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
  6944. NumRegs, RegisterVT, VT, nullptr,
  6945. AssertOp));
  6946. CurReg += NumRegs;
  6947. }
  6948. // For a function returning void, there is no return value. We can't create
  6949. // such a node, so we just return a null return value in that case. In
  6950. // that case, nothing will actually look at the value.
  6951. if (ReturnValues.empty())
  6952. return std::make_pair(SDValue(), CLI.Chain);
  6953. }
  6954. SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
  6955. CLI.DAG.getVTList(RetTys), ReturnValues);
  6956. return std::make_pair(Res, CLI.Chain);
  6957. }
  6958. void TargetLowering::LowerOperationWrapper(SDNode *N,
  6959. SmallVectorImpl<SDValue> &Results,
  6960. SelectionDAG &DAG) const {
  6961. if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
  6962. Results.push_back(Res);
  6963. }
  6964. SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
  6965. llvm_unreachable("LowerOperation not implemented for this target!");
  6966. }
  6967. void
  6968. SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
  6969. SDValue Op = getNonRegisterValue(V);
  6970. assert((Op.getOpcode() != ISD::CopyFromReg ||
  6971. cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
  6972. "Copy from a reg to the same reg!");
  6973. assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
  6974. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6975. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
  6976. V->getType());
  6977. SDValue Chain = DAG.getEntryNode();
  6978. ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
  6979. FuncInfo.PreferredExtendType.end())
  6980. ? ISD::ANY_EXTEND
  6981. : FuncInfo.PreferredExtendType[V];
  6982. RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
  6983. PendingExports.push_back(Chain);
  6984. }
  6985. #include "llvm/CodeGen/SelectionDAGISel.h"
  6986. /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
  6987. /// entry block, return true. This includes arguments used by switches, since
  6988. /// the switch may expand into multiple basic blocks.
  6989. static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
  6990. // With FastISel active, we may be splitting blocks, so force creation
  6991. // of virtual registers for all non-dead arguments.
  6992. if (FastISel)
  6993. return A->use_empty();
  6994. const BasicBlock &Entry = A->getParent()->front();
  6995. for (const User *U : A->users())
  6996. if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
  6997. return false; // Use not in entry block.
  6998. return true;
  6999. }
  7000. void SelectionDAGISel::LowerArguments(const Function &F) {
  7001. SelectionDAG &DAG = SDB->DAG;
  7002. SDLoc dl = SDB->getCurSDLoc();
  7003. const DataLayout &DL = DAG.getDataLayout();
  7004. SmallVector<ISD::InputArg, 16> Ins;
  7005. if (!FuncInfo->CanLowerReturn) {
  7006. // Put in an sret pointer parameter before all the other parameters.
  7007. SmallVector<EVT, 1> ValueVTs;
  7008. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  7009. PointerType::getUnqual(F.getReturnType()), ValueVTs);
  7010. // NOTE: Assuming that a pointer will never break down to more than one VT
  7011. // or one register.
  7012. ISD::ArgFlagsTy Flags;
  7013. Flags.setSRet();
  7014. MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
  7015. ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
  7016. ISD::InputArg::NoArgIndex, 0);
  7017. Ins.push_back(RetArg);
  7018. }
  7019. // Set up the incoming argument description vector.
  7020. unsigned Idx = 1;
  7021. for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
  7022. I != E; ++I, ++Idx) {
  7023. SmallVector<EVT, 4> ValueVTs;
  7024. ComputeValueVTs(*TLI, DAG.getDataLayout(), I->getType(), ValueVTs);
  7025. bool isArgValueUsed = !I->use_empty();
  7026. unsigned PartBase = 0;
  7027. Type *FinalType = I->getType();
  7028. if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
  7029. FinalType = cast<PointerType>(FinalType)->getElementType();
  7030. bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
  7031. FinalType, F.getCallingConv(), F.isVarArg());
  7032. for (unsigned Value = 0, NumValues = ValueVTs.size();
  7033. Value != NumValues; ++Value) {
  7034. EVT VT = ValueVTs[Value];
  7035. Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
  7036. ISD::ArgFlagsTy Flags;
  7037. unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
  7038. if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
  7039. Flags.setZExt();
  7040. if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
  7041. Flags.setSExt();
  7042. if (F.getAttributes().hasAttribute(Idx, Attribute::InReg))
  7043. Flags.setInReg();
  7044. if (F.getAttributes().hasAttribute(Idx, Attribute::StructRet))
  7045. Flags.setSRet();
  7046. if (F.getAttributes().hasAttribute(Idx, Attribute::SwiftSelf))
  7047. Flags.setSwiftSelf();
  7048. if (F.getAttributes().hasAttribute(Idx, Attribute::SwiftError))
  7049. Flags.setSwiftError();
  7050. if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
  7051. Flags.setByVal();
  7052. if (F.getAttributes().hasAttribute(Idx, Attribute::InAlloca)) {
  7053. Flags.setInAlloca();
  7054. // Set the byval flag for CCAssignFn callbacks that don't know about
  7055. // inalloca. This way we can know how many bytes we should've allocated
  7056. // and how many bytes a callee cleanup function will pop. If we port
  7057. // inalloca to more targets, we'll have to add custom inalloca handling
  7058. // in the various CC lowering callbacks.
  7059. Flags.setByVal();
  7060. }
  7061. if (F.getCallingConv() == CallingConv::X86_INTR) {
  7062. // IA Interrupt passes frame (1st parameter) by value in the stack.
  7063. if (Idx == 1)
  7064. Flags.setByVal();
  7065. }
  7066. if (Flags.isByVal() || Flags.isInAlloca()) {
  7067. PointerType *Ty = cast<PointerType>(I->getType());
  7068. Type *ElementTy = Ty->getElementType();
  7069. Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
  7070. // For ByVal, alignment should be passed from FE. BE will guess if
  7071. // this info is not there but there are cases it cannot get right.
  7072. unsigned FrameAlign;
  7073. if (F.getParamAlignment(Idx))
  7074. FrameAlign = F.getParamAlignment(Idx);
  7075. else
  7076. FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
  7077. Flags.setByValAlign(FrameAlign);
  7078. }
  7079. if (F.getAttributes().hasAttribute(Idx, Attribute::Nest))
  7080. Flags.setNest();
  7081. if (NeedsRegBlock)
  7082. Flags.setInConsecutiveRegs();
  7083. Flags.setOrigAlign(OriginalAlignment);
  7084. MVT RegisterVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
  7085. unsigned NumRegs = TLI->getNumRegisters(*CurDAG->getContext(), VT);
  7086. for (unsigned i = 0; i != NumRegs; ++i) {
  7087. ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
  7088. Idx-1, PartBase+i*RegisterVT.getStoreSize());
  7089. if (NumRegs > 1 && i == 0)
  7090. MyFlags.Flags.setSplit();
  7091. // if it isn't first piece, alignment must be 1
  7092. else if (i > 0) {
  7093. MyFlags.Flags.setOrigAlign(1);
  7094. if (i == NumRegs - 1)
  7095. MyFlags.Flags.setSplitEnd();
  7096. }
  7097. Ins.push_back(MyFlags);
  7098. }
  7099. if (NeedsRegBlock && Value == NumValues - 1)
  7100. Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
  7101. PartBase += VT.getStoreSize();
  7102. }
  7103. }
  7104. // Call the target to set up the argument values.
  7105. SmallVector<SDValue, 8> InVals;
  7106. SDValue NewRoot = TLI->LowerFormalArguments(
  7107. DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
  7108. // Verify that the target's LowerFormalArguments behaved as expected.
  7109. assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
  7110. "LowerFormalArguments didn't return a valid chain!");
  7111. assert(InVals.size() == Ins.size() &&
  7112. "LowerFormalArguments didn't emit the correct number of values!");
  7113. DEBUG({
  7114. for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
  7115. assert(InVals[i].getNode() &&
  7116. "LowerFormalArguments emitted a null value!");
  7117. assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
  7118. "LowerFormalArguments emitted a value with the wrong type!");
  7119. }
  7120. });
  7121. // Update the DAG with the new chain value resulting from argument lowering.
  7122. DAG.setRoot(NewRoot);
  7123. // Set up the argument values.
  7124. unsigned i = 0;
  7125. Idx = 1;
  7126. if (!FuncInfo->CanLowerReturn) {
  7127. // Create a virtual register for the sret pointer, and put in a copy
  7128. // from the sret argument into it.
  7129. SmallVector<EVT, 1> ValueVTs;
  7130. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  7131. PointerType::getUnqual(F.getReturnType()), ValueVTs);
  7132. MVT VT = ValueVTs[0].getSimpleVT();
  7133. MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
  7134. Optional<ISD::NodeType> AssertOp = None;
  7135. SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
  7136. RegVT, VT, nullptr, AssertOp);
  7137. MachineFunction& MF = SDB->DAG.getMachineFunction();
  7138. MachineRegisterInfo& RegInfo = MF.getRegInfo();
  7139. unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
  7140. FuncInfo->DemoteRegister = SRetReg;
  7141. NewRoot =
  7142. SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
  7143. DAG.setRoot(NewRoot);
  7144. // i indexes lowered arguments. Bump it past the hidden sret argument.
  7145. // Idx indexes LLVM arguments. Don't touch it.
  7146. ++i;
  7147. }
  7148. for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
  7149. ++I, ++Idx) {
  7150. SmallVector<SDValue, 4> ArgValues;
  7151. SmallVector<EVT, 4> ValueVTs;
  7152. ComputeValueVTs(*TLI, DAG.getDataLayout(), I->getType(), ValueVTs);
  7153. unsigned NumValues = ValueVTs.size();
  7154. // If this argument is unused then remember its value. It is used to generate
  7155. // debugging information.
  7156. bool isSwiftErrorArg =
  7157. TLI->supportSwiftError() &&
  7158. F.getAttributes().hasAttribute(Idx, Attribute::SwiftError);
  7159. if (I->use_empty() && NumValues && !isSwiftErrorArg) {
  7160. SDB->setUnusedArgValue(&*I, InVals[i]);
  7161. // Also remember any frame index for use in FastISel.
  7162. if (FrameIndexSDNode *FI =
  7163. dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
  7164. FuncInfo->setArgumentFrameIndex(&*I, FI->getIndex());
  7165. }
  7166. for (unsigned Val = 0; Val != NumValues; ++Val) {
  7167. EVT VT = ValueVTs[Val];
  7168. MVT PartVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
  7169. unsigned NumParts = TLI->getNumRegisters(*CurDAG->getContext(), VT);
  7170. // Even an apparant 'unused' swifterror argument needs to be returned. So
  7171. // we do generate a copy for it that can be used on return from the
  7172. // function.
  7173. if (!I->use_empty() || isSwiftErrorArg) {
  7174. Optional<ISD::NodeType> AssertOp;
  7175. if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
  7176. AssertOp = ISD::AssertSext;
  7177. else if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
  7178. AssertOp = ISD::AssertZext;
  7179. ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
  7180. NumParts, PartVT, VT,
  7181. nullptr, AssertOp));
  7182. }
  7183. i += NumParts;
  7184. }
  7185. // We don't need to do anything else for unused arguments.
  7186. if (ArgValues.empty())
  7187. continue;
  7188. // Note down frame index.
  7189. if (FrameIndexSDNode *FI =
  7190. dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
  7191. FuncInfo->setArgumentFrameIndex(&*I, FI->getIndex());
  7192. SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
  7193. SDB->getCurSDLoc());
  7194. SDB->setValue(&*I, Res);
  7195. if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
  7196. if (LoadSDNode *LNode =
  7197. dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
  7198. if (FrameIndexSDNode *FI =
  7199. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  7200. FuncInfo->setArgumentFrameIndex(&*I, FI->getIndex());
  7201. }
  7202. // Update the SwiftErrorVRegDefMap.
  7203. if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
  7204. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  7205. if (TargetRegisterInfo::isVirtualRegister(Reg))
  7206. FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB,
  7207. FuncInfo->SwiftErrorArg, Reg);
  7208. }
  7209. // If this argument is live outside of the entry block, insert a copy from
  7210. // wherever we got it to the vreg that other BB's will reference it as.
  7211. if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
  7212. // If we can, though, try to skip creating an unnecessary vreg.
  7213. // FIXME: This isn't very clean... it would be nice to make this more
  7214. // general. It's also subtly incompatible with the hacks FastISel
  7215. // uses with vregs.
  7216. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  7217. if (TargetRegisterInfo::isVirtualRegister(Reg)) {
  7218. FuncInfo->ValueMap[&*I] = Reg;
  7219. continue;
  7220. }
  7221. }
  7222. if (!isOnlyUsedInEntryBlock(&*I, TM.Options.EnableFastISel)) {
  7223. FuncInfo->InitializeRegForValue(&*I);
  7224. SDB->CopyToExportRegsIfNeeded(&*I);
  7225. }
  7226. }
  7227. assert(i == InVals.size() && "Argument register count mismatch!");
  7228. // Finally, if the target has anything special to do, allow it to do so.
  7229. EmitFunctionEntryCode();
  7230. }
  7231. /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
  7232. /// ensure constants are generated when needed. Remember the virtual registers
  7233. /// that need to be added to the Machine PHI nodes as input. We cannot just
  7234. /// directly add them, because expansion might result in multiple MBB's for one
  7235. /// BB. As such, the start of the BB might correspond to a different MBB than
  7236. /// the end.
  7237. ///
  7238. void
  7239. SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
  7240. const TerminatorInst *TI = LLVMBB->getTerminator();
  7241. SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
  7242. // Check PHI nodes in successors that expect a value to be available from this
  7243. // block.
  7244. for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
  7245. const BasicBlock *SuccBB = TI->getSuccessor(succ);
  7246. if (!isa<PHINode>(SuccBB->begin())) continue;
  7247. MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
  7248. // If this terminator has multiple identical successors (common for
  7249. // switches), only handle each succ once.
  7250. if (!SuccsHandled.insert(SuccMBB).second)
  7251. continue;
  7252. MachineBasicBlock::iterator MBBI = SuccMBB->begin();
  7253. // At this point we know that there is a 1-1 correspondence between LLVM PHI
  7254. // nodes and Machine PHI nodes, but the incoming operands have not been
  7255. // emitted yet.
  7256. for (BasicBlock::const_iterator I = SuccBB->begin();
  7257. const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
  7258. // Ignore dead phi's.
  7259. if (PN->use_empty()) continue;
  7260. // Skip empty types
  7261. if (PN->getType()->isEmptyTy())
  7262. continue;
  7263. unsigned Reg;
  7264. const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
  7265. if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
  7266. unsigned &RegOut = ConstantsOut[C];
  7267. if (RegOut == 0) {
  7268. RegOut = FuncInfo.CreateRegs(C->getType());
  7269. CopyValueToVirtualRegister(C, RegOut);
  7270. }
  7271. Reg = RegOut;
  7272. } else {
  7273. DenseMap<const Value *, unsigned>::iterator I =
  7274. FuncInfo.ValueMap.find(PHIOp);
  7275. if (I != FuncInfo.ValueMap.end())
  7276. Reg = I->second;
  7277. else {
  7278. assert(isa<AllocaInst>(PHIOp) &&
  7279. FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
  7280. "Didn't codegen value into a register!??");
  7281. Reg = FuncInfo.CreateRegs(PHIOp->getType());
  7282. CopyValueToVirtualRegister(PHIOp, Reg);
  7283. }
  7284. }
  7285. // Remember that this register needs to added to the machine PHI node as
  7286. // the input for this MBB.
  7287. SmallVector<EVT, 4> ValueVTs;
  7288. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7289. ComputeValueVTs(TLI, DAG.getDataLayout(), PN->getType(), ValueVTs);
  7290. for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
  7291. EVT VT = ValueVTs[vti];
  7292. unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
  7293. for (unsigned i = 0, e = NumRegisters; i != e; ++i)
  7294. FuncInfo.PHINodesToUpdate.push_back(
  7295. std::make_pair(&*MBBI++, Reg + i));
  7296. Reg += NumRegisters;
  7297. }
  7298. }
  7299. }
  7300. ConstantsOut.clear();
  7301. }
  7302. /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
  7303. /// is 0.
  7304. MachineBasicBlock *
  7305. SelectionDAGBuilder::StackProtectorDescriptor::
  7306. AddSuccessorMBB(const BasicBlock *BB,
  7307. MachineBasicBlock *ParentMBB,
  7308. bool IsLikely,
  7309. MachineBasicBlock *SuccMBB) {
  7310. // If SuccBB has not been created yet, create it.
  7311. if (!SuccMBB) {
  7312. MachineFunction *MF = ParentMBB->getParent();
  7313. MachineFunction::iterator BBI(ParentMBB);
  7314. SuccMBB = MF->CreateMachineBasicBlock(BB);
  7315. MF->insert(++BBI, SuccMBB);
  7316. }
  7317. // Add it as a successor of ParentMBB.
  7318. ParentMBB->addSuccessor(
  7319. SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
  7320. return SuccMBB;
  7321. }
  7322. MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
  7323. MachineFunction::iterator I(MBB);
  7324. if (++I == FuncInfo.MF->end())
  7325. return nullptr;
  7326. return &*I;
  7327. }
  7328. /// During lowering new call nodes can be created (such as memset, etc.).
  7329. /// Those will become new roots of the current DAG, but complications arise
  7330. /// when they are tail calls. In such cases, the call lowering will update
  7331. /// the root, but the builder still needs to know that a tail call has been
  7332. /// lowered in order to avoid generating an additional return.
  7333. void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
  7334. // If the node is null, we do have a tail call.
  7335. if (MaybeTC.getNode() != nullptr)
  7336. DAG.setRoot(MaybeTC);
  7337. else
  7338. HasTailCall = true;
  7339. }
  7340. bool SelectionDAGBuilder::isDense(const CaseClusterVector &Clusters,
  7341. const SmallVectorImpl<unsigned> &TotalCases,
  7342. unsigned First, unsigned Last,
  7343. unsigned Density) const {
  7344. assert(Last >= First);
  7345. assert(TotalCases[Last] >= TotalCases[First]);
  7346. const APInt &LowCase = Clusters[First].Low->getValue();
  7347. const APInt &HighCase = Clusters[Last].High->getValue();
  7348. assert(LowCase.getBitWidth() == HighCase.getBitWidth());
  7349. // FIXME: A range of consecutive cases has 100% density, but only requires one
  7350. // comparison to lower. We should discriminate against such consecutive ranges
  7351. // in jump tables.
  7352. uint64_t Diff = (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100);
  7353. uint64_t Range = Diff + 1;
  7354. uint64_t NumCases =
  7355. TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
  7356. assert(NumCases < UINT64_MAX / 100);
  7357. assert(Range >= NumCases);
  7358. return NumCases * 100 >= Range * Density;
  7359. }
  7360. static inline bool areJTsAllowed(const TargetLowering &TLI,
  7361. const SwitchInst *SI) {
  7362. const Function *Fn = SI->getParent()->getParent();
  7363. if (Fn->getFnAttribute("no-jump-tables").getValueAsString() == "true")
  7364. return false;
  7365. return TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
  7366. TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
  7367. }
  7368. bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters,
  7369. unsigned First, unsigned Last,
  7370. const SwitchInst *SI,
  7371. MachineBasicBlock *DefaultMBB,
  7372. CaseCluster &JTCluster) {
  7373. assert(First <= Last);
  7374. auto Prob = BranchProbability::getZero();
  7375. unsigned NumCmps = 0;
  7376. std::vector<MachineBasicBlock*> Table;
  7377. DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
  7378. // Initialize probabilities in JTProbs.
  7379. for (unsigned I = First; I <= Last; ++I)
  7380. JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
  7381. for (unsigned I = First; I <= Last; ++I) {
  7382. assert(Clusters[I].Kind == CC_Range);
  7383. Prob += Clusters[I].Prob;
  7384. const APInt &Low = Clusters[I].Low->getValue();
  7385. const APInt &High = Clusters[I].High->getValue();
  7386. NumCmps += (Low == High) ? 1 : 2;
  7387. if (I != First) {
  7388. // Fill the gap between this and the previous cluster.
  7389. const APInt &PreviousHigh = Clusters[I - 1].High->getValue();
  7390. assert(PreviousHigh.slt(Low));
  7391. uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
  7392. for (uint64_t J = 0; J < Gap; J++)
  7393. Table.push_back(DefaultMBB);
  7394. }
  7395. uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
  7396. for (uint64_t J = 0; J < ClusterSize; ++J)
  7397. Table.push_back(Clusters[I].MBB);
  7398. JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
  7399. }
  7400. unsigned NumDests = JTProbs.size();
  7401. if (isSuitableForBitTests(NumDests, NumCmps,
  7402. Clusters[First].Low->getValue(),
  7403. Clusters[Last].High->getValue())) {
  7404. // Clusters[First..Last] should be lowered as bit tests instead.
  7405. return false;
  7406. }
  7407. // Create the MBB that will load from and jump through the table.
  7408. // Note: We create it here, but it's not inserted into the function yet.
  7409. MachineFunction *CurMF = FuncInfo.MF;
  7410. MachineBasicBlock *JumpTableMBB =
  7411. CurMF->CreateMachineBasicBlock(SI->getParent());
  7412. // Add successors. Note: use table order for determinism.
  7413. SmallPtrSet<MachineBasicBlock *, 8> Done;
  7414. for (MachineBasicBlock *Succ : Table) {
  7415. if (Done.count(Succ))
  7416. continue;
  7417. addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
  7418. Done.insert(Succ);
  7419. }
  7420. JumpTableMBB->normalizeSuccProbs();
  7421. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7422. unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
  7423. ->createJumpTableIndex(Table);
  7424. // Set up the jump table info.
  7425. JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
  7426. JumpTableHeader JTH(Clusters[First].Low->getValue(),
  7427. Clusters[Last].High->getValue(), SI->getCondition(),
  7428. nullptr, false);
  7429. JTCases.emplace_back(std::move(JTH), std::move(JT));
  7430. JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
  7431. JTCases.size() - 1, Prob);
  7432. return true;
  7433. }
  7434. void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
  7435. const SwitchInst *SI,
  7436. MachineBasicBlock *DefaultMBB) {
  7437. #ifndef NDEBUG
  7438. // Clusters must be non-empty, sorted, and only contain Range clusters.
  7439. assert(!Clusters.empty());
  7440. for (CaseCluster &C : Clusters)
  7441. assert(C.Kind == CC_Range);
  7442. for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
  7443. assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
  7444. #endif
  7445. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7446. if (!areJTsAllowed(TLI, SI))
  7447. return;
  7448. const bool OptForSize = DefaultMBB->getParent()->getFunction()->optForSize();
  7449. const int64_t N = Clusters.size();
  7450. const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries();
  7451. const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2;
  7452. const unsigned MaxJumpTableSize =
  7453. OptForSize || TLI.getMaximumJumpTableSize() == 0
  7454. ? UINT_MAX : TLI.getMaximumJumpTableSize();
  7455. if (N < 2 || N < MinJumpTableEntries)
  7456. return;
  7457. // TotalCases[i]: Total nbr of cases in Clusters[0..i].
  7458. SmallVector<unsigned, 8> TotalCases(N);
  7459. for (unsigned i = 0; i < N; ++i) {
  7460. const APInt &Hi = Clusters[i].High->getValue();
  7461. const APInt &Lo = Clusters[i].Low->getValue();
  7462. TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
  7463. if (i != 0)
  7464. TotalCases[i] += TotalCases[i - 1];
  7465. }
  7466. const unsigned MinDensity =
  7467. OptForSize ? OptsizeJumpTableDensity : JumpTableDensity;
  7468. // Cheap case: the whole range may be suitable for jump table.
  7469. unsigned JumpTableSize = (Clusters[N - 1].High->getValue() -
  7470. Clusters[0].Low->getValue())
  7471. .getLimitedValue(UINT_MAX - 1) + 1;
  7472. if (JumpTableSize <= MaxJumpTableSize &&
  7473. isDense(Clusters, TotalCases, 0, N - 1, MinDensity)) {
  7474. CaseCluster JTCluster;
  7475. if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
  7476. Clusters[0] = JTCluster;
  7477. Clusters.resize(1);
  7478. return;
  7479. }
  7480. }
  7481. // The algorithm below is not suitable for -O0.
  7482. if (TM.getOptLevel() == CodeGenOpt::None)
  7483. return;
  7484. // Split Clusters into minimum number of dense partitions. The algorithm uses
  7485. // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
  7486. // for the Case Statement'" (1994), but builds the MinPartitions array in
  7487. // reverse order to make it easier to reconstruct the partitions in ascending
  7488. // order. In the choice between two optimal partitionings, it picks the one
  7489. // which yields more jump tables.
  7490. // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
  7491. SmallVector<unsigned, 8> MinPartitions(N);
  7492. // LastElement[i] is the last element of the partition starting at i.
  7493. SmallVector<unsigned, 8> LastElement(N);
  7494. // PartitionsScore[i] is used to break ties when choosing between two
  7495. // partitionings resulting in the same number of partitions.
  7496. SmallVector<unsigned, 8> PartitionsScore(N);
  7497. // For PartitionsScore, a small number of comparisons is considered as good as
  7498. // a jump table and a single comparison is considered better than a jump
  7499. // table.
  7500. enum PartitionScores : unsigned {
  7501. NoTable = 0,
  7502. Table = 1,
  7503. FewCases = 1,
  7504. SingleCase = 2
  7505. };
  7506. // Base case: There is only one way to partition Clusters[N-1].
  7507. MinPartitions[N - 1] = 1;
  7508. LastElement[N - 1] = N - 1;
  7509. PartitionsScore[N - 1] = PartitionScores::SingleCase;
  7510. // Note: loop indexes are signed to avoid underflow.
  7511. for (int64_t i = N - 2; i >= 0; i--) {
  7512. // Find optimal partitioning of Clusters[i..N-1].
  7513. // Baseline: Put Clusters[i] into a partition on its own.
  7514. MinPartitions[i] = MinPartitions[i + 1] + 1;
  7515. LastElement[i] = i;
  7516. PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase;
  7517. // Search for a solution that results in fewer partitions.
  7518. for (int64_t j = N - 1; j > i; j--) {
  7519. // Try building a partition from Clusters[i..j].
  7520. JumpTableSize = (Clusters[j].High->getValue() -
  7521. Clusters[i].Low->getValue())
  7522. .getLimitedValue(UINT_MAX - 1) + 1;
  7523. if (JumpTableSize <= MaxJumpTableSize &&
  7524. isDense(Clusters, TotalCases, i, j, MinDensity)) {
  7525. unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
  7526. unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1];
  7527. int64_t NumEntries = j - i + 1;
  7528. if (NumEntries == 1)
  7529. Score += PartitionScores::SingleCase;
  7530. else if (NumEntries <= SmallNumberOfEntries)
  7531. Score += PartitionScores::FewCases;
  7532. else if (NumEntries >= MinJumpTableEntries)
  7533. Score += PartitionScores::Table;
  7534. // If this leads to fewer partitions, or to the same number of
  7535. // partitions with better score, it is a better partitioning.
  7536. if (NumPartitions < MinPartitions[i] ||
  7537. (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) {
  7538. MinPartitions[i] = NumPartitions;
  7539. LastElement[i] = j;
  7540. PartitionsScore[i] = Score;
  7541. }
  7542. }
  7543. }
  7544. }
  7545. // Iterate over the partitions, replacing some with jump tables in-place.
  7546. unsigned DstIndex = 0;
  7547. for (unsigned First = 0, Last; First < N; First = Last + 1) {
  7548. Last = LastElement[First];
  7549. assert(Last >= First);
  7550. assert(DstIndex <= First);
  7551. unsigned NumClusters = Last - First + 1;
  7552. CaseCluster JTCluster;
  7553. if (NumClusters >= MinJumpTableEntries &&
  7554. buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
  7555. Clusters[DstIndex++] = JTCluster;
  7556. } else {
  7557. for (unsigned I = First; I <= Last; ++I)
  7558. std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
  7559. }
  7560. }
  7561. Clusters.resize(DstIndex);
  7562. }
  7563. bool SelectionDAGBuilder::rangeFitsInWord(const APInt &Low, const APInt &High) {
  7564. // FIXME: Using the pointer type doesn't seem ideal.
  7565. uint64_t BW = DAG.getDataLayout().getPointerSizeInBits();
  7566. uint64_t Range = (High - Low).getLimitedValue(UINT64_MAX - 1) + 1;
  7567. return Range <= BW;
  7568. }
  7569. bool SelectionDAGBuilder::isSuitableForBitTests(unsigned NumDests,
  7570. unsigned NumCmps,
  7571. const APInt &Low,
  7572. const APInt &High) {
  7573. // FIXME: I don't think NumCmps is the correct metric: a single case and a
  7574. // range of cases both require only one branch to lower. Just looking at the
  7575. // number of clusters and destinations should be enough to decide whether to
  7576. // build bit tests.
  7577. // To lower a range with bit tests, the range must fit the bitwidth of a
  7578. // machine word.
  7579. if (!rangeFitsInWord(Low, High))
  7580. return false;
  7581. // Decide whether it's profitable to lower this range with bit tests. Each
  7582. // destination requires a bit test and branch, and there is an overall range
  7583. // check branch. For a small number of clusters, separate comparisons might be
  7584. // cheaper, and for many destinations, splitting the range might be better.
  7585. return (NumDests == 1 && NumCmps >= 3) ||
  7586. (NumDests == 2 && NumCmps >= 5) ||
  7587. (NumDests == 3 && NumCmps >= 6);
  7588. }
  7589. bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
  7590. unsigned First, unsigned Last,
  7591. const SwitchInst *SI,
  7592. CaseCluster &BTCluster) {
  7593. assert(First <= Last);
  7594. if (First == Last)
  7595. return false;
  7596. BitVector Dests(FuncInfo.MF->getNumBlockIDs());
  7597. unsigned NumCmps = 0;
  7598. for (int64_t I = First; I <= Last; ++I) {
  7599. assert(Clusters[I].Kind == CC_Range);
  7600. Dests.set(Clusters[I].MBB->getNumber());
  7601. NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
  7602. }
  7603. unsigned NumDests = Dests.count();
  7604. APInt Low = Clusters[First].Low->getValue();
  7605. APInt High = Clusters[Last].High->getValue();
  7606. assert(Low.slt(High));
  7607. if (!isSuitableForBitTests(NumDests, NumCmps, Low, High))
  7608. return false;
  7609. APInt LowBound;
  7610. APInt CmpRange;
  7611. const int BitWidth = DAG.getTargetLoweringInfo()
  7612. .getPointerTy(DAG.getDataLayout())
  7613. .getSizeInBits();
  7614. assert(rangeFitsInWord(Low, High) && "Case range must fit in bit mask!");
  7615. // Check if the clusters cover a contiguous range such that no value in the
  7616. // range will jump to the default statement.
  7617. bool ContiguousRange = true;
  7618. for (int64_t I = First + 1; I <= Last; ++I) {
  7619. if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
  7620. ContiguousRange = false;
  7621. break;
  7622. }
  7623. }
  7624. if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
  7625. // Optimize the case where all the case values fit in a word without having
  7626. // to subtract minValue. In this case, we can optimize away the subtraction.
  7627. LowBound = APInt::getNullValue(Low.getBitWidth());
  7628. CmpRange = High;
  7629. ContiguousRange = false;
  7630. } else {
  7631. LowBound = Low;
  7632. CmpRange = High - Low;
  7633. }
  7634. CaseBitsVector CBV;
  7635. auto TotalProb = BranchProbability::getZero();
  7636. for (unsigned i = First; i <= Last; ++i) {
  7637. // Find the CaseBits for this destination.
  7638. unsigned j;
  7639. for (j = 0; j < CBV.size(); ++j)
  7640. if (CBV[j].BB == Clusters[i].MBB)
  7641. break;
  7642. if (j == CBV.size())
  7643. CBV.push_back(
  7644. CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
  7645. CaseBits *CB = &CBV[j];
  7646. // Update Mask, Bits and ExtraProb.
  7647. uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
  7648. uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
  7649. assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
  7650. CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
  7651. CB->Bits += Hi - Lo + 1;
  7652. CB->ExtraProb += Clusters[i].Prob;
  7653. TotalProb += Clusters[i].Prob;
  7654. }
  7655. BitTestInfo BTI;
  7656. std::sort(CBV.begin(), CBV.end(), [](const CaseBits &a, const CaseBits &b) {
  7657. // Sort by probability first, number of bits second.
  7658. if (a.ExtraProb != b.ExtraProb)
  7659. return a.ExtraProb > b.ExtraProb;
  7660. return a.Bits > b.Bits;
  7661. });
  7662. for (auto &CB : CBV) {
  7663. MachineBasicBlock *BitTestBB =
  7664. FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
  7665. BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
  7666. }
  7667. BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
  7668. SI->getCondition(), -1U, MVT::Other, false,
  7669. ContiguousRange, nullptr, nullptr, std::move(BTI),
  7670. TotalProb);
  7671. BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
  7672. BitTestCases.size() - 1, TotalProb);
  7673. return true;
  7674. }
  7675. void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
  7676. const SwitchInst *SI) {
  7677. // Partition Clusters into as few subsets as possible, where each subset has a
  7678. // range that fits in a machine word and has <= 3 unique destinations.
  7679. #ifndef NDEBUG
  7680. // Clusters must be sorted and contain Range or JumpTable clusters.
  7681. assert(!Clusters.empty());
  7682. assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
  7683. for (const CaseCluster &C : Clusters)
  7684. assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
  7685. for (unsigned i = 1; i < Clusters.size(); ++i)
  7686. assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
  7687. #endif
  7688. // The algorithm below is not suitable for -O0.
  7689. if (TM.getOptLevel() == CodeGenOpt::None)
  7690. return;
  7691. // If target does not have legal shift left, do not emit bit tests at all.
  7692. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7693. EVT PTy = TLI.getPointerTy(DAG.getDataLayout());
  7694. if (!TLI.isOperationLegal(ISD::SHL, PTy))
  7695. return;
  7696. int BitWidth = PTy.getSizeInBits();
  7697. const int64_t N = Clusters.size();
  7698. // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
  7699. SmallVector<unsigned, 8> MinPartitions(N);
  7700. // LastElement[i] is the last element of the partition starting at i.
  7701. SmallVector<unsigned, 8> LastElement(N);
  7702. // FIXME: This might not be the best algorithm for finding bit test clusters.
  7703. // Base case: There is only one way to partition Clusters[N-1].
  7704. MinPartitions[N - 1] = 1;
  7705. LastElement[N - 1] = N - 1;
  7706. // Note: loop indexes are signed to avoid underflow.
  7707. for (int64_t i = N - 2; i >= 0; --i) {
  7708. // Find optimal partitioning of Clusters[i..N-1].
  7709. // Baseline: Put Clusters[i] into a partition on its own.
  7710. MinPartitions[i] = MinPartitions[i + 1] + 1;
  7711. LastElement[i] = i;
  7712. // Search for a solution that results in fewer partitions.
  7713. // Note: the search is limited by BitWidth, reducing time complexity.
  7714. for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
  7715. // Try building a partition from Clusters[i..j].
  7716. // Check the range.
  7717. if (!rangeFitsInWord(Clusters[i].Low->getValue(),
  7718. Clusters[j].High->getValue()))
  7719. continue;
  7720. // Check nbr of destinations and cluster types.
  7721. // FIXME: This works, but doesn't seem very efficient.
  7722. bool RangesOnly = true;
  7723. BitVector Dests(FuncInfo.MF->getNumBlockIDs());
  7724. for (int64_t k = i; k <= j; k++) {
  7725. if (Clusters[k].Kind != CC_Range) {
  7726. RangesOnly = false;
  7727. break;
  7728. }
  7729. Dests.set(Clusters[k].MBB->getNumber());
  7730. }
  7731. if (!RangesOnly || Dests.count() > 3)
  7732. break;
  7733. // Check if it's a better partition.
  7734. unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
  7735. if (NumPartitions < MinPartitions[i]) {
  7736. // Found a better partition.
  7737. MinPartitions[i] = NumPartitions;
  7738. LastElement[i] = j;
  7739. }
  7740. }
  7741. }
  7742. // Iterate over the partitions, replacing with bit-test clusters in-place.
  7743. unsigned DstIndex = 0;
  7744. for (unsigned First = 0, Last; First < N; First = Last + 1) {
  7745. Last = LastElement[First];
  7746. assert(First <= Last);
  7747. assert(DstIndex <= First);
  7748. CaseCluster BitTestCluster;
  7749. if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
  7750. Clusters[DstIndex++] = BitTestCluster;
  7751. } else {
  7752. size_t NumClusters = Last - First + 1;
  7753. std::memmove(&Clusters[DstIndex], &Clusters[First],
  7754. sizeof(Clusters[0]) * NumClusters);
  7755. DstIndex += NumClusters;
  7756. }
  7757. }
  7758. Clusters.resize(DstIndex);
  7759. }
  7760. void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
  7761. MachineBasicBlock *SwitchMBB,
  7762. MachineBasicBlock *DefaultMBB) {
  7763. MachineFunction *CurMF = FuncInfo.MF;
  7764. MachineBasicBlock *NextMBB = nullptr;
  7765. MachineFunction::iterator BBI(W.MBB);
  7766. if (++BBI != FuncInfo.MF->end())
  7767. NextMBB = &*BBI;
  7768. unsigned Size = W.LastCluster - W.FirstCluster + 1;
  7769. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  7770. if (Size == 2 && W.MBB == SwitchMBB) {
  7771. // If any two of the cases has the same destination, and if one value
  7772. // is the same as the other, but has one bit unset that the other has set,
  7773. // use bit manipulation to do two compares at once. For example:
  7774. // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
  7775. // TODO: This could be extended to merge any 2 cases in switches with 3
  7776. // cases.
  7777. // TODO: Handle cases where W.CaseBB != SwitchBB.
  7778. CaseCluster &Small = *W.FirstCluster;
  7779. CaseCluster &Big = *W.LastCluster;
  7780. if (Small.Low == Small.High && Big.Low == Big.High &&
  7781. Small.MBB == Big.MBB) {
  7782. const APInt &SmallValue = Small.Low->getValue();
  7783. const APInt &BigValue = Big.Low->getValue();
  7784. // Check that there is only one bit different.
  7785. APInt CommonBit = BigValue ^ SmallValue;
  7786. if (CommonBit.isPowerOf2()) {
  7787. SDValue CondLHS = getValue(Cond);
  7788. EVT VT = CondLHS.getValueType();
  7789. SDLoc DL = getCurSDLoc();
  7790. SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
  7791. DAG.getConstant(CommonBit, DL, VT));
  7792. SDValue Cond = DAG.getSetCC(
  7793. DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
  7794. ISD::SETEQ);
  7795. // Update successor info.
  7796. // Both Small and Big will jump to Small.BB, so we sum up the
  7797. // probabilities.
  7798. addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
  7799. if (BPI)
  7800. addSuccessorWithProb(
  7801. SwitchMBB, DefaultMBB,
  7802. // The default destination is the first successor in IR.
  7803. BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
  7804. else
  7805. addSuccessorWithProb(SwitchMBB, DefaultMBB);
  7806. // Insert the true branch.
  7807. SDValue BrCond =
  7808. DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
  7809. DAG.getBasicBlock(Small.MBB));
  7810. // Insert the false branch.
  7811. BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
  7812. DAG.getBasicBlock(DefaultMBB));
  7813. DAG.setRoot(BrCond);
  7814. return;
  7815. }
  7816. }
  7817. }
  7818. if (TM.getOptLevel() != CodeGenOpt::None) {
  7819. // Order cases by probability so the most likely case will be checked first.
  7820. std::sort(W.FirstCluster, W.LastCluster + 1,
  7821. [](const CaseCluster &a, const CaseCluster &b) {
  7822. return a.Prob > b.Prob;
  7823. });
  7824. // Rearrange the case blocks so that the last one falls through if possible
  7825. // without without changing the order of probabilities.
  7826. for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
  7827. --I;
  7828. if (I->Prob > W.LastCluster->Prob)
  7829. break;
  7830. if (I->Kind == CC_Range && I->MBB == NextMBB) {
  7831. std::swap(*I, *W.LastCluster);
  7832. break;
  7833. }
  7834. }
  7835. }
  7836. // Compute total probability.
  7837. BranchProbability DefaultProb = W.DefaultProb;
  7838. BranchProbability UnhandledProbs = DefaultProb;
  7839. for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
  7840. UnhandledProbs += I->Prob;
  7841. MachineBasicBlock *CurMBB = W.MBB;
  7842. for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
  7843. MachineBasicBlock *Fallthrough;
  7844. if (I == W.LastCluster) {
  7845. // For the last cluster, fall through to the default destination.
  7846. Fallthrough = DefaultMBB;
  7847. } else {
  7848. Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
  7849. CurMF->insert(BBI, Fallthrough);
  7850. // Put Cond in a virtual register to make it available from the new blocks.
  7851. ExportFromCurrentBlock(Cond);
  7852. }
  7853. UnhandledProbs -= I->Prob;
  7854. switch (I->Kind) {
  7855. case CC_JumpTable: {
  7856. // FIXME: Optimize away range check based on pivot comparisons.
  7857. JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
  7858. JumpTable *JT = &JTCases[I->JTCasesIndex].second;
  7859. // The jump block hasn't been inserted yet; insert it here.
  7860. MachineBasicBlock *JumpMBB = JT->MBB;
  7861. CurMF->insert(BBI, JumpMBB);
  7862. auto JumpProb = I->Prob;
  7863. auto FallthroughProb = UnhandledProbs;
  7864. // If the default statement is a target of the jump table, we evenly
  7865. // distribute the default probability to successors of CurMBB. Also
  7866. // update the probability on the edge from JumpMBB to Fallthrough.
  7867. for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
  7868. SE = JumpMBB->succ_end();
  7869. SI != SE; ++SI) {
  7870. if (*SI == DefaultMBB) {
  7871. JumpProb += DefaultProb / 2;
  7872. FallthroughProb -= DefaultProb / 2;
  7873. JumpMBB->setSuccProbability(SI, DefaultProb / 2);
  7874. JumpMBB->normalizeSuccProbs();
  7875. break;
  7876. }
  7877. }
  7878. addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
  7879. addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
  7880. CurMBB->normalizeSuccProbs();
  7881. // The jump table header will be inserted in our current block, do the
  7882. // range check, and fall through to our fallthrough block.
  7883. JTH->HeaderBB = CurMBB;
  7884. JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
  7885. // If we're in the right place, emit the jump table header right now.
  7886. if (CurMBB == SwitchMBB) {
  7887. visitJumpTableHeader(*JT, *JTH, SwitchMBB);
  7888. JTH->Emitted = true;
  7889. }
  7890. break;
  7891. }
  7892. case CC_BitTests: {
  7893. // FIXME: Optimize away range check based on pivot comparisons.
  7894. BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
  7895. // The bit test blocks haven't been inserted yet; insert them here.
  7896. for (BitTestCase &BTC : BTB->Cases)
  7897. CurMF->insert(BBI, BTC.ThisBB);
  7898. // Fill in fields of the BitTestBlock.
  7899. BTB->Parent = CurMBB;
  7900. BTB->Default = Fallthrough;
  7901. BTB->DefaultProb = UnhandledProbs;
  7902. // If the cases in bit test don't form a contiguous range, we evenly
  7903. // distribute the probability on the edge to Fallthrough to two
  7904. // successors of CurMBB.
  7905. if (!BTB->ContiguousRange) {
  7906. BTB->Prob += DefaultProb / 2;
  7907. BTB->DefaultProb -= DefaultProb / 2;
  7908. }
  7909. // If we're in the right place, emit the bit test header right now.
  7910. if (CurMBB == SwitchMBB) {
  7911. visitBitTestHeader(*BTB, SwitchMBB);
  7912. BTB->Emitted = true;
  7913. }
  7914. break;
  7915. }
  7916. case CC_Range: {
  7917. const Value *RHS, *LHS, *MHS;
  7918. ISD::CondCode CC;
  7919. if (I->Low == I->High) {
  7920. // Check Cond == I->Low.
  7921. CC = ISD::SETEQ;
  7922. LHS = Cond;
  7923. RHS=I->Low;
  7924. MHS = nullptr;
  7925. } else {
  7926. // Check I->Low <= Cond <= I->High.
  7927. CC = ISD::SETLE;
  7928. LHS = I->Low;
  7929. MHS = Cond;
  7930. RHS = I->High;
  7931. }
  7932. // The false probability is the sum of all unhandled cases.
  7933. CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, I->Prob,
  7934. UnhandledProbs);
  7935. if (CurMBB == SwitchMBB)
  7936. visitSwitchCase(CB, SwitchMBB);
  7937. else
  7938. SwitchCases.push_back(CB);
  7939. break;
  7940. }
  7941. }
  7942. CurMBB = Fallthrough;
  7943. }
  7944. }
  7945. unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
  7946. CaseClusterIt First,
  7947. CaseClusterIt Last) {
  7948. return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
  7949. if (X.Prob != CC.Prob)
  7950. return X.Prob > CC.Prob;
  7951. // Ties are broken by comparing the case value.
  7952. return X.Low->getValue().slt(CC.Low->getValue());
  7953. });
  7954. }
  7955. void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
  7956. const SwitchWorkListItem &W,
  7957. Value *Cond,
  7958. MachineBasicBlock *SwitchMBB) {
  7959. assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
  7960. "Clusters not sorted?");
  7961. assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
  7962. // Balance the tree based on branch probabilities to create a near-optimal (in
  7963. // terms of search time given key frequency) binary search tree. See e.g. Kurt
  7964. // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
  7965. CaseClusterIt LastLeft = W.FirstCluster;
  7966. CaseClusterIt FirstRight = W.LastCluster;
  7967. auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
  7968. auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
  7969. // Move LastLeft and FirstRight towards each other from opposite directions to
  7970. // find a partitioning of the clusters which balances the probability on both
  7971. // sides. If LeftProb and RightProb are equal, alternate which side is
  7972. // taken to ensure 0-probability nodes are distributed evenly.
  7973. unsigned I = 0;
  7974. while (LastLeft + 1 < FirstRight) {
  7975. if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
  7976. LeftProb += (++LastLeft)->Prob;
  7977. else
  7978. RightProb += (--FirstRight)->Prob;
  7979. I++;
  7980. }
  7981. for (;;) {
  7982. // Our binary search tree differs from a typical BST in that ours can have up
  7983. // to three values in each leaf. The pivot selection above doesn't take that
  7984. // into account, which means the tree might require more nodes and be less
  7985. // efficient. We compensate for this here.
  7986. unsigned NumLeft = LastLeft - W.FirstCluster + 1;
  7987. unsigned NumRight = W.LastCluster - FirstRight + 1;
  7988. if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
  7989. // If one side has less than 3 clusters, and the other has more than 3,
  7990. // consider taking a cluster from the other side.
  7991. if (NumLeft < NumRight) {
  7992. // Consider moving the first cluster on the right to the left side.
  7993. CaseCluster &CC = *FirstRight;
  7994. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  7995. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  7996. if (LeftSideRank <= RightSideRank) {
  7997. // Moving the cluster to the left does not demote it.
  7998. ++LastLeft;
  7999. ++FirstRight;
  8000. continue;
  8001. }
  8002. } else {
  8003. assert(NumRight < NumLeft);
  8004. // Consider moving the last element on the left to the right side.
  8005. CaseCluster &CC = *LastLeft;
  8006. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  8007. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  8008. if (RightSideRank <= LeftSideRank) {
  8009. // Moving the cluster to the right does not demot it.
  8010. --LastLeft;
  8011. --FirstRight;
  8012. continue;
  8013. }
  8014. }
  8015. }
  8016. break;
  8017. }
  8018. assert(LastLeft + 1 == FirstRight);
  8019. assert(LastLeft >= W.FirstCluster);
  8020. assert(FirstRight <= W.LastCluster);
  8021. // Use the first element on the right as pivot since we will make less-than
  8022. // comparisons against it.
  8023. CaseClusterIt PivotCluster = FirstRight;
  8024. assert(PivotCluster > W.FirstCluster);
  8025. assert(PivotCluster <= W.LastCluster);
  8026. CaseClusterIt FirstLeft = W.FirstCluster;
  8027. CaseClusterIt LastRight = W.LastCluster;
  8028. const ConstantInt *Pivot = PivotCluster->Low;
  8029. // New blocks will be inserted immediately after the current one.
  8030. MachineFunction::iterator BBI(W.MBB);
  8031. ++BBI;
  8032. // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
  8033. // we can branch to its destination directly if it's squeezed exactly in
  8034. // between the known lower bound and Pivot - 1.
  8035. MachineBasicBlock *LeftMBB;
  8036. if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
  8037. FirstLeft->Low == W.GE &&
  8038. (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
  8039. LeftMBB = FirstLeft->MBB;
  8040. } else {
  8041. LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  8042. FuncInfo.MF->insert(BBI, LeftMBB);
  8043. WorkList.push_back(
  8044. {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
  8045. // Put Cond in a virtual register to make it available from the new blocks.
  8046. ExportFromCurrentBlock(Cond);
  8047. }
  8048. // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
  8049. // single cluster, RHS.Low == Pivot, and we can branch to its destination
  8050. // directly if RHS.High equals the current upper bound.
  8051. MachineBasicBlock *RightMBB;
  8052. if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
  8053. W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
  8054. RightMBB = FirstRight->MBB;
  8055. } else {
  8056. RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  8057. FuncInfo.MF->insert(BBI, RightMBB);
  8058. WorkList.push_back(
  8059. {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
  8060. // Put Cond in a virtual register to make it available from the new blocks.
  8061. ExportFromCurrentBlock(Cond);
  8062. }
  8063. // Create the CaseBlock record that will be used to lower the branch.
  8064. CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
  8065. LeftProb, RightProb);
  8066. if (W.MBB == SwitchMBB)
  8067. visitSwitchCase(CB, SwitchMBB);
  8068. else
  8069. SwitchCases.push_back(CB);
  8070. }
  8071. void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
  8072. // Extract cases from the switch.
  8073. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  8074. CaseClusterVector Clusters;
  8075. Clusters.reserve(SI.getNumCases());
  8076. for (auto I : SI.cases()) {
  8077. MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
  8078. const ConstantInt *CaseVal = I.getCaseValue();
  8079. BranchProbability Prob =
  8080. BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
  8081. : BranchProbability(1, SI.getNumCases() + 1);
  8082. Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
  8083. }
  8084. MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
  8085. // Cluster adjacent cases with the same destination. We do this at all
  8086. // optimization levels because it's cheap to do and will make codegen faster
  8087. // if there are many clusters.
  8088. sortAndRangeify(Clusters);
  8089. if (TM.getOptLevel() != CodeGenOpt::None) {
  8090. // Replace an unreachable default with the most popular destination.
  8091. // FIXME: Exploit unreachable default more aggressively.
  8092. bool UnreachableDefault =
  8093. isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg());
  8094. if (UnreachableDefault && !Clusters.empty()) {
  8095. DenseMap<const BasicBlock *, unsigned> Popularity;
  8096. unsigned MaxPop = 0;
  8097. const BasicBlock *MaxBB = nullptr;
  8098. for (auto I : SI.cases()) {
  8099. const BasicBlock *BB = I.getCaseSuccessor();
  8100. if (++Popularity[BB] > MaxPop) {
  8101. MaxPop = Popularity[BB];
  8102. MaxBB = BB;
  8103. }
  8104. }
  8105. // Set new default.
  8106. assert(MaxPop > 0 && MaxBB);
  8107. DefaultMBB = FuncInfo.MBBMap[MaxBB];
  8108. // Remove cases that were pointing to the destination that is now the
  8109. // default.
  8110. CaseClusterVector New;
  8111. New.reserve(Clusters.size());
  8112. for (CaseCluster &CC : Clusters) {
  8113. if (CC.MBB != DefaultMBB)
  8114. New.push_back(CC);
  8115. }
  8116. Clusters = std::move(New);
  8117. }
  8118. }
  8119. // If there is only the default destination, jump there directly.
  8120. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  8121. if (Clusters.empty()) {
  8122. SwitchMBB->addSuccessor(DefaultMBB);
  8123. if (DefaultMBB != NextBlock(SwitchMBB)) {
  8124. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  8125. getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
  8126. }
  8127. return;
  8128. }
  8129. findJumpTables(Clusters, &SI, DefaultMBB);
  8130. findBitTestClusters(Clusters, &SI);
  8131. DEBUG({
  8132. dbgs() << "Case clusters: ";
  8133. for (const CaseCluster &C : Clusters) {
  8134. if (C.Kind == CC_JumpTable) dbgs() << "JT:";
  8135. if (C.Kind == CC_BitTests) dbgs() << "BT:";
  8136. C.Low->getValue().print(dbgs(), true);
  8137. if (C.Low != C.High) {
  8138. dbgs() << '-';
  8139. C.High->getValue().print(dbgs(), true);
  8140. }
  8141. dbgs() << ' ';
  8142. }
  8143. dbgs() << '\n';
  8144. });
  8145. assert(!Clusters.empty());
  8146. SwitchWorkList WorkList;
  8147. CaseClusterIt First = Clusters.begin();
  8148. CaseClusterIt Last = Clusters.end() - 1;
  8149. auto DefaultProb = getEdgeProbability(SwitchMBB, DefaultMBB);
  8150. WorkList.push_back({SwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
  8151. while (!WorkList.empty()) {
  8152. SwitchWorkListItem W = WorkList.back();
  8153. WorkList.pop_back();
  8154. unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
  8155. if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
  8156. !DefaultMBB->getParent()->getFunction()->optForMinSize()) {
  8157. // For optimized builds, lower large range as a balanced binary tree.
  8158. splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
  8159. continue;
  8160. }
  8161. lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
  8162. }
  8163. }