SelectionDAGBuilder.cpp 440 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250
  1. //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This implements routines for translating from LLVM IR into SelectionDAG IR.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "SelectionDAGBuilder.h"
  13. #include "SDNodeDbgValue.h"
  14. #include "llvm/ADT/APFloat.h"
  15. #include "llvm/ADT/APInt.h"
  16. #include "llvm/ADT/BitVector.h"
  17. #include "llvm/ADT/None.h"
  18. #include "llvm/ADT/Optional.h"
  19. #include "llvm/ADT/STLExtras.h"
  20. #include "llvm/ADT/SmallPtrSet.h"
  21. #include "llvm/ADT/SmallSet.h"
  22. #include "llvm/ADT/StringRef.h"
  23. #include "llvm/ADT/Triple.h"
  24. #include "llvm/ADT/Twine.h"
  25. #include "llvm/Analysis/AliasAnalysis.h"
  26. #include "llvm/Analysis/BlockFrequencyInfo.h"
  27. #include "llvm/Analysis/BranchProbabilityInfo.h"
  28. #include "llvm/Analysis/ConstantFolding.h"
  29. #include "llvm/Analysis/EHPersonalities.h"
  30. #include "llvm/Analysis/Loads.h"
  31. #include "llvm/Analysis/MemoryLocation.h"
  32. #include "llvm/Analysis/ProfileSummaryInfo.h"
  33. #include "llvm/Analysis/TargetLibraryInfo.h"
  34. #include "llvm/Analysis/ValueTracking.h"
  35. #include "llvm/Analysis/VectorUtils.h"
  36. #include "llvm/CodeGen/Analysis.h"
  37. #include "llvm/CodeGen/FunctionLoweringInfo.h"
  38. #include "llvm/CodeGen/GCMetadata.h"
  39. #include "llvm/CodeGen/MachineBasicBlock.h"
  40. #include "llvm/CodeGen/MachineFrameInfo.h"
  41. #include "llvm/CodeGen/MachineFunction.h"
  42. #include "llvm/CodeGen/MachineInstr.h"
  43. #include "llvm/CodeGen/MachineInstrBuilder.h"
  44. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  45. #include "llvm/CodeGen/MachineMemOperand.h"
  46. #include "llvm/CodeGen/MachineModuleInfo.h"
  47. #include "llvm/CodeGen/MachineOperand.h"
  48. #include "llvm/CodeGen/MachineRegisterInfo.h"
  49. #include "llvm/CodeGen/RuntimeLibcalls.h"
  50. #include "llvm/CodeGen/SelectionDAG.h"
  51. #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
  52. #include "llvm/CodeGen/StackMaps.h"
  53. #include "llvm/CodeGen/SwiftErrorValueTracking.h"
  54. #include "llvm/CodeGen/TargetFrameLowering.h"
  55. #include "llvm/CodeGen/TargetInstrInfo.h"
  56. #include "llvm/CodeGen/TargetOpcodes.h"
  57. #include "llvm/CodeGen/TargetRegisterInfo.h"
  58. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  59. #include "llvm/CodeGen/WinEHFuncInfo.h"
  60. #include "llvm/IR/Argument.h"
  61. #include "llvm/IR/Attributes.h"
  62. #include "llvm/IR/BasicBlock.h"
  63. #include "llvm/IR/CFG.h"
  64. #include "llvm/IR/CallingConv.h"
  65. #include "llvm/IR/Constant.h"
  66. #include "llvm/IR/ConstantRange.h"
  67. #include "llvm/IR/Constants.h"
  68. #include "llvm/IR/DataLayout.h"
  69. #include "llvm/IR/DebugInfoMetadata.h"
  70. #include "llvm/IR/DerivedTypes.h"
  71. #include "llvm/IR/DiagnosticInfo.h"
  72. #include "llvm/IR/Function.h"
  73. #include "llvm/IR/GetElementPtrTypeIterator.h"
  74. #include "llvm/IR/InlineAsm.h"
  75. #include "llvm/IR/InstrTypes.h"
  76. #include "llvm/IR/Instructions.h"
  77. #include "llvm/IR/IntrinsicInst.h"
  78. #include "llvm/IR/Intrinsics.h"
  79. #include "llvm/IR/IntrinsicsAArch64.h"
  80. #include "llvm/IR/IntrinsicsWebAssembly.h"
  81. #include "llvm/IR/LLVMContext.h"
  82. #include "llvm/IR/Metadata.h"
  83. #include "llvm/IR/Module.h"
  84. #include "llvm/IR/Operator.h"
  85. #include "llvm/IR/PatternMatch.h"
  86. #include "llvm/IR/Statepoint.h"
  87. #include "llvm/IR/Type.h"
  88. #include "llvm/IR/User.h"
  89. #include "llvm/IR/Value.h"
  90. #include "llvm/MC/MCContext.h"
  91. #include "llvm/MC/MCSymbol.h"
  92. #include "llvm/Support/AtomicOrdering.h"
  93. #include "llvm/Support/Casting.h"
  94. #include "llvm/Support/CommandLine.h"
  95. #include "llvm/Support/Compiler.h"
  96. #include "llvm/Support/Debug.h"
  97. #include "llvm/Support/MathExtras.h"
  98. #include "llvm/Support/raw_ostream.h"
  99. #include "llvm/Target/TargetIntrinsicInfo.h"
  100. #include "llvm/Target/TargetMachine.h"
  101. #include "llvm/Target/TargetOptions.h"
  102. #include "llvm/Transforms/Utils/Local.h"
  103. #include <cstddef>
  104. #include <cstring>
  105. #include <iterator>
  106. #include <limits>
  107. #include <numeric>
  108. #include <tuple>
  109. using namespace llvm;
  110. using namespace PatternMatch;
  111. using namespace SwitchCG;
  112. #define DEBUG_TYPE "isel"
  113. /// LimitFloatPrecision - Generate low-precision inline sequences for
  114. /// some float libcalls (6, 8 or 12 bits).
  115. static unsigned LimitFloatPrecision;
  116. static cl::opt<bool>
  117. InsertAssertAlign("insert-assert-align", cl::init(true),
  118. cl::desc("Insert the experimental `assertalign` node."),
  119. cl::ReallyHidden);
  120. static cl::opt<unsigned, true>
  121. LimitFPPrecision("limit-float-precision",
  122. cl::desc("Generate low-precision inline sequences "
  123. "for some float libcalls"),
  124. cl::location(LimitFloatPrecision), cl::Hidden,
  125. cl::init(0));
  126. static cl::opt<unsigned> SwitchPeelThreshold(
  127. "switch-peel-threshold", cl::Hidden, cl::init(66),
  128. cl::desc("Set the case probability threshold for peeling the case from a "
  129. "switch statement. A value greater than 100 will void this "
  130. "optimization"));
  131. // Limit the width of DAG chains. This is important in general to prevent
  132. // DAG-based analysis from blowing up. For example, alias analysis and
  133. // load clustering may not complete in reasonable time. It is difficult to
  134. // recognize and avoid this situation within each individual analysis, and
  135. // future analyses are likely to have the same behavior. Limiting DAG width is
  136. // the safe approach and will be especially important with global DAGs.
  137. //
  138. // MaxParallelChains default is arbitrarily high to avoid affecting
  139. // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
  140. // sequence over this should have been converted to llvm.memcpy by the
  141. // frontend. It is easy to induce this behavior with .ll code such as:
  142. // %buffer = alloca [4096 x i8]
  143. // %data = load [4096 x i8]* %argPtr
  144. // store [4096 x i8] %data, [4096 x i8]* %buffer
  145. static const unsigned MaxParallelChains = 64;
  146. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  147. const SDValue *Parts, unsigned NumParts,
  148. MVT PartVT, EVT ValueVT, const Value *V,
  149. Optional<CallingConv::ID> CC);
  150. /// getCopyFromParts - Create a value that contains the specified legal parts
  151. /// combined into the value they represent. If the parts combine to a type
  152. /// larger than ValueVT then AssertOp can be used to specify whether the extra
  153. /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
  154. /// (ISD::AssertSext).
  155. static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
  156. const SDValue *Parts, unsigned NumParts,
  157. MVT PartVT, EVT ValueVT, const Value *V,
  158. Optional<CallingConv::ID> CC = None,
  159. Optional<ISD::NodeType> AssertOp = None) {
  160. // Let the target assemble the parts if it wants to
  161. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  162. if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
  163. PartVT, ValueVT, CC))
  164. return Val;
  165. if (ValueVT.isVector())
  166. return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
  167. CC);
  168. assert(NumParts > 0 && "No parts to assemble!");
  169. SDValue Val = Parts[0];
  170. if (NumParts > 1) {
  171. // Assemble the value from multiple parts.
  172. if (ValueVT.isInteger()) {
  173. unsigned PartBits = PartVT.getSizeInBits();
  174. unsigned ValueBits = ValueVT.getSizeInBits();
  175. // Assemble the power of 2 part.
  176. unsigned RoundParts =
  177. (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
  178. unsigned RoundBits = PartBits * RoundParts;
  179. EVT RoundVT = RoundBits == ValueBits ?
  180. ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
  181. SDValue Lo, Hi;
  182. EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
  183. if (RoundParts > 2) {
  184. Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
  185. PartVT, HalfVT, V);
  186. Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
  187. RoundParts / 2, PartVT, HalfVT, V);
  188. } else {
  189. Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
  190. Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
  191. }
  192. if (DAG.getDataLayout().isBigEndian())
  193. std::swap(Lo, Hi);
  194. Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
  195. if (RoundParts < NumParts) {
  196. // Assemble the trailing non-power-of-2 part.
  197. unsigned OddParts = NumParts - RoundParts;
  198. EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
  199. Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
  200. OddVT, V, CC);
  201. // Combine the round and odd parts.
  202. Lo = Val;
  203. if (DAG.getDataLayout().isBigEndian())
  204. std::swap(Lo, Hi);
  205. EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  206. Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
  207. Hi =
  208. DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
  209. DAG.getConstant(Lo.getValueSizeInBits(), DL,
  210. TLI.getPointerTy(DAG.getDataLayout())));
  211. Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
  212. Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
  213. }
  214. } else if (PartVT.isFloatingPoint()) {
  215. // FP split into multiple FP parts (for ppcf128)
  216. assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
  217. "Unexpected split");
  218. SDValue Lo, Hi;
  219. Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
  220. Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
  221. if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
  222. std::swap(Lo, Hi);
  223. Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
  224. } else {
  225. // FP split into integer parts (soft fp)
  226. assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
  227. !PartVT.isVector() && "Unexpected split");
  228. EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  229. Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
  230. }
  231. }
  232. // There is now one part, held in Val. Correct it to match ValueVT.
  233. // PartEVT is the type of the register class that holds the value.
  234. // ValueVT is the type of the inline asm operation.
  235. EVT PartEVT = Val.getValueType();
  236. if (PartEVT == ValueVT)
  237. return Val;
  238. if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
  239. ValueVT.bitsLT(PartEVT)) {
  240. // For an FP value in an integer part, we need to truncate to the right
  241. // width first.
  242. PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  243. Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
  244. }
  245. // Handle types that have the same size.
  246. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
  247. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  248. // Handle types with different sizes.
  249. if (PartEVT.isInteger() && ValueVT.isInteger()) {
  250. if (ValueVT.bitsLT(PartEVT)) {
  251. // For a truncate, see if we have any information to
  252. // indicate whether the truncated bits will always be
  253. // zero or sign-extension.
  254. if (AssertOp.hasValue())
  255. Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
  256. DAG.getValueType(ValueVT));
  257. return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  258. }
  259. return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
  260. }
  261. if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  262. // FP_ROUND's are always exact here.
  263. if (ValueVT.bitsLT(Val.getValueType()))
  264. return DAG.getNode(
  265. ISD::FP_ROUND, DL, ValueVT, Val,
  266. DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
  267. return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
  268. }
  269. // Handle MMX to a narrower integer type by bitcasting MMX to integer and
  270. // then truncating.
  271. if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
  272. ValueVT.bitsLT(PartEVT)) {
  273. Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
  274. return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  275. }
  276. report_fatal_error("Unknown mismatch in getCopyFromParts!");
  277. }
  278. static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
  279. const Twine &ErrMsg) {
  280. const Instruction *I = dyn_cast_or_null<Instruction>(V);
  281. if (!V)
  282. return Ctx.emitError(ErrMsg);
  283. const char *AsmError = ", possible invalid constraint for vector type";
  284. if (const CallInst *CI = dyn_cast<CallInst>(I))
  285. if (CI->isInlineAsm())
  286. return Ctx.emitError(I, ErrMsg + AsmError);
  287. return Ctx.emitError(I, ErrMsg);
  288. }
  289. /// getCopyFromPartsVector - Create a value that contains the specified legal
  290. /// parts combined into the value they represent. If the parts combine to a
  291. /// type larger than ValueVT then AssertOp can be used to specify whether the
  292. /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
  293. /// ValueVT (ISD::AssertSext).
  294. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  295. const SDValue *Parts, unsigned NumParts,
  296. MVT PartVT, EVT ValueVT, const Value *V,
  297. Optional<CallingConv::ID> CallConv) {
  298. assert(ValueVT.isVector() && "Not a vector value");
  299. assert(NumParts > 0 && "No parts to assemble!");
  300. const bool IsABIRegCopy = CallConv.hasValue();
  301. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  302. SDValue Val = Parts[0];
  303. // Handle a multi-element vector.
  304. if (NumParts > 1) {
  305. EVT IntermediateVT;
  306. MVT RegisterVT;
  307. unsigned NumIntermediates;
  308. unsigned NumRegs;
  309. if (IsABIRegCopy) {
  310. NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
  311. *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
  312. NumIntermediates, RegisterVT);
  313. } else {
  314. NumRegs =
  315. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  316. NumIntermediates, RegisterVT);
  317. }
  318. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  319. NumParts = NumRegs; // Silence a compiler warning.
  320. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  321. assert(RegisterVT.getSizeInBits() ==
  322. Parts[0].getSimpleValueType().getSizeInBits() &&
  323. "Part type sizes don't match!");
  324. // Assemble the parts into intermediate operands.
  325. SmallVector<SDValue, 8> Ops(NumIntermediates);
  326. if (NumIntermediates == NumParts) {
  327. // If the register was not expanded, truncate or copy the value,
  328. // as appropriate.
  329. for (unsigned i = 0; i != NumParts; ++i)
  330. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
  331. PartVT, IntermediateVT, V, CallConv);
  332. } else if (NumParts > 0) {
  333. // If the intermediate type was expanded, build the intermediate
  334. // operands from the parts.
  335. assert(NumParts % NumIntermediates == 0 &&
  336. "Must expand into a divisible number of parts!");
  337. unsigned Factor = NumParts / NumIntermediates;
  338. for (unsigned i = 0; i != NumIntermediates; ++i)
  339. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
  340. PartVT, IntermediateVT, V, CallConv);
  341. }
  342. // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
  343. // intermediate operands.
  344. EVT BuiltVectorTy =
  345. IntermediateVT.isVector()
  346. ? EVT::getVectorVT(
  347. *DAG.getContext(), IntermediateVT.getScalarType(),
  348. IntermediateVT.getVectorElementCount() * NumParts)
  349. : EVT::getVectorVT(*DAG.getContext(),
  350. IntermediateVT.getScalarType(),
  351. NumIntermediates);
  352. Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
  353. : ISD::BUILD_VECTOR,
  354. DL, BuiltVectorTy, Ops);
  355. }
  356. // There is now one part, held in Val. Correct it to match ValueVT.
  357. EVT PartEVT = Val.getValueType();
  358. if (PartEVT == ValueVT)
  359. return Val;
  360. if (PartEVT.isVector()) {
  361. // Vector/Vector bitcast.
  362. if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
  363. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  364. // If the element type of the source/dest vectors are the same, but the
  365. // parts vector has more elements than the value vector, then we have a
  366. // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
  367. // elements we want.
  368. if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
  369. assert((PartEVT.getVectorElementCount().getKnownMinValue() >
  370. ValueVT.getVectorElementCount().getKnownMinValue()) &&
  371. (PartEVT.getVectorElementCount().isScalable() ==
  372. ValueVT.getVectorElementCount().isScalable()) &&
  373. "Cannot narrow, it would be a lossy transformation");
  374. PartEVT =
  375. EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(),
  376. ValueVT.getVectorElementCount());
  377. Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
  378. DAG.getVectorIdxConstant(0, DL));
  379. if (PartEVT == ValueVT)
  380. return Val;
  381. }
  382. // Promoted vector extract
  383. return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
  384. }
  385. // Trivial bitcast if the types are the same size and the destination
  386. // vector type is legal.
  387. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
  388. TLI.isTypeLegal(ValueVT))
  389. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  390. if (ValueVT.getVectorNumElements() != 1) {
  391. // Certain ABIs require that vectors are passed as integers. For vectors
  392. // are the same size, this is an obvious bitcast.
  393. if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
  394. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  395. } else if (ValueVT.bitsLT(PartEVT)) {
  396. const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
  397. EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
  398. // Drop the extra bits.
  399. Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
  400. return DAG.getBitcast(ValueVT, Val);
  401. }
  402. diagnosePossiblyInvalidConstraint(
  403. *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
  404. return DAG.getUNDEF(ValueVT);
  405. }
  406. // Handle cases such as i8 -> <1 x i1>
  407. EVT ValueSVT = ValueVT.getVectorElementType();
  408. if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
  409. if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits())
  410. Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
  411. else
  412. Val = ValueVT.isFloatingPoint()
  413. ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
  414. : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
  415. }
  416. return DAG.getBuildVector(ValueVT, DL, Val);
  417. }
  418. static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
  419. SDValue Val, SDValue *Parts, unsigned NumParts,
  420. MVT PartVT, const Value *V,
  421. Optional<CallingConv::ID> CallConv);
  422. /// getCopyToParts - Create a series of nodes that contain the specified value
  423. /// split into legal parts. If the parts contain more bits than Val, then, for
  424. /// integers, ExtendKind can be used to specify how to generate the extra bits.
  425. static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
  426. SDValue *Parts, unsigned NumParts, MVT PartVT,
  427. const Value *V,
  428. Optional<CallingConv::ID> CallConv = None,
  429. ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
  430. // Let the target split the parts if it wants to
  431. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  432. if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
  433. CallConv))
  434. return;
  435. EVT ValueVT = Val.getValueType();
  436. // Handle the vector case separately.
  437. if (ValueVT.isVector())
  438. return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
  439. CallConv);
  440. unsigned PartBits = PartVT.getSizeInBits();
  441. unsigned OrigNumParts = NumParts;
  442. assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
  443. "Copying to an illegal type!");
  444. if (NumParts == 0)
  445. return;
  446. assert(!ValueVT.isVector() && "Vector case handled elsewhere");
  447. EVT PartEVT = PartVT;
  448. if (PartEVT == ValueVT) {
  449. assert(NumParts == 1 && "No-op copy with multiple parts!");
  450. Parts[0] = Val;
  451. return;
  452. }
  453. if (NumParts * PartBits > ValueVT.getSizeInBits()) {
  454. // If the parts cover more bits than the value has, promote the value.
  455. if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  456. assert(NumParts == 1 && "Do not know what to promote to!");
  457. Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
  458. } else {
  459. if (ValueVT.isFloatingPoint()) {
  460. // FP values need to be bitcast, then extended if they are being put
  461. // into a larger container.
  462. ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  463. Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  464. }
  465. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  466. ValueVT.isInteger() &&
  467. "Unknown mismatch!");
  468. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  469. Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
  470. if (PartVT == MVT::x86mmx)
  471. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  472. }
  473. } else if (PartBits == ValueVT.getSizeInBits()) {
  474. // Different types of the same size.
  475. assert(NumParts == 1 && PartEVT != ValueVT);
  476. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  477. } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
  478. // If the parts cover less bits than value has, truncate the value.
  479. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  480. ValueVT.isInteger() &&
  481. "Unknown mismatch!");
  482. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  483. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  484. if (PartVT == MVT::x86mmx)
  485. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  486. }
  487. // The value may have changed - recompute ValueVT.
  488. ValueVT = Val.getValueType();
  489. assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
  490. "Failed to tile the value with PartVT!");
  491. if (NumParts == 1) {
  492. if (PartEVT != ValueVT) {
  493. diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
  494. "scalar-to-vector conversion failed");
  495. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  496. }
  497. Parts[0] = Val;
  498. return;
  499. }
  500. // Expand the value into multiple parts.
  501. if (NumParts & (NumParts - 1)) {
  502. // The number of parts is not a power of 2. Split off and copy the tail.
  503. assert(PartVT.isInteger() && ValueVT.isInteger() &&
  504. "Do not know what to expand to!");
  505. unsigned RoundParts = 1 << Log2_32(NumParts);
  506. unsigned RoundBits = RoundParts * PartBits;
  507. unsigned OddParts = NumParts - RoundParts;
  508. SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
  509. DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
  510. getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
  511. CallConv);
  512. if (DAG.getDataLayout().isBigEndian())
  513. // The odd parts were reversed by getCopyToParts - unreverse them.
  514. std::reverse(Parts + RoundParts, Parts + NumParts);
  515. NumParts = RoundParts;
  516. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  517. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  518. }
  519. // The number of parts is a power of 2. Repeatedly bisect the value using
  520. // EXTRACT_ELEMENT.
  521. Parts[0] = DAG.getNode(ISD::BITCAST, DL,
  522. EVT::getIntegerVT(*DAG.getContext(),
  523. ValueVT.getSizeInBits()),
  524. Val);
  525. for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
  526. for (unsigned i = 0; i < NumParts; i += StepSize) {
  527. unsigned ThisBits = StepSize * PartBits / 2;
  528. EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
  529. SDValue &Part0 = Parts[i];
  530. SDValue &Part1 = Parts[i+StepSize/2];
  531. Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  532. ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
  533. Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  534. ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
  535. if (ThisBits == PartBits && ThisVT != PartVT) {
  536. Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
  537. Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
  538. }
  539. }
  540. }
  541. if (DAG.getDataLayout().isBigEndian())
  542. std::reverse(Parts, Parts + OrigNumParts);
  543. }
  544. static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
  545. const SDLoc &DL, EVT PartVT) {
  546. if (!PartVT.isVector())
  547. return SDValue();
  548. EVT ValueVT = Val.getValueType();
  549. ElementCount PartNumElts = PartVT.getVectorElementCount();
  550. ElementCount ValueNumElts = ValueVT.getVectorElementCount();
  551. // We only support widening vectors with equivalent element types and
  552. // fixed/scalable properties. If a target needs to widen a fixed-length type
  553. // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
  554. if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
  555. PartNumElts.isScalable() != ValueNumElts.isScalable() ||
  556. PartVT.getVectorElementType() != ValueVT.getVectorElementType())
  557. return SDValue();
  558. // Widening a scalable vector to another scalable vector is done by inserting
  559. // the vector into a larger undef one.
  560. if (PartNumElts.isScalable())
  561. return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
  562. Val, DAG.getVectorIdxConstant(0, DL));
  563. EVT ElementVT = PartVT.getVectorElementType();
  564. // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
  565. // undef elements.
  566. SmallVector<SDValue, 16> Ops;
  567. DAG.ExtractVectorElements(Val, Ops);
  568. SDValue EltUndef = DAG.getUNDEF(ElementVT);
  569. Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
  570. // FIXME: Use CONCAT for 2x -> 4x.
  571. return DAG.getBuildVector(PartVT, DL, Ops);
  572. }
  573. /// getCopyToPartsVector - Create a series of nodes that contain the specified
  574. /// value split into legal parts.
  575. static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  576. SDValue Val, SDValue *Parts, unsigned NumParts,
  577. MVT PartVT, const Value *V,
  578. Optional<CallingConv::ID> CallConv) {
  579. EVT ValueVT = Val.getValueType();
  580. assert(ValueVT.isVector() && "Not a vector");
  581. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  582. const bool IsABIRegCopy = CallConv.hasValue();
  583. if (NumParts == 1) {
  584. EVT PartEVT = PartVT;
  585. if (PartEVT == ValueVT) {
  586. // Nothing to do.
  587. } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
  588. // Bitconvert vector->vector case.
  589. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  590. } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
  591. Val = Widened;
  592. } else if (PartVT.isVector() &&
  593. PartEVT.getVectorElementType().bitsGE(
  594. ValueVT.getVectorElementType()) &&
  595. PartEVT.getVectorElementCount() ==
  596. ValueVT.getVectorElementCount()) {
  597. // Promoted vector extract
  598. Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
  599. } else if (PartEVT.isVector() &&
  600. PartEVT.getVectorElementType() !=
  601. ValueVT.getVectorElementType() &&
  602. TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
  603. TargetLowering::TypeWidenVector) {
  604. // Combination of widening and promotion.
  605. EVT WidenVT =
  606. EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(),
  607. PartVT.getVectorElementCount());
  608. SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
  609. Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
  610. } else {
  611. if (ValueVT.getVectorElementCount().isScalar()) {
  612. Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
  613. DAG.getVectorIdxConstant(0, DL));
  614. } else {
  615. uint64_t ValueSize = ValueVT.getFixedSizeInBits();
  616. assert(PartVT.getFixedSizeInBits() > ValueSize &&
  617. "lossy conversion of vector to scalar type");
  618. EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
  619. Val = DAG.getBitcast(IntermediateType, Val);
  620. Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
  621. }
  622. }
  623. assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
  624. Parts[0] = Val;
  625. return;
  626. }
  627. // Handle a multi-element vector.
  628. EVT IntermediateVT;
  629. MVT RegisterVT;
  630. unsigned NumIntermediates;
  631. unsigned NumRegs;
  632. if (IsABIRegCopy) {
  633. NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
  634. *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
  635. NumIntermediates, RegisterVT);
  636. } else {
  637. NumRegs =
  638. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  639. NumIntermediates, RegisterVT);
  640. }
  641. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  642. NumParts = NumRegs; // Silence a compiler warning.
  643. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  644. assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
  645. "Mixing scalable and fixed vectors when copying in parts");
  646. Optional<ElementCount> DestEltCnt;
  647. if (IntermediateVT.isVector())
  648. DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
  649. else
  650. DestEltCnt = ElementCount::getFixed(NumIntermediates);
  651. EVT BuiltVectorTy = EVT::getVectorVT(
  652. *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt.getValue());
  653. if (ValueVT == BuiltVectorTy) {
  654. // Nothing to do.
  655. } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
  656. // Bitconvert vector->vector case.
  657. Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
  658. } else {
  659. if (BuiltVectorTy.getVectorElementType().bitsGT(
  660. ValueVT.getVectorElementType())) {
  661. // Integer promotion.
  662. ValueVT = EVT::getVectorVT(*DAG.getContext(),
  663. BuiltVectorTy.getVectorElementType(),
  664. ValueVT.getVectorElementCount());
  665. Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
  666. }
  667. if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
  668. Val = Widened;
  669. }
  670. }
  671. assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
  672. // Split the vector into intermediate operands.
  673. SmallVector<SDValue, 8> Ops(NumIntermediates);
  674. for (unsigned i = 0; i != NumIntermediates; ++i) {
  675. if (IntermediateVT.isVector()) {
  676. // This does something sensible for scalable vectors - see the
  677. // definition of EXTRACT_SUBVECTOR for further details.
  678. unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
  679. Ops[i] =
  680. DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
  681. DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
  682. } else {
  683. Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
  684. DAG.getVectorIdxConstant(i, DL));
  685. }
  686. }
  687. // Split the intermediate operands into legal parts.
  688. if (NumParts == NumIntermediates) {
  689. // If the register was not expanded, promote or copy the value,
  690. // as appropriate.
  691. for (unsigned i = 0; i != NumParts; ++i)
  692. getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
  693. } else if (NumParts > 0) {
  694. // If the intermediate type was expanded, split each the value into
  695. // legal parts.
  696. assert(NumIntermediates != 0 && "division by zero");
  697. assert(NumParts % NumIntermediates == 0 &&
  698. "Must expand into a divisible number of parts!");
  699. unsigned Factor = NumParts / NumIntermediates;
  700. for (unsigned i = 0; i != NumIntermediates; ++i)
  701. getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
  702. CallConv);
  703. }
  704. }
  705. RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
  706. EVT valuevt, Optional<CallingConv::ID> CC)
  707. : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
  708. RegCount(1, regs.size()), CallConv(CC) {}
  709. RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
  710. const DataLayout &DL, unsigned Reg, Type *Ty,
  711. Optional<CallingConv::ID> CC) {
  712. ComputeValueVTs(TLI, DL, Ty, ValueVTs);
  713. CallConv = CC;
  714. for (EVT ValueVT : ValueVTs) {
  715. unsigned NumRegs =
  716. isABIMangled()
  717. ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
  718. : TLI.getNumRegisters(Context, ValueVT);
  719. MVT RegisterVT =
  720. isABIMangled()
  721. ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
  722. : TLI.getRegisterType(Context, ValueVT);
  723. for (unsigned i = 0; i != NumRegs; ++i)
  724. Regs.push_back(Reg + i);
  725. RegVTs.push_back(RegisterVT);
  726. RegCount.push_back(NumRegs);
  727. Reg += NumRegs;
  728. }
  729. }
  730. SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
  731. FunctionLoweringInfo &FuncInfo,
  732. const SDLoc &dl, SDValue &Chain,
  733. SDValue *Flag, const Value *V) const {
  734. // A Value with type {} or [0 x %t] needs no registers.
  735. if (ValueVTs.empty())
  736. return SDValue();
  737. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  738. // Assemble the legal parts into the final values.
  739. SmallVector<SDValue, 4> Values(ValueVTs.size());
  740. SmallVector<SDValue, 8> Parts;
  741. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  742. // Copy the legal parts from the registers.
  743. EVT ValueVT = ValueVTs[Value];
  744. unsigned NumRegs = RegCount[Value];
  745. MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
  746. *DAG.getContext(),
  747. CallConv.getValue(), RegVTs[Value])
  748. : RegVTs[Value];
  749. Parts.resize(NumRegs);
  750. for (unsigned i = 0; i != NumRegs; ++i) {
  751. SDValue P;
  752. if (!Flag) {
  753. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
  754. } else {
  755. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
  756. *Flag = P.getValue(2);
  757. }
  758. Chain = P.getValue(1);
  759. Parts[i] = P;
  760. // If the source register was virtual and if we know something about it,
  761. // add an assert node.
  762. if (!Register::isVirtualRegister(Regs[Part + i]) ||
  763. !RegisterVT.isInteger())
  764. continue;
  765. const FunctionLoweringInfo::LiveOutInfo *LOI =
  766. FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
  767. if (!LOI)
  768. continue;
  769. unsigned RegSize = RegisterVT.getScalarSizeInBits();
  770. unsigned NumSignBits = LOI->NumSignBits;
  771. unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
  772. if (NumZeroBits == RegSize) {
  773. // The current value is a zero.
  774. // Explicitly express that as it would be easier for
  775. // optimizations to kick in.
  776. Parts[i] = DAG.getConstant(0, dl, RegisterVT);
  777. continue;
  778. }
  779. // FIXME: We capture more information than the dag can represent. For
  780. // now, just use the tightest assertzext/assertsext possible.
  781. bool isSExt;
  782. EVT FromVT(MVT::Other);
  783. if (NumZeroBits) {
  784. FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
  785. isSExt = false;
  786. } else if (NumSignBits > 1) {
  787. FromVT =
  788. EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
  789. isSExt = true;
  790. } else {
  791. continue;
  792. }
  793. // Add an assertion node.
  794. assert(FromVT != MVT::Other);
  795. Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
  796. RegisterVT, P, DAG.getValueType(FromVT));
  797. }
  798. Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
  799. RegisterVT, ValueVT, V, CallConv);
  800. Part += NumRegs;
  801. Parts.clear();
  802. }
  803. return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
  804. }
  805. void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
  806. const SDLoc &dl, SDValue &Chain, SDValue *Flag,
  807. const Value *V,
  808. ISD::NodeType PreferredExtendType) const {
  809. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  810. ISD::NodeType ExtendKind = PreferredExtendType;
  811. // Get the list of the values's legal parts.
  812. unsigned NumRegs = Regs.size();
  813. SmallVector<SDValue, 8> Parts(NumRegs);
  814. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  815. unsigned NumParts = RegCount[Value];
  816. MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
  817. *DAG.getContext(),
  818. CallConv.getValue(), RegVTs[Value])
  819. : RegVTs[Value];
  820. // We need to zero extend constants that are liveout to match assumptions
  821. // in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
  822. if (ExtendKind == ISD::ANY_EXTEND &&
  823. (TLI.isZExtFree(Val, RegisterVT) || isa<ConstantSDNode>(Val)))
  824. ExtendKind = ISD::ZERO_EXTEND;
  825. getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
  826. NumParts, RegisterVT, V, CallConv, ExtendKind);
  827. Part += NumParts;
  828. }
  829. // Copy the parts into the registers.
  830. SmallVector<SDValue, 8> Chains(NumRegs);
  831. for (unsigned i = 0; i != NumRegs; ++i) {
  832. SDValue Part;
  833. if (!Flag) {
  834. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
  835. } else {
  836. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
  837. *Flag = Part.getValue(1);
  838. }
  839. Chains[i] = Part.getValue(0);
  840. }
  841. if (NumRegs == 1 || Flag)
  842. // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
  843. // flagged to it. That is the CopyToReg nodes and the user are considered
  844. // a single scheduling unit. If we create a TokenFactor and return it as
  845. // chain, then the TokenFactor is both a predecessor (operand) of the
  846. // user as well as a successor (the TF operands are flagged to the user).
  847. // c1, f1 = CopyToReg
  848. // c2, f2 = CopyToReg
  849. // c3 = TokenFactor c1, c2
  850. // ...
  851. // = op c3, ..., f2
  852. Chain = Chains[NumRegs-1];
  853. else
  854. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  855. }
  856. void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
  857. unsigned MatchingIdx, const SDLoc &dl,
  858. SelectionDAG &DAG,
  859. std::vector<SDValue> &Ops) const {
  860. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  861. unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
  862. if (HasMatching)
  863. Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
  864. else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
  865. // Put the register class of the virtual registers in the flag word. That
  866. // way, later passes can recompute register class constraints for inline
  867. // assembly as well as normal instructions.
  868. // Don't do this for tied operands that can use the regclass information
  869. // from the def.
  870. const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
  871. const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
  872. Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
  873. }
  874. SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
  875. Ops.push_back(Res);
  876. if (Code == InlineAsm::Kind_Clobber) {
  877. // Clobbers should always have a 1:1 mapping with registers, and may
  878. // reference registers that have illegal (e.g. vector) types. Hence, we
  879. // shouldn't try to apply any sort of splitting logic to them.
  880. assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
  881. "No 1:1 mapping from clobbers to regs?");
  882. Register SP = TLI.getStackPointerRegisterToSaveRestore();
  883. (void)SP;
  884. for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
  885. Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
  886. assert(
  887. (Regs[I] != SP ||
  888. DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
  889. "If we clobbered the stack pointer, MFI should know about it.");
  890. }
  891. return;
  892. }
  893. for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
  894. MVT RegisterVT = RegVTs[Value];
  895. unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
  896. RegisterVT);
  897. for (unsigned i = 0; i != NumRegs; ++i) {
  898. assert(Reg < Regs.size() && "Mismatch in # registers expected");
  899. unsigned TheReg = Regs[Reg++];
  900. Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
  901. }
  902. }
  903. }
  904. SmallVector<std::pair<unsigned, TypeSize>, 4>
  905. RegsForValue::getRegsAndSizes() const {
  906. SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
  907. unsigned I = 0;
  908. for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
  909. unsigned RegCount = std::get<0>(CountAndVT);
  910. MVT RegisterVT = std::get<1>(CountAndVT);
  911. TypeSize RegisterSize = RegisterVT.getSizeInBits();
  912. for (unsigned E = I + RegCount; I != E; ++I)
  913. OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
  914. }
  915. return OutVec;
  916. }
  917. void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
  918. const TargetLibraryInfo *li) {
  919. AA = aa;
  920. GFI = gfi;
  921. LibInfo = li;
  922. Context = DAG.getContext();
  923. LPadToCallSiteMap.clear();
  924. SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
  925. }
  926. void SelectionDAGBuilder::clear() {
  927. NodeMap.clear();
  928. UnusedArgNodeMap.clear();
  929. PendingLoads.clear();
  930. PendingExports.clear();
  931. PendingConstrainedFP.clear();
  932. PendingConstrainedFPStrict.clear();
  933. CurInst = nullptr;
  934. HasTailCall = false;
  935. SDNodeOrder = LowestSDNodeOrder;
  936. StatepointLowering.clear();
  937. }
  938. void SelectionDAGBuilder::clearDanglingDebugInfo() {
  939. DanglingDebugInfoMap.clear();
  940. }
  941. // Update DAG root to include dependencies on Pending chains.
  942. SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
  943. SDValue Root = DAG.getRoot();
  944. if (Pending.empty())
  945. return Root;
  946. // Add current root to PendingChains, unless we already indirectly
  947. // depend on it.
  948. if (Root.getOpcode() != ISD::EntryToken) {
  949. unsigned i = 0, e = Pending.size();
  950. for (; i != e; ++i) {
  951. assert(Pending[i].getNode()->getNumOperands() > 1);
  952. if (Pending[i].getNode()->getOperand(0) == Root)
  953. break; // Don't add the root if we already indirectly depend on it.
  954. }
  955. if (i == e)
  956. Pending.push_back(Root);
  957. }
  958. if (Pending.size() == 1)
  959. Root = Pending[0];
  960. else
  961. Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
  962. DAG.setRoot(Root);
  963. Pending.clear();
  964. return Root;
  965. }
  966. SDValue SelectionDAGBuilder::getMemoryRoot() {
  967. return updateRoot(PendingLoads);
  968. }
  969. SDValue SelectionDAGBuilder::getRoot() {
  970. // Chain up all pending constrained intrinsics together with all
  971. // pending loads, by simply appending them to PendingLoads and
  972. // then calling getMemoryRoot().
  973. PendingLoads.reserve(PendingLoads.size() +
  974. PendingConstrainedFP.size() +
  975. PendingConstrainedFPStrict.size());
  976. PendingLoads.append(PendingConstrainedFP.begin(),
  977. PendingConstrainedFP.end());
  978. PendingLoads.append(PendingConstrainedFPStrict.begin(),
  979. PendingConstrainedFPStrict.end());
  980. PendingConstrainedFP.clear();
  981. PendingConstrainedFPStrict.clear();
  982. return getMemoryRoot();
  983. }
  984. SDValue SelectionDAGBuilder::getControlRoot() {
  985. // We need to emit pending fpexcept.strict constrained intrinsics,
  986. // so append them to the PendingExports list.
  987. PendingExports.append(PendingConstrainedFPStrict.begin(),
  988. PendingConstrainedFPStrict.end());
  989. PendingConstrainedFPStrict.clear();
  990. return updateRoot(PendingExports);
  991. }
  992. void SelectionDAGBuilder::visit(const Instruction &I) {
  993. // Set up outgoing PHI node register values before emitting the terminator.
  994. if (I.isTerminator()) {
  995. HandlePHINodesInSuccessorBlocks(I.getParent());
  996. }
  997. // Increase the SDNodeOrder if dealing with a non-debug instruction.
  998. if (!isa<DbgInfoIntrinsic>(I))
  999. ++SDNodeOrder;
  1000. CurInst = &I;
  1001. visit(I.getOpcode(), I);
  1002. if (!I.isTerminator() && !HasTailCall &&
  1003. !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
  1004. CopyToExportRegsIfNeeded(&I);
  1005. CurInst = nullptr;
  1006. }
  1007. void SelectionDAGBuilder::visitPHI(const PHINode &) {
  1008. llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
  1009. }
  1010. void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
  1011. // Note: this doesn't use InstVisitor, because it has to work with
  1012. // ConstantExpr's in addition to instructions.
  1013. switch (Opcode) {
  1014. default: llvm_unreachable("Unknown instruction type encountered!");
  1015. // Build the switch statement using the Instruction.def file.
  1016. #define HANDLE_INST(NUM, OPCODE, CLASS) \
  1017. case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
  1018. #include "llvm/IR/Instruction.def"
  1019. }
  1020. }
  1021. void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI,
  1022. DebugLoc DL, unsigned Order) {
  1023. // We treat variadic dbg_values differently at this stage.
  1024. if (DI->hasArgList()) {
  1025. // For variadic dbg_values we will now insert an undef.
  1026. // FIXME: We can potentially recover these!
  1027. SmallVector<SDDbgOperand, 2> Locs;
  1028. for (const Value *V : DI->getValues()) {
  1029. auto Undef = UndefValue::get(V->getType());
  1030. Locs.push_back(SDDbgOperand::fromConst(Undef));
  1031. }
  1032. SDDbgValue *SDV = DAG.getDbgValueList(
  1033. DI->getVariable(), DI->getExpression(), Locs, {},
  1034. /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true);
  1035. DAG.AddDbgValue(SDV, /*isParameter=*/false);
  1036. } else {
  1037. // TODO: Dangling debug info will eventually either be resolved or produce
  1038. // an Undef DBG_VALUE. However in the resolution case, a gap may appear
  1039. // between the original dbg.value location and its resolved DBG_VALUE,
  1040. // which we should ideally fill with an extra Undef DBG_VALUE.
  1041. assert(DI->getNumVariableLocationOps() == 1 &&
  1042. "DbgValueInst without an ArgList should have a single location "
  1043. "operand.");
  1044. DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order);
  1045. }
  1046. }
  1047. void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
  1048. const DIExpression *Expr) {
  1049. auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
  1050. const DbgValueInst *DI = DDI.getDI();
  1051. DIVariable *DanglingVariable = DI->getVariable();
  1052. DIExpression *DanglingExpr = DI->getExpression();
  1053. if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
  1054. LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
  1055. return true;
  1056. }
  1057. return false;
  1058. };
  1059. for (auto &DDIMI : DanglingDebugInfoMap) {
  1060. DanglingDebugInfoVector &DDIV = DDIMI.second;
  1061. // If debug info is to be dropped, run it through final checks to see
  1062. // whether it can be salvaged.
  1063. for (auto &DDI : DDIV)
  1064. if (isMatchingDbgValue(DDI))
  1065. salvageUnresolvedDbgValue(DDI);
  1066. erase_if(DDIV, isMatchingDbgValue);
  1067. }
  1068. }
  1069. // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
  1070. // generate the debug data structures now that we've seen its definition.
  1071. void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
  1072. SDValue Val) {
  1073. auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
  1074. if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
  1075. return;
  1076. DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
  1077. for (auto &DDI : DDIV) {
  1078. const DbgValueInst *DI = DDI.getDI();
  1079. assert(!DI->hasArgList() && "Not implemented for variadic dbg_values");
  1080. assert(DI && "Ill-formed DanglingDebugInfo");
  1081. DebugLoc dl = DDI.getdl();
  1082. unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
  1083. unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
  1084. DILocalVariable *Variable = DI->getVariable();
  1085. DIExpression *Expr = DI->getExpression();
  1086. assert(Variable->isValidLocationForIntrinsic(dl) &&
  1087. "Expected inlined-at fields to agree");
  1088. SDDbgValue *SDV;
  1089. if (Val.getNode()) {
  1090. // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
  1091. // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
  1092. // we couldn't resolve it directly when examining the DbgValue intrinsic
  1093. // in the first place we should not be more successful here). Unless we
  1094. // have some test case that prove this to be correct we should avoid
  1095. // calling EmitFuncArgumentDbgValue here.
  1096. if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
  1097. LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
  1098. << DbgSDNodeOrder << "] for:\n " << *DI << "\n");
  1099. LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump());
  1100. // Increase the SDNodeOrder for the DbgValue here to make sure it is
  1101. // inserted after the definition of Val when emitting the instructions
  1102. // after ISel. An alternative could be to teach
  1103. // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
  1104. LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
  1105. << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
  1106. << ValSDNodeOrder << "\n");
  1107. SDV = getDbgValue(Val, Variable, Expr, dl,
  1108. std::max(DbgSDNodeOrder, ValSDNodeOrder));
  1109. DAG.AddDbgValue(SDV, false);
  1110. } else
  1111. LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
  1112. << "in EmitFuncArgumentDbgValue\n");
  1113. } else {
  1114. LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
  1115. auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
  1116. auto SDV =
  1117. DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
  1118. DAG.AddDbgValue(SDV, false);
  1119. }
  1120. }
  1121. DDIV.clear();
  1122. }
  1123. void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
  1124. // TODO: For the variadic implementation, instead of only checking the fail
  1125. // state of `handleDebugValue`, we need know specifically which values were
  1126. // invalid, so that we attempt to salvage only those values when processing
  1127. // a DIArgList.
  1128. assert(!DDI.getDI()->hasArgList() &&
  1129. "Not implemented for variadic dbg_values");
  1130. Value *V = DDI.getDI()->getValue(0);
  1131. DILocalVariable *Var = DDI.getDI()->getVariable();
  1132. DIExpression *Expr = DDI.getDI()->getExpression();
  1133. DebugLoc DL = DDI.getdl();
  1134. DebugLoc InstDL = DDI.getDI()->getDebugLoc();
  1135. unsigned SDOrder = DDI.getSDNodeOrder();
  1136. // Currently we consider only dbg.value intrinsics -- we tell the salvager
  1137. // that DW_OP_stack_value is desired.
  1138. assert(isa<DbgValueInst>(DDI.getDI()));
  1139. bool StackValue = true;
  1140. // Can this Value can be encoded without any further work?
  1141. if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, /*IsVariadic=*/false))
  1142. return;
  1143. // Attempt to salvage back through as many instructions as possible. Bail if
  1144. // a non-instruction is seen, such as a constant expression or global
  1145. // variable. FIXME: Further work could recover those too.
  1146. while (isa<Instruction>(V)) {
  1147. Instruction &VAsInst = *cast<Instruction>(V);
  1148. // Temporary "0", awaiting real implementation.
  1149. SmallVector<uint64_t, 16> Ops;
  1150. SmallVector<Value *, 4> AdditionalValues;
  1151. V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops,
  1152. AdditionalValues);
  1153. // If we cannot salvage any further, and haven't yet found a suitable debug
  1154. // expression, bail out.
  1155. if (!V)
  1156. break;
  1157. // TODO: If AdditionalValues isn't empty, then the salvage can only be
  1158. // represented with a DBG_VALUE_LIST, so we give up. When we have support
  1159. // here for variadic dbg_values, remove that condition.
  1160. if (!AdditionalValues.empty())
  1161. break;
  1162. // New value and expr now represent this debuginfo.
  1163. Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
  1164. // Some kind of simplification occurred: check whether the operand of the
  1165. // salvaged debug expression can be encoded in this DAG.
  1166. if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder,
  1167. /*IsVariadic=*/false)) {
  1168. LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n "
  1169. << DDI.getDI() << "\nBy stripping back to:\n " << V);
  1170. return;
  1171. }
  1172. }
  1173. // This was the final opportunity to salvage this debug information, and it
  1174. // couldn't be done. Place an undef DBG_VALUE at this location to terminate
  1175. // any earlier variable location.
  1176. auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
  1177. auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
  1178. DAG.AddDbgValue(SDV, false);
  1179. LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI()
  1180. << "\n");
  1181. LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0)
  1182. << "\n");
  1183. }
  1184. bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
  1185. DILocalVariable *Var,
  1186. DIExpression *Expr, DebugLoc dl,
  1187. DebugLoc InstDL, unsigned Order,
  1188. bool IsVariadic) {
  1189. if (Values.empty())
  1190. return true;
  1191. SmallVector<SDDbgOperand> LocationOps;
  1192. SmallVector<SDNode *> Dependencies;
  1193. for (const Value *V : Values) {
  1194. // Constant value.
  1195. if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
  1196. isa<ConstantPointerNull>(V)) {
  1197. LocationOps.emplace_back(SDDbgOperand::fromConst(V));
  1198. continue;
  1199. }
  1200. // If the Value is a frame index, we can create a FrameIndex debug value
  1201. // without relying on the DAG at all.
  1202. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  1203. auto SI = FuncInfo.StaticAllocaMap.find(AI);
  1204. if (SI != FuncInfo.StaticAllocaMap.end()) {
  1205. LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
  1206. continue;
  1207. }
  1208. }
  1209. // Do not use getValue() in here; we don't want to generate code at
  1210. // this point if it hasn't been done yet.
  1211. SDValue N = NodeMap[V];
  1212. if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
  1213. N = UnusedArgNodeMap[V];
  1214. if (N.getNode()) {
  1215. // Only emit func arg dbg value for non-variadic dbg.values for now.
  1216. if (!IsVariadic && EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
  1217. return true;
  1218. if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
  1219. // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
  1220. // describe stack slot locations.
  1221. //
  1222. // Consider "int x = 0; int *px = &x;". There are two kinds of
  1223. // interesting debug values here after optimization:
  1224. //
  1225. // dbg.value(i32* %px, !"int *px", !DIExpression()), and
  1226. // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
  1227. //
  1228. // Both describe the direct values of their associated variables.
  1229. Dependencies.push_back(N.getNode());
  1230. LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
  1231. continue;
  1232. }
  1233. LocationOps.emplace_back(
  1234. SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
  1235. continue;
  1236. }
  1237. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1238. // Special rules apply for the first dbg.values of parameter variables in a
  1239. // function. Identify them by the fact they reference Argument Values, that
  1240. // they're parameters, and they are parameters of the current function. We
  1241. // need to let them dangle until they get an SDNode.
  1242. bool IsParamOfFunc =
  1243. isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt();
  1244. if (IsParamOfFunc)
  1245. return false;
  1246. // The value is not used in this block yet (or it would have an SDNode).
  1247. // We still want the value to appear for the user if possible -- if it has
  1248. // an associated VReg, we can refer to that instead.
  1249. auto VMI = FuncInfo.ValueMap.find(V);
  1250. if (VMI != FuncInfo.ValueMap.end()) {
  1251. unsigned Reg = VMI->second;
  1252. // If this is a PHI node, it may be split up into several MI PHI nodes
  1253. // (in FunctionLoweringInfo::set).
  1254. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
  1255. V->getType(), None);
  1256. if (RFV.occupiesMultipleRegs()) {
  1257. // FIXME: We could potentially support variadic dbg_values here.
  1258. if (IsVariadic)
  1259. return false;
  1260. unsigned Offset = 0;
  1261. unsigned BitsToDescribe = 0;
  1262. if (auto VarSize = Var->getSizeInBits())
  1263. BitsToDescribe = *VarSize;
  1264. if (auto Fragment = Expr->getFragmentInfo())
  1265. BitsToDescribe = Fragment->SizeInBits;
  1266. for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
  1267. // Bail out if all bits are described already.
  1268. if (Offset >= BitsToDescribe)
  1269. break;
  1270. // TODO: handle scalable vectors.
  1271. unsigned RegisterSize = RegAndSize.second;
  1272. unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
  1273. ? BitsToDescribe - Offset
  1274. : RegisterSize;
  1275. auto FragmentExpr = DIExpression::createFragmentExpression(
  1276. Expr, Offset, FragmentSize);
  1277. if (!FragmentExpr)
  1278. continue;
  1279. SDDbgValue *SDV = DAG.getVRegDbgValue(
  1280. Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder);
  1281. DAG.AddDbgValue(SDV, false);
  1282. Offset += RegisterSize;
  1283. }
  1284. return true;
  1285. }
  1286. // We can use simple vreg locations for variadic dbg_values as well.
  1287. LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
  1288. continue;
  1289. }
  1290. // We failed to create a SDDbgOperand for V.
  1291. return false;
  1292. }
  1293. // We have created a SDDbgOperand for each Value in Values.
  1294. // Should use Order instead of SDNodeOrder?
  1295. assert(!LocationOps.empty());
  1296. SDDbgValue *SDV =
  1297. DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
  1298. /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic);
  1299. DAG.AddDbgValue(SDV, /*isParameter=*/false);
  1300. return true;
  1301. }
  1302. void SelectionDAGBuilder::resolveOrClearDbgInfo() {
  1303. // Try to fixup any remaining dangling debug info -- and drop it if we can't.
  1304. for (auto &Pair : DanglingDebugInfoMap)
  1305. for (auto &DDI : Pair.second)
  1306. salvageUnresolvedDbgValue(DDI);
  1307. clearDanglingDebugInfo();
  1308. }
  1309. /// getCopyFromRegs - If there was virtual register allocated for the value V
  1310. /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
  1311. SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
  1312. DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
  1313. SDValue Result;
  1314. if (It != FuncInfo.ValueMap.end()) {
  1315. Register InReg = It->second;
  1316. RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
  1317. DAG.getDataLayout(), InReg, Ty,
  1318. None); // This is not an ABI copy.
  1319. SDValue Chain = DAG.getEntryNode();
  1320. Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
  1321. V);
  1322. resolveDanglingDebugInfo(V, Result);
  1323. }
  1324. return Result;
  1325. }
  1326. /// getValue - Return an SDValue for the given Value.
  1327. SDValue SelectionDAGBuilder::getValue(const Value *V) {
  1328. // If we already have an SDValue for this value, use it. It's important
  1329. // to do this first, so that we don't create a CopyFromReg if we already
  1330. // have a regular SDValue.
  1331. SDValue &N = NodeMap[V];
  1332. if (N.getNode()) return N;
  1333. // If there's a virtual register allocated and initialized for this
  1334. // value, use it.
  1335. if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
  1336. return copyFromReg;
  1337. // Otherwise create a new SDValue and remember it.
  1338. SDValue Val = getValueImpl(V);
  1339. NodeMap[V] = Val;
  1340. resolveDanglingDebugInfo(V, Val);
  1341. return Val;
  1342. }
  1343. /// getNonRegisterValue - Return an SDValue for the given Value, but
  1344. /// don't look in FuncInfo.ValueMap for a virtual register.
  1345. SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
  1346. // If we already have an SDValue for this value, use it.
  1347. SDValue &N = NodeMap[V];
  1348. if (N.getNode()) {
  1349. if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
  1350. // Remove the debug location from the node as the node is about to be used
  1351. // in a location which may differ from the original debug location. This
  1352. // is relevant to Constant and ConstantFP nodes because they can appear
  1353. // as constant expressions inside PHI nodes.
  1354. N->setDebugLoc(DebugLoc());
  1355. }
  1356. return N;
  1357. }
  1358. // Otherwise create a new SDValue and remember it.
  1359. SDValue Val = getValueImpl(V);
  1360. NodeMap[V] = Val;
  1361. resolveDanglingDebugInfo(V, Val);
  1362. return Val;
  1363. }
  1364. /// getValueImpl - Helper function for getValue and getNonRegisterValue.
  1365. /// Create an SDValue for the given value.
  1366. SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
  1367. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1368. if (const Constant *C = dyn_cast<Constant>(V)) {
  1369. EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
  1370. if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
  1371. return DAG.getConstant(*CI, getCurSDLoc(), VT);
  1372. if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
  1373. return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
  1374. if (isa<ConstantPointerNull>(C)) {
  1375. unsigned AS = V->getType()->getPointerAddressSpace();
  1376. return DAG.getConstant(0, getCurSDLoc(),
  1377. TLI.getPointerTy(DAG.getDataLayout(), AS));
  1378. }
  1379. if (match(C, m_VScale(DAG.getDataLayout())))
  1380. return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
  1381. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
  1382. return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
  1383. if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
  1384. return DAG.getUNDEF(VT);
  1385. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  1386. visit(CE->getOpcode(), *CE);
  1387. SDValue N1 = NodeMap[V];
  1388. assert(N1.getNode() && "visit didn't populate the NodeMap!");
  1389. return N1;
  1390. }
  1391. if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
  1392. SmallVector<SDValue, 4> Constants;
  1393. for (const Use &U : C->operands()) {
  1394. SDNode *Val = getValue(U).getNode();
  1395. // If the operand is an empty aggregate, there are no values.
  1396. if (!Val) continue;
  1397. // Add each leaf value from the operand to the Constants list
  1398. // to form a flattened list of all the values.
  1399. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  1400. Constants.push_back(SDValue(Val, i));
  1401. }
  1402. return DAG.getMergeValues(Constants, getCurSDLoc());
  1403. }
  1404. if (const ConstantDataSequential *CDS =
  1405. dyn_cast<ConstantDataSequential>(C)) {
  1406. SmallVector<SDValue, 4> Ops;
  1407. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  1408. SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
  1409. // Add each leaf value from the operand to the Constants list
  1410. // to form a flattened list of all the values.
  1411. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  1412. Ops.push_back(SDValue(Val, i));
  1413. }
  1414. if (isa<ArrayType>(CDS->getType()))
  1415. return DAG.getMergeValues(Ops, getCurSDLoc());
  1416. return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
  1417. }
  1418. if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
  1419. assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
  1420. "Unknown struct or array constant!");
  1421. SmallVector<EVT, 4> ValueVTs;
  1422. ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
  1423. unsigned NumElts = ValueVTs.size();
  1424. if (NumElts == 0)
  1425. return SDValue(); // empty struct
  1426. SmallVector<SDValue, 4> Constants(NumElts);
  1427. for (unsigned i = 0; i != NumElts; ++i) {
  1428. EVT EltVT = ValueVTs[i];
  1429. if (isa<UndefValue>(C))
  1430. Constants[i] = DAG.getUNDEF(EltVT);
  1431. else if (EltVT.isFloatingPoint())
  1432. Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  1433. else
  1434. Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
  1435. }
  1436. return DAG.getMergeValues(Constants, getCurSDLoc());
  1437. }
  1438. if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
  1439. return DAG.getBlockAddress(BA, VT);
  1440. if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
  1441. return getValue(Equiv->getGlobalValue());
  1442. if (const auto *NC = dyn_cast<NoCFIValue>(C))
  1443. return getValue(NC->getGlobalValue());
  1444. VectorType *VecTy = cast<VectorType>(V->getType());
  1445. // Now that we know the number and type of the elements, get that number of
  1446. // elements into the Ops array based on what kind of constant it is.
  1447. if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
  1448. SmallVector<SDValue, 16> Ops;
  1449. unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
  1450. for (unsigned i = 0; i != NumElements; ++i)
  1451. Ops.push_back(getValue(CV->getOperand(i)));
  1452. return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
  1453. } else if (isa<ConstantAggregateZero>(C)) {
  1454. EVT EltVT =
  1455. TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
  1456. SDValue Op;
  1457. if (EltVT.isFloatingPoint())
  1458. Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  1459. else
  1460. Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
  1461. if (isa<ScalableVectorType>(VecTy))
  1462. return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op);
  1463. else {
  1464. SmallVector<SDValue, 16> Ops;
  1465. Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op);
  1466. return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
  1467. }
  1468. }
  1469. llvm_unreachable("Unknown vector constant");
  1470. }
  1471. // If this is a static alloca, generate it as the frameindex instead of
  1472. // computation.
  1473. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  1474. DenseMap<const AllocaInst*, int>::iterator SI =
  1475. FuncInfo.StaticAllocaMap.find(AI);
  1476. if (SI != FuncInfo.StaticAllocaMap.end())
  1477. return DAG.getFrameIndex(SI->second,
  1478. TLI.getFrameIndexTy(DAG.getDataLayout()));
  1479. }
  1480. // If this is an instruction which fast-isel has deferred, select it now.
  1481. if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
  1482. unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
  1483. RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
  1484. Inst->getType(), None);
  1485. SDValue Chain = DAG.getEntryNode();
  1486. return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
  1487. }
  1488. if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) {
  1489. return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
  1490. }
  1491. if (const auto *BB = dyn_cast<BasicBlock>(V))
  1492. return DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
  1493. llvm_unreachable("Can't get register for value!");
  1494. }
  1495. void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
  1496. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1497. bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
  1498. bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
  1499. bool IsSEH = isAsynchronousEHPersonality(Pers);
  1500. MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
  1501. if (!IsSEH)
  1502. CatchPadMBB->setIsEHScopeEntry();
  1503. // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
  1504. if (IsMSVCCXX || IsCoreCLR)
  1505. CatchPadMBB->setIsEHFuncletEntry();
  1506. }
  1507. void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
  1508. // Update machine-CFG edge.
  1509. MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
  1510. FuncInfo.MBB->addSuccessor(TargetMBB);
  1511. TargetMBB->setIsEHCatchretTarget(true);
  1512. DAG.getMachineFunction().setHasEHCatchret(true);
  1513. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1514. bool IsSEH = isAsynchronousEHPersonality(Pers);
  1515. if (IsSEH) {
  1516. // If this is not a fall-through branch or optimizations are switched off,
  1517. // emit the branch.
  1518. if (TargetMBB != NextBlock(FuncInfo.MBB) ||
  1519. TM.getOptLevel() == CodeGenOpt::None)
  1520. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  1521. getControlRoot(), DAG.getBasicBlock(TargetMBB)));
  1522. return;
  1523. }
  1524. // Figure out the funclet membership for the catchret's successor.
  1525. // This will be used by the FuncletLayout pass to determine how to order the
  1526. // BB's.
  1527. // A 'catchret' returns to the outer scope's color.
  1528. Value *ParentPad = I.getCatchSwitchParentPad();
  1529. const BasicBlock *SuccessorColor;
  1530. if (isa<ConstantTokenNone>(ParentPad))
  1531. SuccessorColor = &FuncInfo.Fn->getEntryBlock();
  1532. else
  1533. SuccessorColor = cast<Instruction>(ParentPad)->getParent();
  1534. assert(SuccessorColor && "No parent funclet for catchret!");
  1535. MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
  1536. assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
  1537. // Create the terminator node.
  1538. SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
  1539. getControlRoot(), DAG.getBasicBlock(TargetMBB),
  1540. DAG.getBasicBlock(SuccessorColorMBB));
  1541. DAG.setRoot(Ret);
  1542. }
  1543. void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
  1544. // Don't emit any special code for the cleanuppad instruction. It just marks
  1545. // the start of an EH scope/funclet.
  1546. FuncInfo.MBB->setIsEHScopeEntry();
  1547. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1548. if (Pers != EHPersonality::Wasm_CXX) {
  1549. FuncInfo.MBB->setIsEHFuncletEntry();
  1550. FuncInfo.MBB->setIsCleanupFuncletEntry();
  1551. }
  1552. }
  1553. // In wasm EH, even though a catchpad may not catch an exception if a tag does
  1554. // not match, it is OK to add only the first unwind destination catchpad to the
  1555. // successors, because there will be at least one invoke instruction within the
  1556. // catch scope that points to the next unwind destination, if one exists, so
  1557. // CFGSort cannot mess up with BB sorting order.
  1558. // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
  1559. // call within them, and catchpads only consisting of 'catch (...)' have a
  1560. // '__cxa_end_catch' call within them, both of which generate invokes in case
  1561. // the next unwind destination exists, i.e., the next unwind destination is not
  1562. // the caller.)
  1563. //
  1564. // Having at most one EH pad successor is also simpler and helps later
  1565. // transformations.
  1566. //
  1567. // For example,
  1568. // current:
  1569. // invoke void @foo to ... unwind label %catch.dispatch
  1570. // catch.dispatch:
  1571. // %0 = catchswitch within ... [label %catch.start] unwind label %next
  1572. // catch.start:
  1573. // ...
  1574. // ... in this BB or some other child BB dominated by this BB there will be an
  1575. // invoke that points to 'next' BB as an unwind destination
  1576. //
  1577. // next: ; We don't need to add this to 'current' BB's successor
  1578. // ...
  1579. static void findWasmUnwindDestinations(
  1580. FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
  1581. BranchProbability Prob,
  1582. SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
  1583. &UnwindDests) {
  1584. while (EHPadBB) {
  1585. const Instruction *Pad = EHPadBB->getFirstNonPHI();
  1586. if (isa<CleanupPadInst>(Pad)) {
  1587. // Stop on cleanup pads.
  1588. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1589. UnwindDests.back().first->setIsEHScopeEntry();
  1590. break;
  1591. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
  1592. // Add the catchpad handlers to the possible destinations. We don't
  1593. // continue to the unwind destination of the catchswitch for wasm.
  1594. for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
  1595. UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
  1596. UnwindDests.back().first->setIsEHScopeEntry();
  1597. }
  1598. break;
  1599. } else {
  1600. continue;
  1601. }
  1602. }
  1603. }
  1604. /// When an invoke or a cleanupret unwinds to the next EH pad, there are
  1605. /// many places it could ultimately go. In the IR, we have a single unwind
  1606. /// destination, but in the machine CFG, we enumerate all the possible blocks.
  1607. /// This function skips over imaginary basic blocks that hold catchswitch
  1608. /// instructions, and finds all the "real" machine
  1609. /// basic block destinations. As those destinations may not be successors of
  1610. /// EHPadBB, here we also calculate the edge probability to those destinations.
  1611. /// The passed-in Prob is the edge probability to EHPadBB.
  1612. static void findUnwindDestinations(
  1613. FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
  1614. BranchProbability Prob,
  1615. SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
  1616. &UnwindDests) {
  1617. EHPersonality Personality =
  1618. classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1619. bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
  1620. bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
  1621. bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
  1622. bool IsSEH = isAsynchronousEHPersonality(Personality);
  1623. if (IsWasmCXX) {
  1624. findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
  1625. assert(UnwindDests.size() <= 1 &&
  1626. "There should be at most one unwind destination for wasm");
  1627. return;
  1628. }
  1629. while (EHPadBB) {
  1630. const Instruction *Pad = EHPadBB->getFirstNonPHI();
  1631. BasicBlock *NewEHPadBB = nullptr;
  1632. if (isa<LandingPadInst>(Pad)) {
  1633. // Stop on landingpads. They are not funclets.
  1634. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1635. break;
  1636. } else if (isa<CleanupPadInst>(Pad)) {
  1637. // Stop on cleanup pads. Cleanups are always funclet entries for all known
  1638. // personalities.
  1639. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1640. UnwindDests.back().first->setIsEHScopeEntry();
  1641. UnwindDests.back().first->setIsEHFuncletEntry();
  1642. break;
  1643. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
  1644. // Add the catchpad handlers to the possible destinations.
  1645. for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
  1646. UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
  1647. // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
  1648. if (IsMSVCCXX || IsCoreCLR)
  1649. UnwindDests.back().first->setIsEHFuncletEntry();
  1650. if (!IsSEH)
  1651. UnwindDests.back().first->setIsEHScopeEntry();
  1652. }
  1653. NewEHPadBB = CatchSwitch->getUnwindDest();
  1654. } else {
  1655. continue;
  1656. }
  1657. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1658. if (BPI && NewEHPadBB)
  1659. Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
  1660. EHPadBB = NewEHPadBB;
  1661. }
  1662. }
  1663. void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
  1664. // Update successor info.
  1665. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  1666. auto UnwindDest = I.getUnwindDest();
  1667. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1668. BranchProbability UnwindDestProb =
  1669. (BPI && UnwindDest)
  1670. ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
  1671. : BranchProbability::getZero();
  1672. findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
  1673. for (auto &UnwindDest : UnwindDests) {
  1674. UnwindDest.first->setIsEHPad();
  1675. addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
  1676. }
  1677. FuncInfo.MBB->normalizeSuccProbs();
  1678. // Create the terminator node.
  1679. SDValue Ret =
  1680. DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
  1681. DAG.setRoot(Ret);
  1682. }
  1683. void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
  1684. report_fatal_error("visitCatchSwitch not yet implemented!");
  1685. }
  1686. void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
  1687. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1688. auto &DL = DAG.getDataLayout();
  1689. SDValue Chain = getControlRoot();
  1690. SmallVector<ISD::OutputArg, 8> Outs;
  1691. SmallVector<SDValue, 8> OutVals;
  1692. // Calls to @llvm.experimental.deoptimize don't generate a return value, so
  1693. // lower
  1694. //
  1695. // %val = call <ty> @llvm.experimental.deoptimize()
  1696. // ret <ty> %val
  1697. //
  1698. // differently.
  1699. if (I.getParent()->getTerminatingDeoptimizeCall()) {
  1700. LowerDeoptimizingReturn();
  1701. return;
  1702. }
  1703. if (!FuncInfo.CanLowerReturn) {
  1704. unsigned DemoteReg = FuncInfo.DemoteRegister;
  1705. const Function *F = I.getParent()->getParent();
  1706. // Emit a store of the return value through the virtual register.
  1707. // Leave Outs empty so that LowerReturn won't try to load return
  1708. // registers the usual way.
  1709. SmallVector<EVT, 1> PtrValueVTs;
  1710. ComputeValueVTs(TLI, DL,
  1711. F->getReturnType()->getPointerTo(
  1712. DAG.getDataLayout().getAllocaAddrSpace()),
  1713. PtrValueVTs);
  1714. SDValue RetPtr =
  1715. DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
  1716. SDValue RetOp = getValue(I.getOperand(0));
  1717. SmallVector<EVT, 4> ValueVTs, MemVTs;
  1718. SmallVector<uint64_t, 4> Offsets;
  1719. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
  1720. &Offsets);
  1721. unsigned NumValues = ValueVTs.size();
  1722. SmallVector<SDValue, 4> Chains(NumValues);
  1723. Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
  1724. for (unsigned i = 0; i != NumValues; ++i) {
  1725. // An aggregate return value cannot wrap around the address space, so
  1726. // offsets to its parts don't wrap either.
  1727. SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
  1728. TypeSize::Fixed(Offsets[i]));
  1729. SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
  1730. if (MemVTs[i] != ValueVTs[i])
  1731. Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
  1732. Chains[i] = DAG.getStore(
  1733. Chain, getCurSDLoc(), Val,
  1734. // FIXME: better loc info would be nice.
  1735. Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
  1736. commonAlignment(BaseAlign, Offsets[i]));
  1737. }
  1738. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
  1739. MVT::Other, Chains);
  1740. } else if (I.getNumOperands() != 0) {
  1741. SmallVector<EVT, 4> ValueVTs;
  1742. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
  1743. unsigned NumValues = ValueVTs.size();
  1744. if (NumValues) {
  1745. SDValue RetOp = getValue(I.getOperand(0));
  1746. const Function *F = I.getParent()->getParent();
  1747. bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
  1748. I.getOperand(0)->getType(), F->getCallingConv(),
  1749. /*IsVarArg*/ false, DL);
  1750. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  1751. if (F->getAttributes().hasRetAttr(Attribute::SExt))
  1752. ExtendKind = ISD::SIGN_EXTEND;
  1753. else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
  1754. ExtendKind = ISD::ZERO_EXTEND;
  1755. LLVMContext &Context = F->getContext();
  1756. bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
  1757. for (unsigned j = 0; j != NumValues; ++j) {
  1758. EVT VT = ValueVTs[j];
  1759. if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
  1760. VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
  1761. CallingConv::ID CC = F->getCallingConv();
  1762. unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
  1763. MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
  1764. SmallVector<SDValue, 4> Parts(NumParts);
  1765. getCopyToParts(DAG, getCurSDLoc(),
  1766. SDValue(RetOp.getNode(), RetOp.getResNo() + j),
  1767. &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
  1768. // 'inreg' on function refers to return value
  1769. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1770. if (RetInReg)
  1771. Flags.setInReg();
  1772. if (I.getOperand(0)->getType()->isPointerTy()) {
  1773. Flags.setPointer();
  1774. Flags.setPointerAddrSpace(
  1775. cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
  1776. }
  1777. if (NeedsRegBlock) {
  1778. Flags.setInConsecutiveRegs();
  1779. if (j == NumValues - 1)
  1780. Flags.setInConsecutiveRegsLast();
  1781. }
  1782. // Propagate extension type if any
  1783. if (ExtendKind == ISD::SIGN_EXTEND)
  1784. Flags.setSExt();
  1785. else if (ExtendKind == ISD::ZERO_EXTEND)
  1786. Flags.setZExt();
  1787. for (unsigned i = 0; i < NumParts; ++i) {
  1788. Outs.push_back(ISD::OutputArg(Flags,
  1789. Parts[i].getValueType().getSimpleVT(),
  1790. VT, /*isfixed=*/true, 0, 0));
  1791. OutVals.push_back(Parts[i]);
  1792. }
  1793. }
  1794. }
  1795. }
  1796. // Push in swifterror virtual register as the last element of Outs. This makes
  1797. // sure swifterror virtual register will be returned in the swifterror
  1798. // physical register.
  1799. const Function *F = I.getParent()->getParent();
  1800. if (TLI.supportSwiftError() &&
  1801. F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
  1802. assert(SwiftError.getFunctionArg() && "Need a swift error argument");
  1803. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1804. Flags.setSwiftError();
  1805. Outs.push_back(ISD::OutputArg(
  1806. Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
  1807. /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
  1808. // Create SDNode for the swifterror virtual register.
  1809. OutVals.push_back(
  1810. DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
  1811. &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
  1812. EVT(TLI.getPointerTy(DL))));
  1813. }
  1814. bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
  1815. CallingConv::ID CallConv =
  1816. DAG.getMachineFunction().getFunction().getCallingConv();
  1817. Chain = DAG.getTargetLoweringInfo().LowerReturn(
  1818. Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
  1819. // Verify that the target's LowerReturn behaved as expected.
  1820. assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
  1821. "LowerReturn didn't return a valid chain!");
  1822. // Update the DAG with the new chain value resulting from return lowering.
  1823. DAG.setRoot(Chain);
  1824. }
  1825. /// CopyToExportRegsIfNeeded - If the given value has virtual registers
  1826. /// created for it, emit nodes to copy the value into the virtual
  1827. /// registers.
  1828. void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
  1829. // Skip empty types
  1830. if (V->getType()->isEmptyTy())
  1831. return;
  1832. DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
  1833. if (VMI != FuncInfo.ValueMap.end()) {
  1834. assert(!V->use_empty() && "Unused value assigned virtual registers!");
  1835. CopyValueToVirtualRegister(V, VMI->second);
  1836. }
  1837. }
  1838. /// ExportFromCurrentBlock - If this condition isn't known to be exported from
  1839. /// the current basic block, add it to ValueMap now so that we'll get a
  1840. /// CopyTo/FromReg.
  1841. void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
  1842. // No need to export constants.
  1843. if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
  1844. // Already exported?
  1845. if (FuncInfo.isExportedInst(V)) return;
  1846. unsigned Reg = FuncInfo.InitializeRegForValue(V);
  1847. CopyValueToVirtualRegister(V, Reg);
  1848. }
  1849. bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
  1850. const BasicBlock *FromBB) {
  1851. // The operands of the setcc have to be in this block. We don't know
  1852. // how to export them from some other block.
  1853. if (const Instruction *VI = dyn_cast<Instruction>(V)) {
  1854. // Can export from current BB.
  1855. if (VI->getParent() == FromBB)
  1856. return true;
  1857. // Is already exported, noop.
  1858. return FuncInfo.isExportedInst(V);
  1859. }
  1860. // If this is an argument, we can export it if the BB is the entry block or
  1861. // if it is already exported.
  1862. if (isa<Argument>(V)) {
  1863. if (FromBB->isEntryBlock())
  1864. return true;
  1865. // Otherwise, can only export this if it is already exported.
  1866. return FuncInfo.isExportedInst(V);
  1867. }
  1868. // Otherwise, constants can always be exported.
  1869. return true;
  1870. }
  1871. /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
  1872. BranchProbability
  1873. SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
  1874. const MachineBasicBlock *Dst) const {
  1875. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1876. const BasicBlock *SrcBB = Src->getBasicBlock();
  1877. const BasicBlock *DstBB = Dst->getBasicBlock();
  1878. if (!BPI) {
  1879. // If BPI is not available, set the default probability as 1 / N, where N is
  1880. // the number of successors.
  1881. auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
  1882. return BranchProbability(1, SuccSize);
  1883. }
  1884. return BPI->getEdgeProbability(SrcBB, DstBB);
  1885. }
  1886. void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
  1887. MachineBasicBlock *Dst,
  1888. BranchProbability Prob) {
  1889. if (!FuncInfo.BPI)
  1890. Src->addSuccessorWithoutProb(Dst);
  1891. else {
  1892. if (Prob.isUnknown())
  1893. Prob = getEdgeProbability(Src, Dst);
  1894. Src->addSuccessor(Dst, Prob);
  1895. }
  1896. }
  1897. static bool InBlock(const Value *V, const BasicBlock *BB) {
  1898. if (const Instruction *I = dyn_cast<Instruction>(V))
  1899. return I->getParent() == BB;
  1900. return true;
  1901. }
  1902. /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
  1903. /// This function emits a branch and is used at the leaves of an OR or an
  1904. /// AND operator tree.
  1905. void
  1906. SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
  1907. MachineBasicBlock *TBB,
  1908. MachineBasicBlock *FBB,
  1909. MachineBasicBlock *CurBB,
  1910. MachineBasicBlock *SwitchBB,
  1911. BranchProbability TProb,
  1912. BranchProbability FProb,
  1913. bool InvertCond) {
  1914. const BasicBlock *BB = CurBB->getBasicBlock();
  1915. // If the leaf of the tree is a comparison, merge the condition into
  1916. // the caseblock.
  1917. if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
  1918. // The operands of the cmp have to be in this block. We don't know
  1919. // how to export them from some other block. If this is the first block
  1920. // of the sequence, no exporting is needed.
  1921. if (CurBB == SwitchBB ||
  1922. (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
  1923. isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
  1924. ISD::CondCode Condition;
  1925. if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
  1926. ICmpInst::Predicate Pred =
  1927. InvertCond ? IC->getInversePredicate() : IC->getPredicate();
  1928. Condition = getICmpCondCode(Pred);
  1929. } else {
  1930. const FCmpInst *FC = cast<FCmpInst>(Cond);
  1931. FCmpInst::Predicate Pred =
  1932. InvertCond ? FC->getInversePredicate() : FC->getPredicate();
  1933. Condition = getFCmpCondCode(Pred);
  1934. if (TM.Options.NoNaNsFPMath)
  1935. Condition = getFCmpCodeWithoutNaN(Condition);
  1936. }
  1937. CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
  1938. TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
  1939. SL->SwitchCases.push_back(CB);
  1940. return;
  1941. }
  1942. }
  1943. // Create a CaseBlock record representing this branch.
  1944. ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
  1945. CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
  1946. nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
  1947. SL->SwitchCases.push_back(CB);
  1948. }
  1949. void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
  1950. MachineBasicBlock *TBB,
  1951. MachineBasicBlock *FBB,
  1952. MachineBasicBlock *CurBB,
  1953. MachineBasicBlock *SwitchBB,
  1954. Instruction::BinaryOps Opc,
  1955. BranchProbability TProb,
  1956. BranchProbability FProb,
  1957. bool InvertCond) {
  1958. // Skip over not part of the tree and remember to invert op and operands at
  1959. // next level.
  1960. Value *NotCond;
  1961. if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
  1962. InBlock(NotCond, CurBB->getBasicBlock())) {
  1963. FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
  1964. !InvertCond);
  1965. return;
  1966. }
  1967. const Instruction *BOp = dyn_cast<Instruction>(Cond);
  1968. const Value *BOpOp0, *BOpOp1;
  1969. // Compute the effective opcode for Cond, taking into account whether it needs
  1970. // to be inverted, e.g.
  1971. // and (not (or A, B)), C
  1972. // gets lowered as
  1973. // and (and (not A, not B), C)
  1974. Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
  1975. if (BOp) {
  1976. BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
  1977. ? Instruction::And
  1978. : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
  1979. ? Instruction::Or
  1980. : (Instruction::BinaryOps)0);
  1981. if (InvertCond) {
  1982. if (BOpc == Instruction::And)
  1983. BOpc = Instruction::Or;
  1984. else if (BOpc == Instruction::Or)
  1985. BOpc = Instruction::And;
  1986. }
  1987. }
  1988. // If this node is not part of the or/and tree, emit it as a branch.
  1989. // Note that all nodes in the tree should have same opcode.
  1990. bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
  1991. if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
  1992. !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
  1993. !InBlock(BOpOp1, CurBB->getBasicBlock())) {
  1994. EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
  1995. TProb, FProb, InvertCond);
  1996. return;
  1997. }
  1998. // Create TmpBB after CurBB.
  1999. MachineFunction::iterator BBI(CurBB);
  2000. MachineFunction &MF = DAG.getMachineFunction();
  2001. MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
  2002. CurBB->getParent()->insert(++BBI, TmpBB);
  2003. if (Opc == Instruction::Or) {
  2004. // Codegen X | Y as:
  2005. // BB1:
  2006. // jmp_if_X TBB
  2007. // jmp TmpBB
  2008. // TmpBB:
  2009. // jmp_if_Y TBB
  2010. // jmp FBB
  2011. //
  2012. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  2013. // The requirement is that
  2014. // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
  2015. // = TrueProb for original BB.
  2016. // Assuming the original probabilities are A and B, one choice is to set
  2017. // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
  2018. // A/(1+B) and 2B/(1+B). This choice assumes that
  2019. // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
  2020. // Another choice is to assume TrueProb for BB1 equals to TrueProb for
  2021. // TmpBB, but the math is more complicated.
  2022. auto NewTrueProb = TProb / 2;
  2023. auto NewFalseProb = TProb / 2 + FProb;
  2024. // Emit the LHS condition.
  2025. FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
  2026. NewFalseProb, InvertCond);
  2027. // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
  2028. SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
  2029. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  2030. // Emit the RHS condition into TmpBB.
  2031. FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
  2032. Probs[1], InvertCond);
  2033. } else {
  2034. assert(Opc == Instruction::And && "Unknown merge op!");
  2035. // Codegen X & Y as:
  2036. // BB1:
  2037. // jmp_if_X TmpBB
  2038. // jmp FBB
  2039. // TmpBB:
  2040. // jmp_if_Y TBB
  2041. // jmp FBB
  2042. //
  2043. // This requires creation of TmpBB after CurBB.
  2044. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  2045. // The requirement is that
  2046. // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
  2047. // = FalseProb for original BB.
  2048. // Assuming the original probabilities are A and B, one choice is to set
  2049. // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
  2050. // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
  2051. // TrueProb for BB1 * FalseProb for TmpBB.
  2052. auto NewTrueProb = TProb + FProb / 2;
  2053. auto NewFalseProb = FProb / 2;
  2054. // Emit the LHS condition.
  2055. FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
  2056. NewFalseProb, InvertCond);
  2057. // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
  2058. SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
  2059. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  2060. // Emit the RHS condition into TmpBB.
  2061. FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
  2062. Probs[1], InvertCond);
  2063. }
  2064. }
  2065. /// If the set of cases should be emitted as a series of branches, return true.
  2066. /// If we should emit this as a bunch of and/or'd together conditions, return
  2067. /// false.
  2068. bool
  2069. SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
  2070. if (Cases.size() != 2) return true;
  2071. // If this is two comparisons of the same values or'd or and'd together, they
  2072. // will get folded into a single comparison, so don't emit two blocks.
  2073. if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
  2074. Cases[0].CmpRHS == Cases[1].CmpRHS) ||
  2075. (Cases[0].CmpRHS == Cases[1].CmpLHS &&
  2076. Cases[0].CmpLHS == Cases[1].CmpRHS)) {
  2077. return false;
  2078. }
  2079. // Handle: (X != null) | (Y != null) --> (X|Y) != 0
  2080. // Handle: (X == null) & (Y == null) --> (X|Y) == 0
  2081. if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
  2082. Cases[0].CC == Cases[1].CC &&
  2083. isa<Constant>(Cases[0].CmpRHS) &&
  2084. cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
  2085. if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
  2086. return false;
  2087. if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
  2088. return false;
  2089. }
  2090. return true;
  2091. }
  2092. void SelectionDAGBuilder::visitBr(const BranchInst &I) {
  2093. MachineBasicBlock *BrMBB = FuncInfo.MBB;
  2094. // Update machine-CFG edges.
  2095. MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
  2096. if (I.isUnconditional()) {
  2097. // Update machine-CFG edges.
  2098. BrMBB->addSuccessor(Succ0MBB);
  2099. // If this is not a fall-through branch or optimizations are switched off,
  2100. // emit the branch.
  2101. if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
  2102. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  2103. MVT::Other, getControlRoot(),
  2104. DAG.getBasicBlock(Succ0MBB)));
  2105. return;
  2106. }
  2107. // If this condition is one of the special cases we handle, do special stuff
  2108. // now.
  2109. const Value *CondVal = I.getCondition();
  2110. MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
  2111. // If this is a series of conditions that are or'd or and'd together, emit
  2112. // this as a sequence of branches instead of setcc's with and/or operations.
  2113. // As long as jumps are not expensive (exceptions for multi-use logic ops,
  2114. // unpredictable branches, and vector extracts because those jumps are likely
  2115. // expensive for any target), this should improve performance.
  2116. // For example, instead of something like:
  2117. // cmp A, B
  2118. // C = seteq
  2119. // cmp D, E
  2120. // F = setle
  2121. // or C, F
  2122. // jnz foo
  2123. // Emit:
  2124. // cmp A, B
  2125. // je foo
  2126. // cmp D, E
  2127. // jle foo
  2128. const Instruction *BOp = dyn_cast<Instruction>(CondVal);
  2129. if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
  2130. BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
  2131. Value *Vec;
  2132. const Value *BOp0, *BOp1;
  2133. Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
  2134. if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
  2135. Opcode = Instruction::And;
  2136. else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
  2137. Opcode = Instruction::Or;
  2138. if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
  2139. match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
  2140. FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
  2141. getEdgeProbability(BrMBB, Succ0MBB),
  2142. getEdgeProbability(BrMBB, Succ1MBB),
  2143. /*InvertCond=*/false);
  2144. // If the compares in later blocks need to use values not currently
  2145. // exported from this block, export them now. This block should always
  2146. // be the first entry.
  2147. assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
  2148. // Allow some cases to be rejected.
  2149. if (ShouldEmitAsBranches(SL->SwitchCases)) {
  2150. for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
  2151. ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
  2152. ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
  2153. }
  2154. // Emit the branch for this block.
  2155. visitSwitchCase(SL->SwitchCases[0], BrMBB);
  2156. SL->SwitchCases.erase(SL->SwitchCases.begin());
  2157. return;
  2158. }
  2159. // Okay, we decided not to do this, remove any inserted MBB's and clear
  2160. // SwitchCases.
  2161. for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
  2162. FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
  2163. SL->SwitchCases.clear();
  2164. }
  2165. }
  2166. // Create a CaseBlock record representing this branch.
  2167. CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
  2168. nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
  2169. // Use visitSwitchCase to actually insert the fast branch sequence for this
  2170. // cond branch.
  2171. visitSwitchCase(CB, BrMBB);
  2172. }
  2173. /// visitSwitchCase - Emits the necessary code to represent a single node in
  2174. /// the binary search tree resulting from lowering a switch instruction.
  2175. void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
  2176. MachineBasicBlock *SwitchBB) {
  2177. SDValue Cond;
  2178. SDValue CondLHS = getValue(CB.CmpLHS);
  2179. SDLoc dl = CB.DL;
  2180. if (CB.CC == ISD::SETTRUE) {
  2181. // Branch or fall through to TrueBB.
  2182. addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
  2183. SwitchBB->normalizeSuccProbs();
  2184. if (CB.TrueBB != NextBlock(SwitchBB)) {
  2185. DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
  2186. DAG.getBasicBlock(CB.TrueBB)));
  2187. }
  2188. return;
  2189. }
  2190. auto &TLI = DAG.getTargetLoweringInfo();
  2191. EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
  2192. // Build the setcc now.
  2193. if (!CB.CmpMHS) {
  2194. // Fold "(X == true)" to X and "(X == false)" to !X to
  2195. // handle common cases produced by branch lowering.
  2196. if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
  2197. CB.CC == ISD::SETEQ)
  2198. Cond = CondLHS;
  2199. else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
  2200. CB.CC == ISD::SETEQ) {
  2201. SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
  2202. Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
  2203. } else {
  2204. SDValue CondRHS = getValue(CB.CmpRHS);
  2205. // If a pointer's DAG type is larger than its memory type then the DAG
  2206. // values are zero-extended. This breaks signed comparisons so truncate
  2207. // back to the underlying type before doing the compare.
  2208. if (CondLHS.getValueType() != MemVT) {
  2209. CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
  2210. CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
  2211. }
  2212. Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
  2213. }
  2214. } else {
  2215. assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
  2216. const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
  2217. const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
  2218. SDValue CmpOp = getValue(CB.CmpMHS);
  2219. EVT VT = CmpOp.getValueType();
  2220. if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
  2221. Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
  2222. ISD::SETLE);
  2223. } else {
  2224. SDValue SUB = DAG.getNode(ISD::SUB, dl,
  2225. VT, CmpOp, DAG.getConstant(Low, dl, VT));
  2226. Cond = DAG.getSetCC(dl, MVT::i1, SUB,
  2227. DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
  2228. }
  2229. }
  2230. // Update successor info
  2231. addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
  2232. // TrueBB and FalseBB are always different unless the incoming IR is
  2233. // degenerate. This only happens when running llc on weird IR.
  2234. if (CB.TrueBB != CB.FalseBB)
  2235. addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
  2236. SwitchBB->normalizeSuccProbs();
  2237. // If the lhs block is the next block, invert the condition so that we can
  2238. // fall through to the lhs instead of the rhs block.
  2239. if (CB.TrueBB == NextBlock(SwitchBB)) {
  2240. std::swap(CB.TrueBB, CB.FalseBB);
  2241. SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
  2242. Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
  2243. }
  2244. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2245. MVT::Other, getControlRoot(), Cond,
  2246. DAG.getBasicBlock(CB.TrueBB));
  2247. // Insert the false branch. Do this even if it's a fall through branch,
  2248. // this makes it easier to do DAG optimizations which require inverting
  2249. // the branch condition.
  2250. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  2251. DAG.getBasicBlock(CB.FalseBB));
  2252. DAG.setRoot(BrCond);
  2253. }
  2254. /// visitJumpTable - Emit JumpTable node in the current MBB
  2255. void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
  2256. // Emit the code for the jump table
  2257. assert(JT.Reg != -1U && "Should lower JT Header first!");
  2258. EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
  2259. SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
  2260. JT.Reg, PTy);
  2261. SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
  2262. SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
  2263. MVT::Other, Index.getValue(1),
  2264. Table, Index);
  2265. DAG.setRoot(BrJumpTable);
  2266. }
  2267. /// visitJumpTableHeader - This function emits necessary code to produce index
  2268. /// in the JumpTable from switch case.
  2269. void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
  2270. JumpTableHeader &JTH,
  2271. MachineBasicBlock *SwitchBB) {
  2272. SDLoc dl = getCurSDLoc();
  2273. // Subtract the lowest switch case value from the value being switched on.
  2274. SDValue SwitchOp = getValue(JTH.SValue);
  2275. EVT VT = SwitchOp.getValueType();
  2276. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
  2277. DAG.getConstant(JTH.First, dl, VT));
  2278. // The SDNode we just created, which holds the value being switched on minus
  2279. // the smallest case value, needs to be copied to a virtual register so it
  2280. // can be used as an index into the jump table in a subsequent basic block.
  2281. // This value may be smaller or larger than the target's pointer type, and
  2282. // therefore require extension or truncating.
  2283. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2284. SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
  2285. unsigned JumpTableReg =
  2286. FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
  2287. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
  2288. JumpTableReg, SwitchOp);
  2289. JT.Reg = JumpTableReg;
  2290. if (!JTH.FallthroughUnreachable) {
  2291. // Emit the range check for the jump table, and branch to the default block
  2292. // for the switch statement if the value being switched on exceeds the
  2293. // largest case in the switch.
  2294. SDValue CMP = DAG.getSetCC(
  2295. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  2296. Sub.getValueType()),
  2297. Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
  2298. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2299. MVT::Other, CopyTo, CMP,
  2300. DAG.getBasicBlock(JT.Default));
  2301. // Avoid emitting unnecessary branches to the next block.
  2302. if (JT.MBB != NextBlock(SwitchBB))
  2303. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  2304. DAG.getBasicBlock(JT.MBB));
  2305. DAG.setRoot(BrCond);
  2306. } else {
  2307. // Avoid emitting unnecessary branches to the next block.
  2308. if (JT.MBB != NextBlock(SwitchBB))
  2309. DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
  2310. DAG.getBasicBlock(JT.MBB)));
  2311. else
  2312. DAG.setRoot(CopyTo);
  2313. }
  2314. }
  2315. /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
  2316. /// variable if there exists one.
  2317. static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
  2318. SDValue &Chain) {
  2319. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2320. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  2321. EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
  2322. MachineFunction &MF = DAG.getMachineFunction();
  2323. Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
  2324. MachineSDNode *Node =
  2325. DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
  2326. if (Global) {
  2327. MachinePointerInfo MPInfo(Global);
  2328. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
  2329. MachineMemOperand::MODereferenceable;
  2330. MachineMemOperand *MemRef = MF.getMachineMemOperand(
  2331. MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
  2332. DAG.setNodeMemRefs(Node, {MemRef});
  2333. }
  2334. if (PtrTy != PtrMemTy)
  2335. return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
  2336. return SDValue(Node, 0);
  2337. }
  2338. /// Codegen a new tail for a stack protector check ParentMBB which has had its
  2339. /// tail spliced into a stack protector check success bb.
  2340. ///
  2341. /// For a high level explanation of how this fits into the stack protector
  2342. /// generation see the comment on the declaration of class
  2343. /// StackProtectorDescriptor.
  2344. void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
  2345. MachineBasicBlock *ParentBB) {
  2346. // First create the loads to the guard/stack slot for the comparison.
  2347. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2348. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  2349. EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
  2350. MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
  2351. int FI = MFI.getStackProtectorIndex();
  2352. SDValue Guard;
  2353. SDLoc dl = getCurSDLoc();
  2354. SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
  2355. const Module &M = *ParentBB->getParent()->getFunction().getParent();
  2356. Align Align =
  2357. DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext()));
  2358. // Generate code to load the content of the guard slot.
  2359. SDValue GuardVal = DAG.getLoad(
  2360. PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
  2361. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
  2362. MachineMemOperand::MOVolatile);
  2363. if (TLI.useStackGuardXorFP())
  2364. GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
  2365. // Retrieve guard check function, nullptr if instrumentation is inlined.
  2366. if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
  2367. // The target provides a guard check function to validate the guard value.
  2368. // Generate a call to that function with the content of the guard slot as
  2369. // argument.
  2370. FunctionType *FnTy = GuardCheckFn->getFunctionType();
  2371. assert(FnTy->getNumParams() == 1 && "Invalid function signature");
  2372. TargetLowering::ArgListTy Args;
  2373. TargetLowering::ArgListEntry Entry;
  2374. Entry.Node = GuardVal;
  2375. Entry.Ty = FnTy->getParamType(0);
  2376. if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
  2377. Entry.IsInReg = true;
  2378. Args.push_back(Entry);
  2379. TargetLowering::CallLoweringInfo CLI(DAG);
  2380. CLI.setDebugLoc(getCurSDLoc())
  2381. .setChain(DAG.getEntryNode())
  2382. .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
  2383. getValue(GuardCheckFn), std::move(Args));
  2384. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  2385. DAG.setRoot(Result.second);
  2386. return;
  2387. }
  2388. // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
  2389. // Otherwise, emit a volatile load to retrieve the stack guard value.
  2390. SDValue Chain = DAG.getEntryNode();
  2391. if (TLI.useLoadStackGuardNode()) {
  2392. Guard = getLoadStackGuard(DAG, dl, Chain);
  2393. } else {
  2394. const Value *IRGuard = TLI.getSDagStackGuard(M);
  2395. SDValue GuardPtr = getValue(IRGuard);
  2396. Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
  2397. MachinePointerInfo(IRGuard, 0), Align,
  2398. MachineMemOperand::MOVolatile);
  2399. }
  2400. // Perform the comparison via a getsetcc.
  2401. SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
  2402. *DAG.getContext(),
  2403. Guard.getValueType()),
  2404. Guard, GuardVal, ISD::SETNE);
  2405. // If the guard/stackslot do not equal, branch to failure MBB.
  2406. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2407. MVT::Other, GuardVal.getOperand(0),
  2408. Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
  2409. // Otherwise branch to success MBB.
  2410. SDValue Br = DAG.getNode(ISD::BR, dl,
  2411. MVT::Other, BrCond,
  2412. DAG.getBasicBlock(SPD.getSuccessMBB()));
  2413. DAG.setRoot(Br);
  2414. }
  2415. /// Codegen the failure basic block for a stack protector check.
  2416. ///
  2417. /// A failure stack protector machine basic block consists simply of a call to
  2418. /// __stack_chk_fail().
  2419. ///
  2420. /// For a high level explanation of how this fits into the stack protector
  2421. /// generation see the comment on the declaration of class
  2422. /// StackProtectorDescriptor.
  2423. void
  2424. SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
  2425. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2426. TargetLowering::MakeLibCallOptions CallOptions;
  2427. CallOptions.setDiscardResult(true);
  2428. SDValue Chain =
  2429. TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
  2430. None, CallOptions, getCurSDLoc()).second;
  2431. // On PS4, the "return address" must still be within the calling function,
  2432. // even if it's at the very end, so emit an explicit TRAP here.
  2433. // Passing 'true' for doesNotReturn above won't generate the trap for us.
  2434. if (TM.getTargetTriple().isPS4CPU())
  2435. Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
  2436. // WebAssembly needs an unreachable instruction after a non-returning call,
  2437. // because the function return type can be different from __stack_chk_fail's
  2438. // return type (void).
  2439. if (TM.getTargetTriple().isWasm())
  2440. Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
  2441. DAG.setRoot(Chain);
  2442. }
  2443. /// visitBitTestHeader - This function emits necessary code to produce value
  2444. /// suitable for "bit tests"
  2445. void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
  2446. MachineBasicBlock *SwitchBB) {
  2447. SDLoc dl = getCurSDLoc();
  2448. // Subtract the minimum value.
  2449. SDValue SwitchOp = getValue(B.SValue);
  2450. EVT VT = SwitchOp.getValueType();
  2451. SDValue RangeSub =
  2452. DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
  2453. // Determine the type of the test operands.
  2454. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2455. bool UsePtrType = false;
  2456. if (!TLI.isTypeLegal(VT)) {
  2457. UsePtrType = true;
  2458. } else {
  2459. for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
  2460. if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
  2461. // Switch table case range are encoded into series of masks.
  2462. // Just use pointer type, it's guaranteed to fit.
  2463. UsePtrType = true;
  2464. break;
  2465. }
  2466. }
  2467. SDValue Sub = RangeSub;
  2468. if (UsePtrType) {
  2469. VT = TLI.getPointerTy(DAG.getDataLayout());
  2470. Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
  2471. }
  2472. B.RegVT = VT.getSimpleVT();
  2473. B.Reg = FuncInfo.CreateReg(B.RegVT);
  2474. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
  2475. MachineBasicBlock* MBB = B.Cases[0].ThisBB;
  2476. if (!B.FallthroughUnreachable)
  2477. addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
  2478. addSuccessorWithProb(SwitchBB, MBB, B.Prob);
  2479. SwitchBB->normalizeSuccProbs();
  2480. SDValue Root = CopyTo;
  2481. if (!B.FallthroughUnreachable) {
  2482. // Conditional branch to the default block.
  2483. SDValue RangeCmp = DAG.getSetCC(dl,
  2484. TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  2485. RangeSub.getValueType()),
  2486. RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
  2487. ISD::SETUGT);
  2488. Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
  2489. DAG.getBasicBlock(B.Default));
  2490. }
  2491. // Avoid emitting unnecessary branches to the next block.
  2492. if (MBB != NextBlock(SwitchBB))
  2493. Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
  2494. DAG.setRoot(Root);
  2495. }
  2496. /// visitBitTestCase - this function produces one "bit test"
  2497. void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
  2498. MachineBasicBlock* NextMBB,
  2499. BranchProbability BranchProbToNext,
  2500. unsigned Reg,
  2501. BitTestCase &B,
  2502. MachineBasicBlock *SwitchBB) {
  2503. SDLoc dl = getCurSDLoc();
  2504. MVT VT = BB.RegVT;
  2505. SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
  2506. SDValue Cmp;
  2507. unsigned PopCount = countPopulation(B.Mask);
  2508. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2509. if (PopCount == 1) {
  2510. // Testing for a single bit; just compare the shift count with what it
  2511. // would need to be to shift a 1 bit in that position.
  2512. Cmp = DAG.getSetCC(
  2513. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2514. ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
  2515. ISD::SETEQ);
  2516. } else if (PopCount == BB.Range) {
  2517. // There is only one zero bit in the range, test for it directly.
  2518. Cmp = DAG.getSetCC(
  2519. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2520. ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
  2521. ISD::SETNE);
  2522. } else {
  2523. // Make desired shift
  2524. SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
  2525. DAG.getConstant(1, dl, VT), ShiftOp);
  2526. // Emit bit tests and jumps
  2527. SDValue AndOp = DAG.getNode(ISD::AND, dl,
  2528. VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
  2529. Cmp = DAG.getSetCC(
  2530. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2531. AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
  2532. }
  2533. // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
  2534. addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
  2535. // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
  2536. addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
  2537. // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
  2538. // one as they are relative probabilities (and thus work more like weights),
  2539. // and hence we need to normalize them to let the sum of them become one.
  2540. SwitchBB->normalizeSuccProbs();
  2541. SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
  2542. MVT::Other, getControlRoot(),
  2543. Cmp, DAG.getBasicBlock(B.TargetBB));
  2544. // Avoid emitting unnecessary branches to the next block.
  2545. if (NextMBB != NextBlock(SwitchBB))
  2546. BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
  2547. DAG.getBasicBlock(NextMBB));
  2548. DAG.setRoot(BrAnd);
  2549. }
  2550. void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
  2551. MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
  2552. // Retrieve successors. Look through artificial IR level blocks like
  2553. // catchswitch for successors.
  2554. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
  2555. const BasicBlock *EHPadBB = I.getSuccessor(1);
  2556. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  2557. // have to do anything here to lower funclet bundles.
  2558. assert(!I.hasOperandBundlesOtherThan(
  2559. {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
  2560. LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
  2561. LLVMContext::OB_cfguardtarget,
  2562. LLVMContext::OB_clang_arc_attachedcall}) &&
  2563. "Cannot lower invokes with arbitrary operand bundles yet!");
  2564. const Value *Callee(I.getCalledOperand());
  2565. const Function *Fn = dyn_cast<Function>(Callee);
  2566. if (isa<InlineAsm>(Callee))
  2567. visitInlineAsm(I, EHPadBB);
  2568. else if (Fn && Fn->isIntrinsic()) {
  2569. switch (Fn->getIntrinsicID()) {
  2570. default:
  2571. llvm_unreachable("Cannot invoke this intrinsic");
  2572. case Intrinsic::donothing:
  2573. // Ignore invokes to @llvm.donothing: jump directly to the next BB.
  2574. case Intrinsic::seh_try_begin:
  2575. case Intrinsic::seh_scope_begin:
  2576. case Intrinsic::seh_try_end:
  2577. case Intrinsic::seh_scope_end:
  2578. break;
  2579. case Intrinsic::experimental_patchpoint_void:
  2580. case Intrinsic::experimental_patchpoint_i64:
  2581. visitPatchpoint(I, EHPadBB);
  2582. break;
  2583. case Intrinsic::experimental_gc_statepoint:
  2584. LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
  2585. break;
  2586. case Intrinsic::wasm_rethrow: {
  2587. // This is usually done in visitTargetIntrinsic, but this intrinsic is
  2588. // special because it can be invoked, so we manually lower it to a DAG
  2589. // node here.
  2590. SmallVector<SDValue, 8> Ops;
  2591. Ops.push_back(getRoot()); // inchain
  2592. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2593. Ops.push_back(
  2594. DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
  2595. TLI.getPointerTy(DAG.getDataLayout())));
  2596. SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
  2597. DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
  2598. break;
  2599. }
  2600. }
  2601. } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
  2602. // Currently we do not lower any intrinsic calls with deopt operand bundles.
  2603. // Eventually we will support lowering the @llvm.experimental.deoptimize
  2604. // intrinsic, and right now there are no plans to support other intrinsics
  2605. // with deopt state.
  2606. LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
  2607. } else {
  2608. LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
  2609. }
  2610. // If the value of the invoke is used outside of its defining block, make it
  2611. // available as a virtual register.
  2612. // We already took care of the exported value for the statepoint instruction
  2613. // during call to the LowerStatepoint.
  2614. if (!isa<GCStatepointInst>(I)) {
  2615. CopyToExportRegsIfNeeded(&I);
  2616. }
  2617. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  2618. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  2619. BranchProbability EHPadBBProb =
  2620. BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
  2621. : BranchProbability::getZero();
  2622. findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
  2623. // Update successor info.
  2624. addSuccessorWithProb(InvokeMBB, Return);
  2625. for (auto &UnwindDest : UnwindDests) {
  2626. UnwindDest.first->setIsEHPad();
  2627. addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
  2628. }
  2629. InvokeMBB->normalizeSuccProbs();
  2630. // Drop into normal successor.
  2631. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
  2632. DAG.getBasicBlock(Return)));
  2633. }
  2634. void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
  2635. MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
  2636. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  2637. // have to do anything here to lower funclet bundles.
  2638. assert(!I.hasOperandBundlesOtherThan(
  2639. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  2640. "Cannot lower callbrs with arbitrary operand bundles yet!");
  2641. assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
  2642. visitInlineAsm(I);
  2643. CopyToExportRegsIfNeeded(&I);
  2644. // Retrieve successors.
  2645. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
  2646. // Update successor info.
  2647. addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
  2648. for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
  2649. MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
  2650. addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
  2651. Target->setIsInlineAsmBrIndirectTarget();
  2652. }
  2653. CallBrMBB->normalizeSuccProbs();
  2654. // Drop into default successor.
  2655. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  2656. MVT::Other, getControlRoot(),
  2657. DAG.getBasicBlock(Return)));
  2658. }
  2659. void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
  2660. llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
  2661. }
  2662. void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
  2663. assert(FuncInfo.MBB->isEHPad() &&
  2664. "Call to landingpad not in landing pad!");
  2665. // If there aren't registers to copy the values into (e.g., during SjLj
  2666. // exceptions), then don't bother to create these DAG nodes.
  2667. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2668. const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
  2669. if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
  2670. TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
  2671. return;
  2672. // If landingpad's return type is token type, we don't create DAG nodes
  2673. // for its exception pointer and selector value. The extraction of exception
  2674. // pointer or selector value from token type landingpads is not currently
  2675. // supported.
  2676. if (LP.getType()->isTokenTy())
  2677. return;
  2678. SmallVector<EVT, 2> ValueVTs;
  2679. SDLoc dl = getCurSDLoc();
  2680. ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
  2681. assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
  2682. // Get the two live-in registers as SDValues. The physregs have already been
  2683. // copied into virtual registers.
  2684. SDValue Ops[2];
  2685. if (FuncInfo.ExceptionPointerVirtReg) {
  2686. Ops[0] = DAG.getZExtOrTrunc(
  2687. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2688. FuncInfo.ExceptionPointerVirtReg,
  2689. TLI.getPointerTy(DAG.getDataLayout())),
  2690. dl, ValueVTs[0]);
  2691. } else {
  2692. Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
  2693. }
  2694. Ops[1] = DAG.getZExtOrTrunc(
  2695. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2696. FuncInfo.ExceptionSelectorVirtReg,
  2697. TLI.getPointerTy(DAG.getDataLayout())),
  2698. dl, ValueVTs[1]);
  2699. // Merge into one.
  2700. SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
  2701. DAG.getVTList(ValueVTs), Ops);
  2702. setValue(&LP, Res);
  2703. }
  2704. void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
  2705. MachineBasicBlock *Last) {
  2706. // Update JTCases.
  2707. for (JumpTableBlock &JTB : SL->JTCases)
  2708. if (JTB.first.HeaderBB == First)
  2709. JTB.first.HeaderBB = Last;
  2710. // Update BitTestCases.
  2711. for (BitTestBlock &BTB : SL->BitTestCases)
  2712. if (BTB.Parent == First)
  2713. BTB.Parent = Last;
  2714. }
  2715. void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
  2716. MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
  2717. // Update machine-CFG edges with unique successors.
  2718. SmallSet<BasicBlock*, 32> Done;
  2719. for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
  2720. BasicBlock *BB = I.getSuccessor(i);
  2721. bool Inserted = Done.insert(BB).second;
  2722. if (!Inserted)
  2723. continue;
  2724. MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
  2725. addSuccessorWithProb(IndirectBrMBB, Succ);
  2726. }
  2727. IndirectBrMBB->normalizeSuccProbs();
  2728. DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
  2729. MVT::Other, getControlRoot(),
  2730. getValue(I.getAddress())));
  2731. }
  2732. void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
  2733. if (!DAG.getTarget().Options.TrapUnreachable)
  2734. return;
  2735. // We may be able to ignore unreachable behind a noreturn call.
  2736. if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
  2737. const BasicBlock &BB = *I.getParent();
  2738. if (&I != &BB.front()) {
  2739. BasicBlock::const_iterator PredI =
  2740. std::prev(BasicBlock::const_iterator(&I));
  2741. if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
  2742. if (Call->doesNotReturn())
  2743. return;
  2744. }
  2745. }
  2746. }
  2747. DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
  2748. }
  2749. void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
  2750. SDNodeFlags Flags;
  2751. if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
  2752. Flags.copyFMF(*FPOp);
  2753. SDValue Op = getValue(I.getOperand(0));
  2754. SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
  2755. Op, Flags);
  2756. setValue(&I, UnNodeValue);
  2757. }
  2758. void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
  2759. SDNodeFlags Flags;
  2760. if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
  2761. Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
  2762. Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
  2763. }
  2764. if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
  2765. Flags.setExact(ExactOp->isExact());
  2766. if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
  2767. Flags.copyFMF(*FPOp);
  2768. SDValue Op1 = getValue(I.getOperand(0));
  2769. SDValue Op2 = getValue(I.getOperand(1));
  2770. SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
  2771. Op1, Op2, Flags);
  2772. setValue(&I, BinNodeValue);
  2773. }
  2774. void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
  2775. SDValue Op1 = getValue(I.getOperand(0));
  2776. SDValue Op2 = getValue(I.getOperand(1));
  2777. EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
  2778. Op1.getValueType(), DAG.getDataLayout());
  2779. // Coerce the shift amount to the right type if we can.
  2780. if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
  2781. unsigned ShiftSize = ShiftTy.getSizeInBits();
  2782. unsigned Op2Size = Op2.getValueSizeInBits();
  2783. SDLoc DL = getCurSDLoc();
  2784. // If the operand is smaller than the shift count type, promote it.
  2785. if (ShiftSize > Op2Size)
  2786. Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
  2787. // If the operand is larger than the shift count type but the shift
  2788. // count type has enough bits to represent any shift value, truncate
  2789. // it now. This is a common case and it exposes the truncate to
  2790. // optimization early.
  2791. else if (ShiftSize >= Log2_32_Ceil(Op1.getValueSizeInBits()))
  2792. Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
  2793. // Otherwise we'll need to temporarily settle for some other convenient
  2794. // type. Type legalization will make adjustments once the shiftee is split.
  2795. else
  2796. Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
  2797. }
  2798. bool nuw = false;
  2799. bool nsw = false;
  2800. bool exact = false;
  2801. if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
  2802. if (const OverflowingBinaryOperator *OFBinOp =
  2803. dyn_cast<const OverflowingBinaryOperator>(&I)) {
  2804. nuw = OFBinOp->hasNoUnsignedWrap();
  2805. nsw = OFBinOp->hasNoSignedWrap();
  2806. }
  2807. if (const PossiblyExactOperator *ExactOp =
  2808. dyn_cast<const PossiblyExactOperator>(&I))
  2809. exact = ExactOp->isExact();
  2810. }
  2811. SDNodeFlags Flags;
  2812. Flags.setExact(exact);
  2813. Flags.setNoSignedWrap(nsw);
  2814. Flags.setNoUnsignedWrap(nuw);
  2815. SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
  2816. Flags);
  2817. setValue(&I, Res);
  2818. }
  2819. void SelectionDAGBuilder::visitSDiv(const User &I) {
  2820. SDValue Op1 = getValue(I.getOperand(0));
  2821. SDValue Op2 = getValue(I.getOperand(1));
  2822. SDNodeFlags Flags;
  2823. Flags.setExact(isa<PossiblyExactOperator>(&I) &&
  2824. cast<PossiblyExactOperator>(&I)->isExact());
  2825. setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
  2826. Op2, Flags));
  2827. }
  2828. void SelectionDAGBuilder::visitICmp(const User &I) {
  2829. ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
  2830. if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
  2831. predicate = IC->getPredicate();
  2832. else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
  2833. predicate = ICmpInst::Predicate(IC->getPredicate());
  2834. SDValue Op1 = getValue(I.getOperand(0));
  2835. SDValue Op2 = getValue(I.getOperand(1));
  2836. ISD::CondCode Opcode = getICmpCondCode(predicate);
  2837. auto &TLI = DAG.getTargetLoweringInfo();
  2838. EVT MemVT =
  2839. TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
  2840. // If a pointer's DAG type is larger than its memory type then the DAG values
  2841. // are zero-extended. This breaks signed comparisons so truncate back to the
  2842. // underlying type before doing the compare.
  2843. if (Op1.getValueType() != MemVT) {
  2844. Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
  2845. Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
  2846. }
  2847. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2848. I.getType());
  2849. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
  2850. }
  2851. void SelectionDAGBuilder::visitFCmp(const User &I) {
  2852. FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
  2853. if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
  2854. predicate = FC->getPredicate();
  2855. else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
  2856. predicate = FCmpInst::Predicate(FC->getPredicate());
  2857. SDValue Op1 = getValue(I.getOperand(0));
  2858. SDValue Op2 = getValue(I.getOperand(1));
  2859. ISD::CondCode Condition = getFCmpCondCode(predicate);
  2860. auto *FPMO = cast<FPMathOperator>(&I);
  2861. if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
  2862. Condition = getFCmpCodeWithoutNaN(Condition);
  2863. SDNodeFlags Flags;
  2864. Flags.copyFMF(*FPMO);
  2865. SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
  2866. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2867. I.getType());
  2868. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
  2869. }
  2870. // Check if the condition of the select has one use or two users that are both
  2871. // selects with the same condition.
  2872. static bool hasOnlySelectUsers(const Value *Cond) {
  2873. return llvm::all_of(Cond->users(), [](const Value *V) {
  2874. return isa<SelectInst>(V);
  2875. });
  2876. }
  2877. void SelectionDAGBuilder::visitSelect(const User &I) {
  2878. SmallVector<EVT, 4> ValueVTs;
  2879. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
  2880. ValueVTs);
  2881. unsigned NumValues = ValueVTs.size();
  2882. if (NumValues == 0) return;
  2883. SmallVector<SDValue, 4> Values(NumValues);
  2884. SDValue Cond = getValue(I.getOperand(0));
  2885. SDValue LHSVal = getValue(I.getOperand(1));
  2886. SDValue RHSVal = getValue(I.getOperand(2));
  2887. SmallVector<SDValue, 1> BaseOps(1, Cond);
  2888. ISD::NodeType OpCode =
  2889. Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
  2890. bool IsUnaryAbs = false;
  2891. bool Negate = false;
  2892. SDNodeFlags Flags;
  2893. if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
  2894. Flags.copyFMF(*FPOp);
  2895. // Min/max matching is only viable if all output VTs are the same.
  2896. if (is_splat(ValueVTs)) {
  2897. EVT VT = ValueVTs[0];
  2898. LLVMContext &Ctx = *DAG.getContext();
  2899. auto &TLI = DAG.getTargetLoweringInfo();
  2900. // We care about the legality of the operation after it has been type
  2901. // legalized.
  2902. while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
  2903. VT = TLI.getTypeToTransformTo(Ctx, VT);
  2904. // If the vselect is legal, assume we want to leave this as a vector setcc +
  2905. // vselect. Otherwise, if this is going to be scalarized, we want to see if
  2906. // min/max is legal on the scalar type.
  2907. bool UseScalarMinMax = VT.isVector() &&
  2908. !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
  2909. Value *LHS, *RHS;
  2910. auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
  2911. ISD::NodeType Opc = ISD::DELETED_NODE;
  2912. switch (SPR.Flavor) {
  2913. case SPF_UMAX: Opc = ISD::UMAX; break;
  2914. case SPF_UMIN: Opc = ISD::UMIN; break;
  2915. case SPF_SMAX: Opc = ISD::SMAX; break;
  2916. case SPF_SMIN: Opc = ISD::SMIN; break;
  2917. case SPF_FMINNUM:
  2918. switch (SPR.NaNBehavior) {
  2919. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2920. case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break;
  2921. case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
  2922. case SPNB_RETURNS_ANY: {
  2923. if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
  2924. Opc = ISD::FMINNUM;
  2925. else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
  2926. Opc = ISD::FMINIMUM;
  2927. else if (UseScalarMinMax)
  2928. Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
  2929. ISD::FMINNUM : ISD::FMINIMUM;
  2930. break;
  2931. }
  2932. }
  2933. break;
  2934. case SPF_FMAXNUM:
  2935. switch (SPR.NaNBehavior) {
  2936. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2937. case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break;
  2938. case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
  2939. case SPNB_RETURNS_ANY:
  2940. if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
  2941. Opc = ISD::FMAXNUM;
  2942. else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
  2943. Opc = ISD::FMAXIMUM;
  2944. else if (UseScalarMinMax)
  2945. Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
  2946. ISD::FMAXNUM : ISD::FMAXIMUM;
  2947. break;
  2948. }
  2949. break;
  2950. case SPF_NABS:
  2951. Negate = true;
  2952. LLVM_FALLTHROUGH;
  2953. case SPF_ABS:
  2954. IsUnaryAbs = true;
  2955. Opc = ISD::ABS;
  2956. break;
  2957. default: break;
  2958. }
  2959. if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
  2960. (TLI.isOperationLegalOrCustom(Opc, VT) ||
  2961. (UseScalarMinMax &&
  2962. TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
  2963. // If the underlying comparison instruction is used by any other
  2964. // instruction, the consumed instructions won't be destroyed, so it is
  2965. // not profitable to convert to a min/max.
  2966. hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
  2967. OpCode = Opc;
  2968. LHSVal = getValue(LHS);
  2969. RHSVal = getValue(RHS);
  2970. BaseOps.clear();
  2971. }
  2972. if (IsUnaryAbs) {
  2973. OpCode = Opc;
  2974. LHSVal = getValue(LHS);
  2975. BaseOps.clear();
  2976. }
  2977. }
  2978. if (IsUnaryAbs) {
  2979. for (unsigned i = 0; i != NumValues; ++i) {
  2980. SDLoc dl = getCurSDLoc();
  2981. EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
  2982. Values[i] =
  2983. DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
  2984. if (Negate)
  2985. Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT),
  2986. Values[i]);
  2987. }
  2988. } else {
  2989. for (unsigned i = 0; i != NumValues; ++i) {
  2990. SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
  2991. Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
  2992. Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
  2993. Values[i] = DAG.getNode(
  2994. OpCode, getCurSDLoc(),
  2995. LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
  2996. }
  2997. }
  2998. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2999. DAG.getVTList(ValueVTs), Values));
  3000. }
  3001. void SelectionDAGBuilder::visitTrunc(const User &I) {
  3002. // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
  3003. SDValue N = getValue(I.getOperand(0));
  3004. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3005. I.getType());
  3006. setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
  3007. }
  3008. void SelectionDAGBuilder::visitZExt(const User &I) {
  3009. // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  3010. // ZExt also can't be a cast to bool for same reason. So, nothing much to do
  3011. SDValue N = getValue(I.getOperand(0));
  3012. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3013. I.getType());
  3014. setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
  3015. }
  3016. void SelectionDAGBuilder::visitSExt(const User &I) {
  3017. // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  3018. // SExt also can't be a cast to bool for same reason. So, nothing much to do
  3019. SDValue N = getValue(I.getOperand(0));
  3020. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3021. I.getType());
  3022. setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
  3023. }
  3024. void SelectionDAGBuilder::visitFPTrunc(const User &I) {
  3025. // FPTrunc is never a no-op cast, no need to check
  3026. SDValue N = getValue(I.getOperand(0));
  3027. SDLoc dl = getCurSDLoc();
  3028. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3029. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3030. setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
  3031. DAG.getTargetConstant(
  3032. 0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
  3033. }
  3034. void SelectionDAGBuilder::visitFPExt(const User &I) {
  3035. // FPExt is never a no-op cast, no need to check
  3036. SDValue N = getValue(I.getOperand(0));
  3037. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3038. I.getType());
  3039. setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
  3040. }
  3041. void SelectionDAGBuilder::visitFPToUI(const User &I) {
  3042. // FPToUI is never a no-op cast, no need to check
  3043. SDValue N = getValue(I.getOperand(0));
  3044. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3045. I.getType());
  3046. setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
  3047. }
  3048. void SelectionDAGBuilder::visitFPToSI(const User &I) {
  3049. // FPToSI is never a no-op cast, no need to check
  3050. SDValue N = getValue(I.getOperand(0));
  3051. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3052. I.getType());
  3053. setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
  3054. }
  3055. void SelectionDAGBuilder::visitUIToFP(const User &I) {
  3056. // UIToFP is never a no-op cast, no need to check
  3057. SDValue N = getValue(I.getOperand(0));
  3058. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3059. I.getType());
  3060. setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
  3061. }
  3062. void SelectionDAGBuilder::visitSIToFP(const User &I) {
  3063. // SIToFP is never a no-op cast, no need to check
  3064. SDValue N = getValue(I.getOperand(0));
  3065. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3066. I.getType());
  3067. setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
  3068. }
  3069. void SelectionDAGBuilder::visitPtrToInt(const User &I) {
  3070. // What to do depends on the size of the integer and the size of the pointer.
  3071. // We can either truncate, zero extend, or no-op, accordingly.
  3072. SDValue N = getValue(I.getOperand(0));
  3073. auto &TLI = DAG.getTargetLoweringInfo();
  3074. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3075. I.getType());
  3076. EVT PtrMemVT =
  3077. TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
  3078. N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
  3079. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
  3080. setValue(&I, N);
  3081. }
  3082. void SelectionDAGBuilder::visitIntToPtr(const User &I) {
  3083. // What to do depends on the size of the integer and the size of the pointer.
  3084. // We can either truncate, zero extend, or no-op, accordingly.
  3085. SDValue N = getValue(I.getOperand(0));
  3086. auto &TLI = DAG.getTargetLoweringInfo();
  3087. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3088. EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
  3089. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
  3090. N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
  3091. setValue(&I, N);
  3092. }
  3093. void SelectionDAGBuilder::visitBitCast(const User &I) {
  3094. SDValue N = getValue(I.getOperand(0));
  3095. SDLoc dl = getCurSDLoc();
  3096. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3097. I.getType());
  3098. // BitCast assures us that source and destination are the same size so this is
  3099. // either a BITCAST or a no-op.
  3100. if (DestVT != N.getValueType())
  3101. setValue(&I, DAG.getNode(ISD::BITCAST, dl,
  3102. DestVT, N)); // convert types.
  3103. // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
  3104. // might fold any kind of constant expression to an integer constant and that
  3105. // is not what we are looking for. Only recognize a bitcast of a genuine
  3106. // constant integer as an opaque constant.
  3107. else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
  3108. setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
  3109. /*isOpaque*/true));
  3110. else
  3111. setValue(&I, N); // noop cast.
  3112. }
  3113. void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
  3114. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3115. const Value *SV = I.getOperand(0);
  3116. SDValue N = getValue(SV);
  3117. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3118. unsigned SrcAS = SV->getType()->getPointerAddressSpace();
  3119. unsigned DestAS = I.getType()->getPointerAddressSpace();
  3120. if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
  3121. N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
  3122. setValue(&I, N);
  3123. }
  3124. void SelectionDAGBuilder::visitInsertElement(const User &I) {
  3125. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3126. SDValue InVec = getValue(I.getOperand(0));
  3127. SDValue InVal = getValue(I.getOperand(1));
  3128. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
  3129. TLI.getVectorIdxTy(DAG.getDataLayout()));
  3130. setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
  3131. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  3132. InVec, InVal, InIdx));
  3133. }
  3134. void SelectionDAGBuilder::visitExtractElement(const User &I) {
  3135. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3136. SDValue InVec = getValue(I.getOperand(0));
  3137. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
  3138. TLI.getVectorIdxTy(DAG.getDataLayout()));
  3139. setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
  3140. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  3141. InVec, InIdx));
  3142. }
  3143. void SelectionDAGBuilder::visitShuffleVector(const User &I) {
  3144. SDValue Src1 = getValue(I.getOperand(0));
  3145. SDValue Src2 = getValue(I.getOperand(1));
  3146. ArrayRef<int> Mask;
  3147. if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
  3148. Mask = SVI->getShuffleMask();
  3149. else
  3150. Mask = cast<ConstantExpr>(I).getShuffleMask();
  3151. SDLoc DL = getCurSDLoc();
  3152. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3153. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3154. EVT SrcVT = Src1.getValueType();
  3155. if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
  3156. VT.isScalableVector()) {
  3157. // Canonical splat form of first element of first input vector.
  3158. SDValue FirstElt =
  3159. DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
  3160. DAG.getVectorIdxConstant(0, DL));
  3161. setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
  3162. return;
  3163. }
  3164. // For now, we only handle splats for scalable vectors.
  3165. // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
  3166. // for targets that support a SPLAT_VECTOR for non-scalable vector types.
  3167. assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
  3168. unsigned SrcNumElts = SrcVT.getVectorNumElements();
  3169. unsigned MaskNumElts = Mask.size();
  3170. if (SrcNumElts == MaskNumElts) {
  3171. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
  3172. return;
  3173. }
  3174. // Normalize the shuffle vector since mask and vector length don't match.
  3175. if (SrcNumElts < MaskNumElts) {
  3176. // Mask is longer than the source vectors. We can use concatenate vector to
  3177. // make the mask and vectors lengths match.
  3178. if (MaskNumElts % SrcNumElts == 0) {
  3179. // Mask length is a multiple of the source vector length.
  3180. // Check if the shuffle is some kind of concatenation of the input
  3181. // vectors.
  3182. unsigned NumConcat = MaskNumElts / SrcNumElts;
  3183. bool IsConcat = true;
  3184. SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
  3185. for (unsigned i = 0; i != MaskNumElts; ++i) {
  3186. int Idx = Mask[i];
  3187. if (Idx < 0)
  3188. continue;
  3189. // Ensure the indices in each SrcVT sized piece are sequential and that
  3190. // the same source is used for the whole piece.
  3191. if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
  3192. (ConcatSrcs[i / SrcNumElts] >= 0 &&
  3193. ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
  3194. IsConcat = false;
  3195. break;
  3196. }
  3197. // Remember which source this index came from.
  3198. ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
  3199. }
  3200. // The shuffle is concatenating multiple vectors together. Just emit
  3201. // a CONCAT_VECTORS operation.
  3202. if (IsConcat) {
  3203. SmallVector<SDValue, 8> ConcatOps;
  3204. for (auto Src : ConcatSrcs) {
  3205. if (Src < 0)
  3206. ConcatOps.push_back(DAG.getUNDEF(SrcVT));
  3207. else if (Src == 0)
  3208. ConcatOps.push_back(Src1);
  3209. else
  3210. ConcatOps.push_back(Src2);
  3211. }
  3212. setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
  3213. return;
  3214. }
  3215. }
  3216. unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
  3217. unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
  3218. EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
  3219. PaddedMaskNumElts);
  3220. // Pad both vectors with undefs to make them the same length as the mask.
  3221. SDValue UndefVal = DAG.getUNDEF(SrcVT);
  3222. SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
  3223. SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
  3224. MOps1[0] = Src1;
  3225. MOps2[0] = Src2;
  3226. Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
  3227. Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
  3228. // Readjust mask for new input vector length.
  3229. SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
  3230. for (unsigned i = 0; i != MaskNumElts; ++i) {
  3231. int Idx = Mask[i];
  3232. if (Idx >= (int)SrcNumElts)
  3233. Idx -= SrcNumElts - PaddedMaskNumElts;
  3234. MappedOps[i] = Idx;
  3235. }
  3236. SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
  3237. // If the concatenated vector was padded, extract a subvector with the
  3238. // correct number of elements.
  3239. if (MaskNumElts != PaddedMaskNumElts)
  3240. Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
  3241. DAG.getVectorIdxConstant(0, DL));
  3242. setValue(&I, Result);
  3243. return;
  3244. }
  3245. if (SrcNumElts > MaskNumElts) {
  3246. // Analyze the access pattern of the vector to see if we can extract
  3247. // two subvectors and do the shuffle.
  3248. int StartIdx[2] = { -1, -1 }; // StartIdx to extract from
  3249. bool CanExtract = true;
  3250. for (int Idx : Mask) {
  3251. unsigned Input = 0;
  3252. if (Idx < 0)
  3253. continue;
  3254. if (Idx >= (int)SrcNumElts) {
  3255. Input = 1;
  3256. Idx -= SrcNumElts;
  3257. }
  3258. // If all the indices come from the same MaskNumElts sized portion of
  3259. // the sources we can use extract. Also make sure the extract wouldn't
  3260. // extract past the end of the source.
  3261. int NewStartIdx = alignDown(Idx, MaskNumElts);
  3262. if (NewStartIdx + MaskNumElts > SrcNumElts ||
  3263. (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
  3264. CanExtract = false;
  3265. // Make sure we always update StartIdx as we use it to track if all
  3266. // elements are undef.
  3267. StartIdx[Input] = NewStartIdx;
  3268. }
  3269. if (StartIdx[0] < 0 && StartIdx[1] < 0) {
  3270. setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
  3271. return;
  3272. }
  3273. if (CanExtract) {
  3274. // Extract appropriate subvector and generate a vector shuffle
  3275. for (unsigned Input = 0; Input < 2; ++Input) {
  3276. SDValue &Src = Input == 0 ? Src1 : Src2;
  3277. if (StartIdx[Input] < 0)
  3278. Src = DAG.getUNDEF(VT);
  3279. else {
  3280. Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
  3281. DAG.getVectorIdxConstant(StartIdx[Input], DL));
  3282. }
  3283. }
  3284. // Calculate new mask.
  3285. SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
  3286. for (int &Idx : MappedOps) {
  3287. if (Idx >= (int)SrcNumElts)
  3288. Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
  3289. else if (Idx >= 0)
  3290. Idx -= StartIdx[0];
  3291. }
  3292. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
  3293. return;
  3294. }
  3295. }
  3296. // We can't use either concat vectors or extract subvectors so fall back to
  3297. // replacing the shuffle with extract and build vector.
  3298. // to insert and build vector.
  3299. EVT EltVT = VT.getVectorElementType();
  3300. SmallVector<SDValue,8> Ops;
  3301. for (int Idx : Mask) {
  3302. SDValue Res;
  3303. if (Idx < 0) {
  3304. Res = DAG.getUNDEF(EltVT);
  3305. } else {
  3306. SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
  3307. if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
  3308. Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
  3309. DAG.getVectorIdxConstant(Idx, DL));
  3310. }
  3311. Ops.push_back(Res);
  3312. }
  3313. setValue(&I, DAG.getBuildVector(VT, DL, Ops));
  3314. }
  3315. void SelectionDAGBuilder::visitInsertValue(const User &I) {
  3316. ArrayRef<unsigned> Indices;
  3317. if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
  3318. Indices = IV->getIndices();
  3319. else
  3320. Indices = cast<ConstantExpr>(&I)->getIndices();
  3321. const Value *Op0 = I.getOperand(0);
  3322. const Value *Op1 = I.getOperand(1);
  3323. Type *AggTy = I.getType();
  3324. Type *ValTy = Op1->getType();
  3325. bool IntoUndef = isa<UndefValue>(Op0);
  3326. bool FromUndef = isa<UndefValue>(Op1);
  3327. unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
  3328. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3329. SmallVector<EVT, 4> AggValueVTs;
  3330. ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
  3331. SmallVector<EVT, 4> ValValueVTs;
  3332. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  3333. unsigned NumAggValues = AggValueVTs.size();
  3334. unsigned NumValValues = ValValueVTs.size();
  3335. SmallVector<SDValue, 4> Values(NumAggValues);
  3336. // Ignore an insertvalue that produces an empty object
  3337. if (!NumAggValues) {
  3338. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  3339. return;
  3340. }
  3341. SDValue Agg = getValue(Op0);
  3342. unsigned i = 0;
  3343. // Copy the beginning value(s) from the original aggregate.
  3344. for (; i != LinearIndex; ++i)
  3345. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3346. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3347. // Copy values from the inserted value(s).
  3348. if (NumValValues) {
  3349. SDValue Val = getValue(Op1);
  3350. for (; i != LinearIndex + NumValValues; ++i)
  3351. Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3352. SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
  3353. }
  3354. // Copy remaining value(s) from the original aggregate.
  3355. for (; i != NumAggValues; ++i)
  3356. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3357. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3358. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  3359. DAG.getVTList(AggValueVTs), Values));
  3360. }
  3361. void SelectionDAGBuilder::visitExtractValue(const User &I) {
  3362. ArrayRef<unsigned> Indices;
  3363. if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
  3364. Indices = EV->getIndices();
  3365. else
  3366. Indices = cast<ConstantExpr>(&I)->getIndices();
  3367. const Value *Op0 = I.getOperand(0);
  3368. Type *AggTy = Op0->getType();
  3369. Type *ValTy = I.getType();
  3370. bool OutOfUndef = isa<UndefValue>(Op0);
  3371. unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
  3372. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3373. SmallVector<EVT, 4> ValValueVTs;
  3374. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  3375. unsigned NumValValues = ValValueVTs.size();
  3376. // Ignore a extractvalue that produces an empty object
  3377. if (!NumValValues) {
  3378. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  3379. return;
  3380. }
  3381. SmallVector<SDValue, 4> Values(NumValValues);
  3382. SDValue Agg = getValue(Op0);
  3383. // Copy out the selected value(s).
  3384. for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
  3385. Values[i - LinearIndex] =
  3386. OutOfUndef ?
  3387. DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
  3388. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3389. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  3390. DAG.getVTList(ValValueVTs), Values));
  3391. }
  3392. void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
  3393. Value *Op0 = I.getOperand(0);
  3394. // Note that the pointer operand may be a vector of pointers. Take the scalar
  3395. // element which holds a pointer.
  3396. unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
  3397. SDValue N = getValue(Op0);
  3398. SDLoc dl = getCurSDLoc();
  3399. auto &TLI = DAG.getTargetLoweringInfo();
  3400. // Normalize Vector GEP - all scalar operands should be converted to the
  3401. // splat vector.
  3402. bool IsVectorGEP = I.getType()->isVectorTy();
  3403. ElementCount VectorElementCount =
  3404. IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
  3405. : ElementCount::getFixed(0);
  3406. if (IsVectorGEP && !N.getValueType().isVector()) {
  3407. LLVMContext &Context = *DAG.getContext();
  3408. EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
  3409. if (VectorElementCount.isScalable())
  3410. N = DAG.getSplatVector(VT, dl, N);
  3411. else
  3412. N = DAG.getSplatBuildVector(VT, dl, N);
  3413. }
  3414. for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
  3415. GTI != E; ++GTI) {
  3416. const Value *Idx = GTI.getOperand();
  3417. if (StructType *StTy = GTI.getStructTypeOrNull()) {
  3418. unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
  3419. if (Field) {
  3420. // N = N + Offset
  3421. uint64_t Offset =
  3422. DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
  3423. // In an inbounds GEP with an offset that is nonnegative even when
  3424. // interpreted as signed, assume there is no unsigned overflow.
  3425. SDNodeFlags Flags;
  3426. if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
  3427. Flags.setNoUnsignedWrap(true);
  3428. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
  3429. DAG.getConstant(Offset, dl, N.getValueType()), Flags);
  3430. }
  3431. } else {
  3432. // IdxSize is the width of the arithmetic according to IR semantics.
  3433. // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
  3434. // (and fix up the result later).
  3435. unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
  3436. MVT IdxTy = MVT::getIntegerVT(IdxSize);
  3437. TypeSize ElementSize =
  3438. DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType());
  3439. // We intentionally mask away the high bits here; ElementSize may not
  3440. // fit in IdxTy.
  3441. APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
  3442. bool ElementScalable = ElementSize.isScalable();
  3443. // If this is a scalar constant or a splat vector of constants,
  3444. // handle it quickly.
  3445. const auto *C = dyn_cast<Constant>(Idx);
  3446. if (C && isa<VectorType>(C->getType()))
  3447. C = C->getSplatValue();
  3448. const auto *CI = dyn_cast_or_null<ConstantInt>(C);
  3449. if (CI && CI->isZero())
  3450. continue;
  3451. if (CI && !ElementScalable) {
  3452. APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
  3453. LLVMContext &Context = *DAG.getContext();
  3454. SDValue OffsVal;
  3455. if (IsVectorGEP)
  3456. OffsVal = DAG.getConstant(
  3457. Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
  3458. else
  3459. OffsVal = DAG.getConstant(Offs, dl, IdxTy);
  3460. // In an inbounds GEP with an offset that is nonnegative even when
  3461. // interpreted as signed, assume there is no unsigned overflow.
  3462. SDNodeFlags Flags;
  3463. if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
  3464. Flags.setNoUnsignedWrap(true);
  3465. OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
  3466. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
  3467. continue;
  3468. }
  3469. // N = N + Idx * ElementMul;
  3470. SDValue IdxN = getValue(Idx);
  3471. if (!IdxN.getValueType().isVector() && IsVectorGEP) {
  3472. EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
  3473. VectorElementCount);
  3474. if (VectorElementCount.isScalable())
  3475. IdxN = DAG.getSplatVector(VT, dl, IdxN);
  3476. else
  3477. IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
  3478. }
  3479. // If the index is smaller or larger than intptr_t, truncate or extend
  3480. // it.
  3481. IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
  3482. if (ElementScalable) {
  3483. EVT VScaleTy = N.getValueType().getScalarType();
  3484. SDValue VScale = DAG.getNode(
  3485. ISD::VSCALE, dl, VScaleTy,
  3486. DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
  3487. if (IsVectorGEP)
  3488. VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
  3489. IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
  3490. } else {
  3491. // If this is a multiply by a power of two, turn it into a shl
  3492. // immediately. This is a very common case.
  3493. if (ElementMul != 1) {
  3494. if (ElementMul.isPowerOf2()) {
  3495. unsigned Amt = ElementMul.logBase2();
  3496. IdxN = DAG.getNode(ISD::SHL, dl,
  3497. N.getValueType(), IdxN,
  3498. DAG.getConstant(Amt, dl, IdxN.getValueType()));
  3499. } else {
  3500. SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
  3501. IdxN.getValueType());
  3502. IdxN = DAG.getNode(ISD::MUL, dl,
  3503. N.getValueType(), IdxN, Scale);
  3504. }
  3505. }
  3506. }
  3507. N = DAG.getNode(ISD::ADD, dl,
  3508. N.getValueType(), N, IdxN);
  3509. }
  3510. }
  3511. MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
  3512. MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
  3513. if (IsVectorGEP) {
  3514. PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
  3515. PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
  3516. }
  3517. if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
  3518. N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
  3519. setValue(&I, N);
  3520. }
  3521. void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
  3522. // If this is a fixed sized alloca in the entry block of the function,
  3523. // allocate it statically on the stack.
  3524. if (FuncInfo.StaticAllocaMap.count(&I))
  3525. return; // getValue will auto-populate this.
  3526. SDLoc dl = getCurSDLoc();
  3527. Type *Ty = I.getAllocatedType();
  3528. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3529. auto &DL = DAG.getDataLayout();
  3530. TypeSize TySize = DL.getTypeAllocSize(Ty);
  3531. MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
  3532. SDValue AllocSize = getValue(I.getArraySize());
  3533. EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
  3534. if (AllocSize.getValueType() != IntPtr)
  3535. AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
  3536. if (TySize.isScalable())
  3537. AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
  3538. DAG.getVScale(dl, IntPtr,
  3539. APInt(IntPtr.getScalarSizeInBits(),
  3540. TySize.getKnownMinValue())));
  3541. else
  3542. AllocSize =
  3543. DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
  3544. DAG.getConstant(TySize.getFixedValue(), dl, IntPtr));
  3545. // Handle alignment. If the requested alignment is less than or equal to
  3546. // the stack alignment, ignore it. If the size is greater than or equal to
  3547. // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
  3548. Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
  3549. if (*Alignment <= StackAlign)
  3550. Alignment = None;
  3551. const uint64_t StackAlignMask = StackAlign.value() - 1U;
  3552. // Round the size of the allocation up to the stack alignment size
  3553. // by add SA-1 to the size. This doesn't overflow because we're computing
  3554. // an address inside an alloca.
  3555. SDNodeFlags Flags;
  3556. Flags.setNoUnsignedWrap(true);
  3557. AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
  3558. DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
  3559. // Mask out the low bits for alignment purposes.
  3560. AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
  3561. DAG.getConstant(~StackAlignMask, dl, IntPtr));
  3562. SDValue Ops[] = {
  3563. getRoot(), AllocSize,
  3564. DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
  3565. SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
  3566. SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
  3567. setValue(&I, DSA);
  3568. DAG.setRoot(DSA.getValue(1));
  3569. assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
  3570. }
  3571. void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
  3572. if (I.isAtomic())
  3573. return visitAtomicLoad(I);
  3574. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3575. const Value *SV = I.getOperand(0);
  3576. if (TLI.supportSwiftError()) {
  3577. // Swifterror values can come from either a function parameter with
  3578. // swifterror attribute or an alloca with swifterror attribute.
  3579. if (const Argument *Arg = dyn_cast<Argument>(SV)) {
  3580. if (Arg->hasSwiftErrorAttr())
  3581. return visitLoadFromSwiftError(I);
  3582. }
  3583. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
  3584. if (Alloca->isSwiftError())
  3585. return visitLoadFromSwiftError(I);
  3586. }
  3587. }
  3588. SDValue Ptr = getValue(SV);
  3589. Type *Ty = I.getType();
  3590. Align Alignment = I.getAlign();
  3591. AAMDNodes AAInfo = I.getAAMetadata();
  3592. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3593. SmallVector<EVT, 4> ValueVTs, MemVTs;
  3594. SmallVector<uint64_t, 4> Offsets;
  3595. ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
  3596. unsigned NumValues = ValueVTs.size();
  3597. if (NumValues == 0)
  3598. return;
  3599. bool isVolatile = I.isVolatile();
  3600. SDValue Root;
  3601. bool ConstantMemory = false;
  3602. if (isVolatile)
  3603. // Serialize volatile loads with other side effects.
  3604. Root = getRoot();
  3605. else if (NumValues > MaxParallelChains)
  3606. Root = getMemoryRoot();
  3607. else if (AA &&
  3608. AA->pointsToConstantMemory(MemoryLocation(
  3609. SV,
  3610. LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
  3611. AAInfo))) {
  3612. // Do not serialize (non-volatile) loads of constant memory with anything.
  3613. Root = DAG.getEntryNode();
  3614. ConstantMemory = true;
  3615. } else {
  3616. // Do not serialize non-volatile loads against each other.
  3617. Root = DAG.getRoot();
  3618. }
  3619. SDLoc dl = getCurSDLoc();
  3620. if (isVolatile)
  3621. Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
  3622. // An aggregate load cannot wrap around the address space, so offsets to its
  3623. // parts don't wrap either.
  3624. SDNodeFlags Flags;
  3625. Flags.setNoUnsignedWrap(true);
  3626. SmallVector<SDValue, 4> Values(NumValues);
  3627. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3628. EVT PtrVT = Ptr.getValueType();
  3629. MachineMemOperand::Flags MMOFlags
  3630. = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
  3631. unsigned ChainI = 0;
  3632. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3633. // Serializing loads here may result in excessive register pressure, and
  3634. // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
  3635. // could recover a bit by hoisting nodes upward in the chain by recognizing
  3636. // they are side-effect free or do not alias. The optimizer should really
  3637. // avoid this case by converting large object/array copies to llvm.memcpy
  3638. // (MaxParallelChains should always remain as failsafe).
  3639. if (ChainI == MaxParallelChains) {
  3640. assert(PendingLoads.empty() && "PendingLoads must be serialized first");
  3641. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3642. makeArrayRef(Chains.data(), ChainI));
  3643. Root = Chain;
  3644. ChainI = 0;
  3645. }
  3646. SDValue A = DAG.getNode(ISD::ADD, dl,
  3647. PtrVT, Ptr,
  3648. DAG.getConstant(Offsets[i], dl, PtrVT),
  3649. Flags);
  3650. SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
  3651. MachinePointerInfo(SV, Offsets[i]), Alignment,
  3652. MMOFlags, AAInfo, Ranges);
  3653. Chains[ChainI] = L.getValue(1);
  3654. if (MemVTs[i] != ValueVTs[i])
  3655. L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
  3656. Values[i] = L;
  3657. }
  3658. if (!ConstantMemory) {
  3659. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3660. makeArrayRef(Chains.data(), ChainI));
  3661. if (isVolatile)
  3662. DAG.setRoot(Chain);
  3663. else
  3664. PendingLoads.push_back(Chain);
  3665. }
  3666. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
  3667. DAG.getVTList(ValueVTs), Values));
  3668. }
  3669. void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
  3670. assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
  3671. "call visitStoreToSwiftError when backend supports swifterror");
  3672. SmallVector<EVT, 4> ValueVTs;
  3673. SmallVector<uint64_t, 4> Offsets;
  3674. const Value *SrcV = I.getOperand(0);
  3675. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3676. SrcV->getType(), ValueVTs, &Offsets);
  3677. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3678. "expect a single EVT for swifterror");
  3679. SDValue Src = getValue(SrcV);
  3680. // Create a virtual register, then update the virtual register.
  3681. Register VReg =
  3682. SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
  3683. // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
  3684. // Chain can be getRoot or getControlRoot.
  3685. SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
  3686. SDValue(Src.getNode(), Src.getResNo()));
  3687. DAG.setRoot(CopyNode);
  3688. }
  3689. void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
  3690. assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
  3691. "call visitLoadFromSwiftError when backend supports swifterror");
  3692. assert(!I.isVolatile() &&
  3693. !I.hasMetadata(LLVMContext::MD_nontemporal) &&
  3694. !I.hasMetadata(LLVMContext::MD_invariant_load) &&
  3695. "Support volatile, non temporal, invariant for load_from_swift_error");
  3696. const Value *SV = I.getOperand(0);
  3697. Type *Ty = I.getType();
  3698. assert(
  3699. (!AA ||
  3700. !AA->pointsToConstantMemory(MemoryLocation(
  3701. SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
  3702. I.getAAMetadata()))) &&
  3703. "load_from_swift_error should not be constant memory");
  3704. SmallVector<EVT, 4> ValueVTs;
  3705. SmallVector<uint64_t, 4> Offsets;
  3706. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
  3707. ValueVTs, &Offsets);
  3708. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3709. "expect a single EVT for swifterror");
  3710. // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
  3711. SDValue L = DAG.getCopyFromReg(
  3712. getRoot(), getCurSDLoc(),
  3713. SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
  3714. setValue(&I, L);
  3715. }
  3716. void SelectionDAGBuilder::visitStore(const StoreInst &I) {
  3717. if (I.isAtomic())
  3718. return visitAtomicStore(I);
  3719. const Value *SrcV = I.getOperand(0);
  3720. const Value *PtrV = I.getOperand(1);
  3721. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3722. if (TLI.supportSwiftError()) {
  3723. // Swifterror values can come from either a function parameter with
  3724. // swifterror attribute or an alloca with swifterror attribute.
  3725. if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
  3726. if (Arg->hasSwiftErrorAttr())
  3727. return visitStoreToSwiftError(I);
  3728. }
  3729. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
  3730. if (Alloca->isSwiftError())
  3731. return visitStoreToSwiftError(I);
  3732. }
  3733. }
  3734. SmallVector<EVT, 4> ValueVTs, MemVTs;
  3735. SmallVector<uint64_t, 4> Offsets;
  3736. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3737. SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
  3738. unsigned NumValues = ValueVTs.size();
  3739. if (NumValues == 0)
  3740. return;
  3741. // Get the lowered operands. Note that we do this after
  3742. // checking if NumResults is zero, because with zero results
  3743. // the operands won't have values in the map.
  3744. SDValue Src = getValue(SrcV);
  3745. SDValue Ptr = getValue(PtrV);
  3746. SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
  3747. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3748. SDLoc dl = getCurSDLoc();
  3749. Align Alignment = I.getAlign();
  3750. AAMDNodes AAInfo = I.getAAMetadata();
  3751. auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
  3752. // An aggregate load cannot wrap around the address space, so offsets to its
  3753. // parts don't wrap either.
  3754. SDNodeFlags Flags;
  3755. Flags.setNoUnsignedWrap(true);
  3756. unsigned ChainI = 0;
  3757. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3758. // See visitLoad comments.
  3759. if (ChainI == MaxParallelChains) {
  3760. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3761. makeArrayRef(Chains.data(), ChainI));
  3762. Root = Chain;
  3763. ChainI = 0;
  3764. }
  3765. SDValue Add =
  3766. DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags);
  3767. SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
  3768. if (MemVTs[i] != ValueVTs[i])
  3769. Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
  3770. SDValue St =
  3771. DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
  3772. Alignment, MMOFlags, AAInfo);
  3773. Chains[ChainI] = St;
  3774. }
  3775. SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3776. makeArrayRef(Chains.data(), ChainI));
  3777. DAG.setRoot(StoreNode);
  3778. }
  3779. void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
  3780. bool IsCompressing) {
  3781. SDLoc sdl = getCurSDLoc();
  3782. auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
  3783. MaybeAlign &Alignment) {
  3784. // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
  3785. Src0 = I.getArgOperand(0);
  3786. Ptr = I.getArgOperand(1);
  3787. Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
  3788. Mask = I.getArgOperand(3);
  3789. };
  3790. auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
  3791. MaybeAlign &Alignment) {
  3792. // llvm.masked.compressstore.*(Src0, Ptr, Mask)
  3793. Src0 = I.getArgOperand(0);
  3794. Ptr = I.getArgOperand(1);
  3795. Mask = I.getArgOperand(2);
  3796. Alignment = None;
  3797. };
  3798. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3799. MaybeAlign Alignment;
  3800. if (IsCompressing)
  3801. getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3802. else
  3803. getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3804. SDValue Ptr = getValue(PtrOperand);
  3805. SDValue Src0 = getValue(Src0Operand);
  3806. SDValue Mask = getValue(MaskOperand);
  3807. SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
  3808. EVT VT = Src0.getValueType();
  3809. if (!Alignment)
  3810. Alignment = DAG.getEVTAlign(VT);
  3811. MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
  3812. MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
  3813. MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata());
  3814. SDValue StoreNode =
  3815. DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
  3816. ISD::UNINDEXED, false /* Truncating */, IsCompressing);
  3817. DAG.setRoot(StoreNode);
  3818. setValue(&I, StoreNode);
  3819. }
  3820. // Get a uniform base for the Gather/Scatter intrinsic.
  3821. // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
  3822. // We try to represent it as a base pointer + vector of indices.
  3823. // Usually, the vector of pointers comes from a 'getelementptr' instruction.
  3824. // The first operand of the GEP may be a single pointer or a vector of pointers
  3825. // Example:
  3826. // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
  3827. // or
  3828. // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
  3829. // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
  3830. //
  3831. // When the first GEP operand is a single pointer - it is the uniform base we
  3832. // are looking for. If first operand of the GEP is a splat vector - we
  3833. // extract the splat value and use it as a uniform base.
  3834. // In all other cases the function returns 'false'.
  3835. static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
  3836. ISD::MemIndexType &IndexType, SDValue &Scale,
  3837. SelectionDAGBuilder *SDB, const BasicBlock *CurBB) {
  3838. SelectionDAG& DAG = SDB->DAG;
  3839. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3840. const DataLayout &DL = DAG.getDataLayout();
  3841. assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
  3842. // Handle splat constant pointer.
  3843. if (auto *C = dyn_cast<Constant>(Ptr)) {
  3844. C = C->getSplatValue();
  3845. if (!C)
  3846. return false;
  3847. Base = SDB->getValue(C);
  3848. ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
  3849. EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
  3850. Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
  3851. IndexType = ISD::SIGNED_SCALED;
  3852. Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
  3853. return true;
  3854. }
  3855. const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
  3856. if (!GEP || GEP->getParent() != CurBB)
  3857. return false;
  3858. if (GEP->getNumOperands() != 2)
  3859. return false;
  3860. const Value *BasePtr = GEP->getPointerOperand();
  3861. const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
  3862. // Make sure the base is scalar and the index is a vector.
  3863. if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
  3864. return false;
  3865. Base = SDB->getValue(BasePtr);
  3866. Index = SDB->getValue(IndexVal);
  3867. IndexType = ISD::SIGNED_SCALED;
  3868. Scale = DAG.getTargetConstant(
  3869. DL.getTypeAllocSize(GEP->getResultElementType()),
  3870. SDB->getCurSDLoc(), TLI.getPointerTy(DL));
  3871. return true;
  3872. }
  3873. void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
  3874. SDLoc sdl = getCurSDLoc();
  3875. // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
  3876. const Value *Ptr = I.getArgOperand(1);
  3877. SDValue Src0 = getValue(I.getArgOperand(0));
  3878. SDValue Mask = getValue(I.getArgOperand(3));
  3879. EVT VT = Src0.getValueType();
  3880. Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
  3881. ->getMaybeAlignValue()
  3882. .getValueOr(DAG.getEVTAlign(VT.getScalarType()));
  3883. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3884. SDValue Base;
  3885. SDValue Index;
  3886. ISD::MemIndexType IndexType;
  3887. SDValue Scale;
  3888. bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
  3889. I.getParent());
  3890. unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
  3891. MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
  3892. MachinePointerInfo(AS), MachineMemOperand::MOStore,
  3893. // TODO: Make MachineMemOperands aware of scalable
  3894. // vectors.
  3895. MemoryLocation::UnknownSize, Alignment, I.getAAMetadata());
  3896. if (!UniformBase) {
  3897. Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3898. Index = getValue(Ptr);
  3899. IndexType = ISD::SIGNED_UNSCALED;
  3900. Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3901. }
  3902. EVT IdxVT = Index.getValueType();
  3903. EVT EltTy = IdxVT.getVectorElementType();
  3904. if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
  3905. EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
  3906. Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
  3907. }
  3908. SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
  3909. SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
  3910. Ops, MMO, IndexType, false);
  3911. DAG.setRoot(Scatter);
  3912. setValue(&I, Scatter);
  3913. }
  3914. void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
  3915. SDLoc sdl = getCurSDLoc();
  3916. auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
  3917. MaybeAlign &Alignment) {
  3918. // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
  3919. Ptr = I.getArgOperand(0);
  3920. Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
  3921. Mask = I.getArgOperand(2);
  3922. Src0 = I.getArgOperand(3);
  3923. };
  3924. auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
  3925. MaybeAlign &Alignment) {
  3926. // @llvm.masked.expandload.*(Ptr, Mask, Src0)
  3927. Ptr = I.getArgOperand(0);
  3928. Alignment = None;
  3929. Mask = I.getArgOperand(1);
  3930. Src0 = I.getArgOperand(2);
  3931. };
  3932. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3933. MaybeAlign Alignment;
  3934. if (IsExpanding)
  3935. getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3936. else
  3937. getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3938. SDValue Ptr = getValue(PtrOperand);
  3939. SDValue Src0 = getValue(Src0Operand);
  3940. SDValue Mask = getValue(MaskOperand);
  3941. SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
  3942. EVT VT = Src0.getValueType();
  3943. if (!Alignment)
  3944. Alignment = DAG.getEVTAlign(VT);
  3945. AAMDNodes AAInfo = I.getAAMetadata();
  3946. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3947. // Do not serialize masked loads of constant memory with anything.
  3948. MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
  3949. bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
  3950. SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
  3951. MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
  3952. MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
  3953. MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
  3954. SDValue Load =
  3955. DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
  3956. ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
  3957. if (AddToChain)
  3958. PendingLoads.push_back(Load.getValue(1));
  3959. setValue(&I, Load);
  3960. }
  3961. void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
  3962. SDLoc sdl = getCurSDLoc();
  3963. // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
  3964. const Value *Ptr = I.getArgOperand(0);
  3965. SDValue Src0 = getValue(I.getArgOperand(3));
  3966. SDValue Mask = getValue(I.getArgOperand(2));
  3967. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3968. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3969. Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
  3970. ->getMaybeAlignValue()
  3971. .getValueOr(DAG.getEVTAlign(VT.getScalarType()));
  3972. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3973. SDValue Root = DAG.getRoot();
  3974. SDValue Base;
  3975. SDValue Index;
  3976. ISD::MemIndexType IndexType;
  3977. SDValue Scale;
  3978. bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
  3979. I.getParent());
  3980. unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
  3981. MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
  3982. MachinePointerInfo(AS), MachineMemOperand::MOLoad,
  3983. // TODO: Make MachineMemOperands aware of scalable
  3984. // vectors.
  3985. MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
  3986. if (!UniformBase) {
  3987. Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3988. Index = getValue(Ptr);
  3989. IndexType = ISD::SIGNED_UNSCALED;
  3990. Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3991. }
  3992. EVT IdxVT = Index.getValueType();
  3993. EVT EltTy = IdxVT.getVectorElementType();
  3994. if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
  3995. EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
  3996. Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
  3997. }
  3998. SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
  3999. SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
  4000. Ops, MMO, IndexType, ISD::NON_EXTLOAD);
  4001. PendingLoads.push_back(Gather.getValue(1));
  4002. setValue(&I, Gather);
  4003. }
  4004. void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
  4005. SDLoc dl = getCurSDLoc();
  4006. AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
  4007. AtomicOrdering FailureOrdering = I.getFailureOrdering();
  4008. SyncScope::ID SSID = I.getSyncScopeID();
  4009. SDValue InChain = getRoot();
  4010. MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
  4011. SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
  4012. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4013. auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
  4014. MachineFunction &MF = DAG.getMachineFunction();
  4015. MachineMemOperand *MMO = MF.getMachineMemOperand(
  4016. MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
  4017. DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
  4018. FailureOrdering);
  4019. SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
  4020. dl, MemVT, VTs, InChain,
  4021. getValue(I.getPointerOperand()),
  4022. getValue(I.getCompareOperand()),
  4023. getValue(I.getNewValOperand()), MMO);
  4024. SDValue OutChain = L.getValue(2);
  4025. setValue(&I, L);
  4026. DAG.setRoot(OutChain);
  4027. }
  4028. void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
  4029. SDLoc dl = getCurSDLoc();
  4030. ISD::NodeType NT;
  4031. switch (I.getOperation()) {
  4032. default: llvm_unreachable("Unknown atomicrmw operation");
  4033. case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
  4034. case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
  4035. case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
  4036. case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
  4037. case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
  4038. case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
  4039. case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
  4040. case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
  4041. case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
  4042. case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
  4043. case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
  4044. case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
  4045. case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
  4046. }
  4047. AtomicOrdering Ordering = I.getOrdering();
  4048. SyncScope::ID SSID = I.getSyncScopeID();
  4049. SDValue InChain = getRoot();
  4050. auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
  4051. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4052. auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
  4053. MachineFunction &MF = DAG.getMachineFunction();
  4054. MachineMemOperand *MMO = MF.getMachineMemOperand(
  4055. MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
  4056. DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
  4057. SDValue L =
  4058. DAG.getAtomic(NT, dl, MemVT, InChain,
  4059. getValue(I.getPointerOperand()), getValue(I.getValOperand()),
  4060. MMO);
  4061. SDValue OutChain = L.getValue(1);
  4062. setValue(&I, L);
  4063. DAG.setRoot(OutChain);
  4064. }
  4065. void SelectionDAGBuilder::visitFence(const FenceInst &I) {
  4066. SDLoc dl = getCurSDLoc();
  4067. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4068. SDValue Ops[3];
  4069. Ops[0] = getRoot();
  4070. Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
  4071. TLI.getFenceOperandTy(DAG.getDataLayout()));
  4072. Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
  4073. TLI.getFenceOperandTy(DAG.getDataLayout()));
  4074. DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
  4075. }
  4076. void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
  4077. SDLoc dl = getCurSDLoc();
  4078. AtomicOrdering Order = I.getOrdering();
  4079. SyncScope::ID SSID = I.getSyncScopeID();
  4080. SDValue InChain = getRoot();
  4081. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4082. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4083. EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
  4084. if (!TLI.supportsUnalignedAtomics() &&
  4085. I.getAlignment() < MemVT.getSizeInBits() / 8)
  4086. report_fatal_error("Cannot generate unaligned atomic load");
  4087. auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
  4088. MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
  4089. MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
  4090. I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
  4091. InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
  4092. SDValue Ptr = getValue(I.getPointerOperand());
  4093. if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
  4094. // TODO: Once this is better exercised by tests, it should be merged with
  4095. // the normal path for loads to prevent future divergence.
  4096. SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
  4097. if (MemVT != VT)
  4098. L = DAG.getPtrExtOrTrunc(L, dl, VT);
  4099. setValue(&I, L);
  4100. SDValue OutChain = L.getValue(1);
  4101. if (!I.isUnordered())
  4102. DAG.setRoot(OutChain);
  4103. else
  4104. PendingLoads.push_back(OutChain);
  4105. return;
  4106. }
  4107. SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
  4108. Ptr, MMO);
  4109. SDValue OutChain = L.getValue(1);
  4110. if (MemVT != VT)
  4111. L = DAG.getPtrExtOrTrunc(L, dl, VT);
  4112. setValue(&I, L);
  4113. DAG.setRoot(OutChain);
  4114. }
  4115. void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
  4116. SDLoc dl = getCurSDLoc();
  4117. AtomicOrdering Ordering = I.getOrdering();
  4118. SyncScope::ID SSID = I.getSyncScopeID();
  4119. SDValue InChain = getRoot();
  4120. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4121. EVT MemVT =
  4122. TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
  4123. if (I.getAlignment() < MemVT.getSizeInBits() / 8)
  4124. report_fatal_error("Cannot generate unaligned atomic store");
  4125. auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
  4126. MachineFunction &MF = DAG.getMachineFunction();
  4127. MachineMemOperand *MMO = MF.getMachineMemOperand(
  4128. MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
  4129. I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
  4130. SDValue Val = getValue(I.getValueOperand());
  4131. if (Val.getValueType() != MemVT)
  4132. Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
  4133. SDValue Ptr = getValue(I.getPointerOperand());
  4134. if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
  4135. // TODO: Once this is better exercised by tests, it should be merged with
  4136. // the normal path for stores to prevent future divergence.
  4137. SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
  4138. DAG.setRoot(S);
  4139. return;
  4140. }
  4141. SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
  4142. Ptr, Val, MMO);
  4143. DAG.setRoot(OutChain);
  4144. }
  4145. /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
  4146. /// node.
  4147. void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
  4148. unsigned Intrinsic) {
  4149. // Ignore the callsite's attributes. A specific call site may be marked with
  4150. // readnone, but the lowering code will expect the chain based on the
  4151. // definition.
  4152. const Function *F = I.getCalledFunction();
  4153. bool HasChain = !F->doesNotAccessMemory();
  4154. bool OnlyLoad = HasChain && F->onlyReadsMemory();
  4155. // Build the operand list.
  4156. SmallVector<SDValue, 8> Ops;
  4157. if (HasChain) { // If this intrinsic has side-effects, chainify it.
  4158. if (OnlyLoad) {
  4159. // We don't need to serialize loads against other loads.
  4160. Ops.push_back(DAG.getRoot());
  4161. } else {
  4162. Ops.push_back(getRoot());
  4163. }
  4164. }
  4165. // Info is set by getTgtMemInstrinsic
  4166. TargetLowering::IntrinsicInfo Info;
  4167. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4168. bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
  4169. DAG.getMachineFunction(),
  4170. Intrinsic);
  4171. // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
  4172. if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
  4173. Info.opc == ISD::INTRINSIC_W_CHAIN)
  4174. Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
  4175. TLI.getPointerTy(DAG.getDataLayout())));
  4176. // Add all operands of the call to the operand list.
  4177. for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
  4178. const Value *Arg = I.getArgOperand(i);
  4179. if (!I.paramHasAttr(i, Attribute::ImmArg)) {
  4180. Ops.push_back(getValue(Arg));
  4181. continue;
  4182. }
  4183. // Use TargetConstant instead of a regular constant for immarg.
  4184. EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
  4185. if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
  4186. assert(CI->getBitWidth() <= 64 &&
  4187. "large intrinsic immediates not handled");
  4188. Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
  4189. } else {
  4190. Ops.push_back(
  4191. DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
  4192. }
  4193. }
  4194. SmallVector<EVT, 4> ValueVTs;
  4195. ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
  4196. if (HasChain)
  4197. ValueVTs.push_back(MVT::Other);
  4198. SDVTList VTs = DAG.getVTList(ValueVTs);
  4199. // Propagate fast-math-flags from IR to node(s).
  4200. SDNodeFlags Flags;
  4201. if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
  4202. Flags.copyFMF(*FPMO);
  4203. SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
  4204. // Create the node.
  4205. SDValue Result;
  4206. if (IsTgtIntrinsic) {
  4207. // This is target intrinsic that touches memory
  4208. Result =
  4209. DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
  4210. MachinePointerInfo(Info.ptrVal, Info.offset),
  4211. Info.align, Info.flags, Info.size,
  4212. I.getAAMetadata());
  4213. } else if (!HasChain) {
  4214. Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
  4215. } else if (!I.getType()->isVoidTy()) {
  4216. Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
  4217. } else {
  4218. Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
  4219. }
  4220. if (HasChain) {
  4221. SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
  4222. if (OnlyLoad)
  4223. PendingLoads.push_back(Chain);
  4224. else
  4225. DAG.setRoot(Chain);
  4226. }
  4227. if (!I.getType()->isVoidTy()) {
  4228. if (!isa<VectorType>(I.getType()))
  4229. Result = lowerRangeToAssertZExt(DAG, I, Result);
  4230. MaybeAlign Alignment = I.getRetAlign();
  4231. if (!Alignment)
  4232. Alignment = F->getAttributes().getRetAlignment();
  4233. // Insert `assertalign` node if there's an alignment.
  4234. if (InsertAssertAlign && Alignment) {
  4235. Result =
  4236. DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
  4237. }
  4238. setValue(&I, Result);
  4239. }
  4240. }
  4241. /// GetSignificand - Get the significand and build it into a floating-point
  4242. /// number with exponent of 1:
  4243. ///
  4244. /// Op = (Op & 0x007fffff) | 0x3f800000;
  4245. ///
  4246. /// where Op is the hexadecimal representation of floating point value.
  4247. static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
  4248. SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  4249. DAG.getConstant(0x007fffff, dl, MVT::i32));
  4250. SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
  4251. DAG.getConstant(0x3f800000, dl, MVT::i32));
  4252. return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
  4253. }
  4254. /// GetExponent - Get the exponent:
  4255. ///
  4256. /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
  4257. ///
  4258. /// where Op is the hexadecimal representation of floating point value.
  4259. static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
  4260. const TargetLowering &TLI, const SDLoc &dl) {
  4261. SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  4262. DAG.getConstant(0x7f800000, dl, MVT::i32));
  4263. SDValue t1 = DAG.getNode(
  4264. ISD::SRL, dl, MVT::i32, t0,
  4265. DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
  4266. SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
  4267. DAG.getConstant(127, dl, MVT::i32));
  4268. return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
  4269. }
  4270. /// getF32Constant - Get 32-bit floating point constant.
  4271. static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
  4272. const SDLoc &dl) {
  4273. return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
  4274. MVT::f32);
  4275. }
  4276. static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
  4277. SelectionDAG &DAG) {
  4278. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4279. // IntegerPartOfX = ((int32_t)(t0);
  4280. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
  4281. // FractionalPartOfX = t0 - (float)IntegerPartOfX;
  4282. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  4283. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
  4284. // IntegerPartOfX <<= 23;
  4285. IntegerPartOfX = DAG.getNode(
  4286. ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  4287. DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
  4288. DAG.getDataLayout())));
  4289. SDValue TwoToFractionalPartOfX;
  4290. if (LimitFloatPrecision <= 6) {
  4291. // For floating-point precision of 6:
  4292. //
  4293. // TwoToFractionalPartOfX =
  4294. // 0.997535578f +
  4295. // (0.735607626f + 0.252464424f * x) * x;
  4296. //
  4297. // error 0.0144103317, which is 6 bits
  4298. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4299. getF32Constant(DAG, 0x3e814304, dl));
  4300. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4301. getF32Constant(DAG, 0x3f3c50c8, dl));
  4302. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4303. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4304. getF32Constant(DAG, 0x3f7f5e7e, dl));
  4305. } else if (LimitFloatPrecision <= 12) {
  4306. // For floating-point precision of 12:
  4307. //
  4308. // TwoToFractionalPartOfX =
  4309. // 0.999892986f +
  4310. // (0.696457318f +
  4311. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  4312. //
  4313. // error 0.000107046256, which is 13 to 14 bits
  4314. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4315. getF32Constant(DAG, 0x3da235e3, dl));
  4316. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4317. getF32Constant(DAG, 0x3e65b8f3, dl));
  4318. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4319. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4320. getF32Constant(DAG, 0x3f324b07, dl));
  4321. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4322. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4323. getF32Constant(DAG, 0x3f7ff8fd, dl));
  4324. } else { // LimitFloatPrecision <= 18
  4325. // For floating-point precision of 18:
  4326. //
  4327. // TwoToFractionalPartOfX =
  4328. // 0.999999982f +
  4329. // (0.693148872f +
  4330. // (0.240227044f +
  4331. // (0.554906021e-1f +
  4332. // (0.961591928e-2f +
  4333. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  4334. // error 2.47208000*10^(-7), which is better than 18 bits
  4335. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4336. getF32Constant(DAG, 0x3924b03e, dl));
  4337. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4338. getF32Constant(DAG, 0x3ab24b87, dl));
  4339. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4340. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4341. getF32Constant(DAG, 0x3c1d8c17, dl));
  4342. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4343. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4344. getF32Constant(DAG, 0x3d634a1d, dl));
  4345. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4346. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4347. getF32Constant(DAG, 0x3e75fe14, dl));
  4348. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4349. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  4350. getF32Constant(DAG, 0x3f317234, dl));
  4351. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  4352. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  4353. getF32Constant(DAG, 0x3f800000, dl));
  4354. }
  4355. // Add the exponent into the result in integer domain.
  4356. SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
  4357. return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
  4358. DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
  4359. }
  4360. /// expandExp - Lower an exp intrinsic. Handles the special sequences for
  4361. /// limited-precision mode.
  4362. static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4363. const TargetLowering &TLI, SDNodeFlags Flags) {
  4364. if (Op.getValueType() == MVT::f32 &&
  4365. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4366. // Put the exponent in the right bit position for later addition to the
  4367. // final result:
  4368. //
  4369. // t0 = Op * log2(e)
  4370. // TODO: What fast-math-flags should be set here?
  4371. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
  4372. DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
  4373. return getLimitedPrecisionExp2(t0, dl, DAG);
  4374. }
  4375. // No special expansion.
  4376. return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
  4377. }
  4378. /// expandLog - Lower a log intrinsic. Handles the special sequences for
  4379. /// limited-precision mode.
  4380. static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4381. const TargetLowering &TLI, SDNodeFlags Flags) {
  4382. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4383. if (Op.getValueType() == MVT::f32 &&
  4384. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4385. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4386. // Scale the exponent by log(2).
  4387. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  4388. SDValue LogOfExponent =
  4389. DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  4390. DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
  4391. // Get the significand and build it into a floating-point number with
  4392. // exponent of 1.
  4393. SDValue X = GetSignificand(DAG, Op1, dl);
  4394. SDValue LogOfMantissa;
  4395. if (LimitFloatPrecision <= 6) {
  4396. // For floating-point precision of 6:
  4397. //
  4398. // LogofMantissa =
  4399. // -1.1609546f +
  4400. // (1.4034025f - 0.23903021f * x) * x;
  4401. //
  4402. // error 0.0034276066, which is better than 8 bits
  4403. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4404. getF32Constant(DAG, 0xbe74c456, dl));
  4405. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4406. getF32Constant(DAG, 0x3fb3a2b1, dl));
  4407. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4408. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4409. getF32Constant(DAG, 0x3f949a29, dl));
  4410. } else if (LimitFloatPrecision <= 12) {
  4411. // For floating-point precision of 12:
  4412. //
  4413. // LogOfMantissa =
  4414. // -1.7417939f +
  4415. // (2.8212026f +
  4416. // (-1.4699568f +
  4417. // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
  4418. //
  4419. // error 0.000061011436, which is 14 bits
  4420. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4421. getF32Constant(DAG, 0xbd67b6d6, dl));
  4422. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4423. getF32Constant(DAG, 0x3ee4f4b8, dl));
  4424. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4425. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4426. getF32Constant(DAG, 0x3fbc278b, dl));
  4427. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4428. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4429. getF32Constant(DAG, 0x40348e95, dl));
  4430. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4431. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4432. getF32Constant(DAG, 0x3fdef31a, dl));
  4433. } else { // LimitFloatPrecision <= 18
  4434. // For floating-point precision of 18:
  4435. //
  4436. // LogOfMantissa =
  4437. // -2.1072184f +
  4438. // (4.2372794f +
  4439. // (-3.7029485f +
  4440. // (2.2781945f +
  4441. // (-0.87823314f +
  4442. // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
  4443. //
  4444. // error 0.0000023660568, which is better than 18 bits
  4445. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4446. getF32Constant(DAG, 0xbc91e5ac, dl));
  4447. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4448. getF32Constant(DAG, 0x3e4350aa, dl));
  4449. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4450. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4451. getF32Constant(DAG, 0x3f60d3e3, dl));
  4452. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4453. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4454. getF32Constant(DAG, 0x4011cdf0, dl));
  4455. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4456. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4457. getF32Constant(DAG, 0x406cfd1c, dl));
  4458. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4459. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4460. getF32Constant(DAG, 0x408797cb, dl));
  4461. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4462. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  4463. getF32Constant(DAG, 0x4006dcab, dl));
  4464. }
  4465. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
  4466. }
  4467. // No special expansion.
  4468. return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
  4469. }
  4470. /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
  4471. /// limited-precision mode.
  4472. static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4473. const TargetLowering &TLI, SDNodeFlags Flags) {
  4474. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4475. if (Op.getValueType() == MVT::f32 &&
  4476. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4477. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4478. // Get the exponent.
  4479. SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
  4480. // Get the significand and build it into a floating-point number with
  4481. // exponent of 1.
  4482. SDValue X = GetSignificand(DAG, Op1, dl);
  4483. // Different possible minimax approximations of significand in
  4484. // floating-point for various degrees of accuracy over [1,2].
  4485. SDValue Log2ofMantissa;
  4486. if (LimitFloatPrecision <= 6) {
  4487. // For floating-point precision of 6:
  4488. //
  4489. // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
  4490. //
  4491. // error 0.0049451742, which is more than 7 bits
  4492. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4493. getF32Constant(DAG, 0xbeb08fe0, dl));
  4494. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4495. getF32Constant(DAG, 0x40019463, dl));
  4496. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4497. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4498. getF32Constant(DAG, 0x3fd6633d, dl));
  4499. } else if (LimitFloatPrecision <= 12) {
  4500. // For floating-point precision of 12:
  4501. //
  4502. // Log2ofMantissa =
  4503. // -2.51285454f +
  4504. // (4.07009056f +
  4505. // (-2.12067489f +
  4506. // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
  4507. //
  4508. // error 0.0000876136000, which is better than 13 bits
  4509. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4510. getF32Constant(DAG, 0xbda7262e, dl));
  4511. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4512. getF32Constant(DAG, 0x3f25280b, dl));
  4513. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4514. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4515. getF32Constant(DAG, 0x4007b923, dl));
  4516. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4517. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4518. getF32Constant(DAG, 0x40823e2f, dl));
  4519. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4520. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4521. getF32Constant(DAG, 0x4020d29c, dl));
  4522. } else { // LimitFloatPrecision <= 18
  4523. // For floating-point precision of 18:
  4524. //
  4525. // Log2ofMantissa =
  4526. // -3.0400495f +
  4527. // (6.1129976f +
  4528. // (-5.3420409f +
  4529. // (3.2865683f +
  4530. // (-1.2669343f +
  4531. // (0.27515199f -
  4532. // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
  4533. //
  4534. // error 0.0000018516, which is better than 18 bits
  4535. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4536. getF32Constant(DAG, 0xbcd2769e, dl));
  4537. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4538. getF32Constant(DAG, 0x3e8ce0b9, dl));
  4539. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4540. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4541. getF32Constant(DAG, 0x3fa22ae7, dl));
  4542. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4543. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4544. getF32Constant(DAG, 0x40525723, dl));
  4545. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4546. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4547. getF32Constant(DAG, 0x40aaf200, dl));
  4548. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4549. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4550. getF32Constant(DAG, 0x40c39dad, dl));
  4551. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4552. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  4553. getF32Constant(DAG, 0x4042902c, dl));
  4554. }
  4555. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
  4556. }
  4557. // No special expansion.
  4558. return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
  4559. }
  4560. /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
  4561. /// limited-precision mode.
  4562. static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4563. const TargetLowering &TLI, SDNodeFlags Flags) {
  4564. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4565. if (Op.getValueType() == MVT::f32 &&
  4566. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4567. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4568. // Scale the exponent by log10(2) [0.30102999f].
  4569. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  4570. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  4571. getF32Constant(DAG, 0x3e9a209a, dl));
  4572. // Get the significand and build it into a floating-point number with
  4573. // exponent of 1.
  4574. SDValue X = GetSignificand(DAG, Op1, dl);
  4575. SDValue Log10ofMantissa;
  4576. if (LimitFloatPrecision <= 6) {
  4577. // For floating-point precision of 6:
  4578. //
  4579. // Log10ofMantissa =
  4580. // -0.50419619f +
  4581. // (0.60948995f - 0.10380950f * x) * x;
  4582. //
  4583. // error 0.0014886165, which is 6 bits
  4584. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4585. getF32Constant(DAG, 0xbdd49a13, dl));
  4586. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4587. getF32Constant(DAG, 0x3f1c0789, dl));
  4588. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4589. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4590. getF32Constant(DAG, 0x3f011300, dl));
  4591. } else if (LimitFloatPrecision <= 12) {
  4592. // For floating-point precision of 12:
  4593. //
  4594. // Log10ofMantissa =
  4595. // -0.64831180f +
  4596. // (0.91751397f +
  4597. // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
  4598. //
  4599. // error 0.00019228036, which is better than 12 bits
  4600. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4601. getF32Constant(DAG, 0x3d431f31, dl));
  4602. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  4603. getF32Constant(DAG, 0x3ea21fb2, dl));
  4604. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4605. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4606. getF32Constant(DAG, 0x3f6ae232, dl));
  4607. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4608. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  4609. getF32Constant(DAG, 0x3f25f7c3, dl));
  4610. } else { // LimitFloatPrecision <= 18
  4611. // For floating-point precision of 18:
  4612. //
  4613. // Log10ofMantissa =
  4614. // -0.84299375f +
  4615. // (1.5327582f +
  4616. // (-1.0688956f +
  4617. // (0.49102474f +
  4618. // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
  4619. //
  4620. // error 0.0000037995730, which is better than 18 bits
  4621. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4622. getF32Constant(DAG, 0x3c5d51ce, dl));
  4623. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  4624. getF32Constant(DAG, 0x3e00685a, dl));
  4625. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4626. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4627. getF32Constant(DAG, 0x3efb6798, dl));
  4628. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4629. SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  4630. getF32Constant(DAG, 0x3f88d192, dl));
  4631. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4632. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4633. getF32Constant(DAG, 0x3fc4316c, dl));
  4634. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4635. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
  4636. getF32Constant(DAG, 0x3f57ce70, dl));
  4637. }
  4638. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
  4639. }
  4640. // No special expansion.
  4641. return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
  4642. }
  4643. /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
  4644. /// limited-precision mode.
  4645. static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4646. const TargetLowering &TLI, SDNodeFlags Flags) {
  4647. if (Op.getValueType() == MVT::f32 &&
  4648. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
  4649. return getLimitedPrecisionExp2(Op, dl, DAG);
  4650. // No special expansion.
  4651. return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
  4652. }
  4653. /// visitPow - Lower a pow intrinsic. Handles the special sequences for
  4654. /// limited-precision mode with x == 10.0f.
  4655. static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
  4656. SelectionDAG &DAG, const TargetLowering &TLI,
  4657. SDNodeFlags Flags) {
  4658. bool IsExp10 = false;
  4659. if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
  4660. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4661. if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
  4662. APFloat Ten(10.0f);
  4663. IsExp10 = LHSC->isExactlyValue(Ten);
  4664. }
  4665. }
  4666. // TODO: What fast-math-flags should be set on the FMUL node?
  4667. if (IsExp10) {
  4668. // Put the exponent in the right bit position for later addition to the
  4669. // final result:
  4670. //
  4671. // #define LOG2OF10 3.3219281f
  4672. // t0 = Op * LOG2OF10;
  4673. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
  4674. getF32Constant(DAG, 0x40549a78, dl));
  4675. return getLimitedPrecisionExp2(t0, dl, DAG);
  4676. }
  4677. // No special expansion.
  4678. return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
  4679. }
  4680. /// ExpandPowI - Expand a llvm.powi intrinsic.
  4681. static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
  4682. SelectionDAG &DAG) {
  4683. // If RHS is a constant, we can expand this out to a multiplication tree,
  4684. // otherwise we end up lowering to a call to __powidf2 (for example). When
  4685. // optimizing for size, we only want to do this if the expansion would produce
  4686. // a small number of multiplies, otherwise we do the full expansion.
  4687. if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
  4688. // Get the exponent as a positive value.
  4689. unsigned Val = RHSC->getSExtValue();
  4690. if ((int)Val < 0) Val = -Val;
  4691. // powi(x, 0) -> 1.0
  4692. if (Val == 0)
  4693. return DAG.getConstantFP(1.0, DL, LHS.getValueType());
  4694. bool OptForSize = DAG.shouldOptForSize();
  4695. if (!OptForSize ||
  4696. // If optimizing for size, don't insert too many multiplies.
  4697. // This inserts up to 5 multiplies.
  4698. countPopulation(Val) + Log2_32(Val) < 7) {
  4699. // We use the simple binary decomposition method to generate the multiply
  4700. // sequence. There are more optimal ways to do this (for example,
  4701. // powi(x,15) generates one more multiply than it should), but this has
  4702. // the benefit of being both really simple and much better than a libcall.
  4703. SDValue Res; // Logically starts equal to 1.0
  4704. SDValue CurSquare = LHS;
  4705. // TODO: Intrinsics should have fast-math-flags that propagate to these
  4706. // nodes.
  4707. while (Val) {
  4708. if (Val & 1) {
  4709. if (Res.getNode())
  4710. Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
  4711. else
  4712. Res = CurSquare; // 1.0*CurSquare.
  4713. }
  4714. CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
  4715. CurSquare, CurSquare);
  4716. Val >>= 1;
  4717. }
  4718. // If the original was negative, invert the result, producing 1/(x*x*x).
  4719. if (RHSC->getSExtValue() < 0)
  4720. Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
  4721. DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
  4722. return Res;
  4723. }
  4724. }
  4725. // Otherwise, expand to a libcall.
  4726. return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
  4727. }
  4728. static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
  4729. SDValue LHS, SDValue RHS, SDValue Scale,
  4730. SelectionDAG &DAG, const TargetLowering &TLI) {
  4731. EVT VT = LHS.getValueType();
  4732. bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
  4733. bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
  4734. LLVMContext &Ctx = *DAG.getContext();
  4735. // If the type is legal but the operation isn't, this node might survive all
  4736. // the way to operation legalization. If we end up there and we do not have
  4737. // the ability to widen the type (if VT*2 is not legal), we cannot expand the
  4738. // node.
  4739. // Coax the legalizer into expanding the node during type legalization instead
  4740. // by bumping the size by one bit. This will force it to Promote, enabling the
  4741. // early expansion and avoiding the need to expand later.
  4742. // We don't have to do this if Scale is 0; that can always be expanded, unless
  4743. // it's a saturating signed operation. Those can experience true integer
  4744. // division overflow, a case which we must avoid.
  4745. // FIXME: We wouldn't have to do this (or any of the early
  4746. // expansion/promotion) if it was possible to expand a libcall of an
  4747. // illegal type during operation legalization. But it's not, so things
  4748. // get a bit hacky.
  4749. unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
  4750. if ((ScaleInt > 0 || (Saturating && Signed)) &&
  4751. (TLI.isTypeLegal(VT) ||
  4752. (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
  4753. TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
  4754. Opcode, VT, ScaleInt);
  4755. if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
  4756. EVT PromVT;
  4757. if (VT.isScalarInteger())
  4758. PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
  4759. else if (VT.isVector()) {
  4760. PromVT = VT.getVectorElementType();
  4761. PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
  4762. PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
  4763. } else
  4764. llvm_unreachable("Wrong VT for DIVFIX?");
  4765. if (Signed) {
  4766. LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
  4767. RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
  4768. } else {
  4769. LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
  4770. RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
  4771. }
  4772. EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
  4773. // For saturating operations, we need to shift up the LHS to get the
  4774. // proper saturation width, and then shift down again afterwards.
  4775. if (Saturating)
  4776. LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
  4777. DAG.getConstant(1, DL, ShiftTy));
  4778. SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
  4779. if (Saturating)
  4780. Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
  4781. DAG.getConstant(1, DL, ShiftTy));
  4782. return DAG.getZExtOrTrunc(Res, DL, VT);
  4783. }
  4784. }
  4785. return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
  4786. }
  4787. // getUnderlyingArgRegs - Find underlying registers used for a truncated,
  4788. // bitcasted, or split argument. Returns a list of <Register, size in bits>
  4789. static void
  4790. getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
  4791. const SDValue &N) {
  4792. switch (N.getOpcode()) {
  4793. case ISD::CopyFromReg: {
  4794. SDValue Op = N.getOperand(1);
  4795. Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
  4796. Op.getValueType().getSizeInBits());
  4797. return;
  4798. }
  4799. case ISD::BITCAST:
  4800. case ISD::AssertZext:
  4801. case ISD::AssertSext:
  4802. case ISD::TRUNCATE:
  4803. getUnderlyingArgRegs(Regs, N.getOperand(0));
  4804. return;
  4805. case ISD::BUILD_PAIR:
  4806. case ISD::BUILD_VECTOR:
  4807. case ISD::CONCAT_VECTORS:
  4808. for (SDValue Op : N->op_values())
  4809. getUnderlyingArgRegs(Regs, Op);
  4810. return;
  4811. default:
  4812. return;
  4813. }
  4814. }
  4815. /// If the DbgValueInst is a dbg_value of a function argument, create the
  4816. /// corresponding DBG_VALUE machine instruction for it now. At the end of
  4817. /// instruction selection, they will be inserted to the entry BB.
  4818. /// We don't currently support this for variadic dbg_values, as they shouldn't
  4819. /// appear for function arguments or in the prologue.
  4820. bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
  4821. const Value *V, DILocalVariable *Variable, DIExpression *Expr,
  4822. DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
  4823. const Argument *Arg = dyn_cast<Argument>(V);
  4824. if (!Arg)
  4825. return false;
  4826. MachineFunction &MF = DAG.getMachineFunction();
  4827. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  4828. // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
  4829. // we've been asked to pursue.
  4830. auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
  4831. bool Indirect) {
  4832. if (Reg.isVirtual() && MF.useDebugInstrRef()) {
  4833. // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
  4834. // pointing at the VReg, which will be patched up later.
  4835. auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
  4836. auto MIB = BuildMI(MF, DL, Inst);
  4837. MIB.addReg(Reg);
  4838. MIB.addImm(0);
  4839. MIB.addMetadata(Variable);
  4840. auto *NewDIExpr = FragExpr;
  4841. // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
  4842. // the DIExpression.
  4843. if (Indirect)
  4844. NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
  4845. MIB.addMetadata(NewDIExpr);
  4846. return MIB;
  4847. } else {
  4848. // Create a completely standard DBG_VALUE.
  4849. auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
  4850. return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
  4851. }
  4852. };
  4853. if (!IsDbgDeclare) {
  4854. // ArgDbgValues are hoisted to the beginning of the entry block. So we
  4855. // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
  4856. // the entry block.
  4857. bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
  4858. if (!IsInEntryBlock)
  4859. return false;
  4860. // ArgDbgValues are hoisted to the beginning of the entry block. So we
  4861. // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
  4862. // variable that also is a param.
  4863. //
  4864. // Although, if we are at the top of the entry block already, we can still
  4865. // emit using ArgDbgValue. This might catch some situations when the
  4866. // dbg.value refers to an argument that isn't used in the entry block, so
  4867. // any CopyToReg node would be optimized out and the only way to express
  4868. // this DBG_VALUE is by using the physical reg (or FI) as done in this
  4869. // method. ArgDbgValues are hoisted to the beginning of the entry block. So
  4870. // we should only emit as ArgDbgValue if the Variable is an argument to the
  4871. // current function, and the dbg.value intrinsic is found in the entry
  4872. // block.
  4873. bool VariableIsFunctionInputArg = Variable->isParameter() &&
  4874. !DL->getInlinedAt();
  4875. bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
  4876. if (!IsInPrologue && !VariableIsFunctionInputArg)
  4877. return false;
  4878. // Here we assume that a function argument on IR level only can be used to
  4879. // describe one input parameter on source level. If we for example have
  4880. // source code like this
  4881. //
  4882. // struct A { long x, y; };
  4883. // void foo(struct A a, long b) {
  4884. // ...
  4885. // b = a.x;
  4886. // ...
  4887. // }
  4888. //
  4889. // and IR like this
  4890. //
  4891. // define void @foo(i32 %a1, i32 %a2, i32 %b) {
  4892. // entry:
  4893. // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
  4894. // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
  4895. // call void @llvm.dbg.value(metadata i32 %b, "b",
  4896. // ...
  4897. // call void @llvm.dbg.value(metadata i32 %a1, "b"
  4898. // ...
  4899. //
  4900. // then the last dbg.value is describing a parameter "b" using a value that
  4901. // is an argument. But since we already has used %a1 to describe a parameter
  4902. // we should not handle that last dbg.value here (that would result in an
  4903. // incorrect hoisting of the DBG_VALUE to the function entry).
  4904. // Notice that we allow one dbg.value per IR level argument, to accommodate
  4905. // for the situation with fragments above.
  4906. if (VariableIsFunctionInputArg) {
  4907. unsigned ArgNo = Arg->getArgNo();
  4908. if (ArgNo >= FuncInfo.DescribedArgs.size())
  4909. FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
  4910. else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
  4911. return false;
  4912. FuncInfo.DescribedArgs.set(ArgNo);
  4913. }
  4914. }
  4915. bool IsIndirect = false;
  4916. Optional<MachineOperand> Op;
  4917. // Some arguments' frame index is recorded during argument lowering.
  4918. int FI = FuncInfo.getArgumentFrameIndex(Arg);
  4919. if (FI != std::numeric_limits<int>::max())
  4920. Op = MachineOperand::CreateFI(FI);
  4921. SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
  4922. if (!Op && N.getNode()) {
  4923. getUnderlyingArgRegs(ArgRegsAndSizes, N);
  4924. Register Reg;
  4925. if (ArgRegsAndSizes.size() == 1)
  4926. Reg = ArgRegsAndSizes.front().first;
  4927. if (Reg && Reg.isVirtual()) {
  4928. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  4929. Register PR = RegInfo.getLiveInPhysReg(Reg);
  4930. if (PR)
  4931. Reg = PR;
  4932. }
  4933. if (Reg) {
  4934. Op = MachineOperand::CreateReg(Reg, false);
  4935. IsIndirect = IsDbgDeclare;
  4936. }
  4937. }
  4938. if (!Op && N.getNode()) {
  4939. // Check if frame index is available.
  4940. SDValue LCandidate = peekThroughBitcasts(N);
  4941. if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
  4942. if (FrameIndexSDNode *FINode =
  4943. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  4944. Op = MachineOperand::CreateFI(FINode->getIndex());
  4945. }
  4946. if (!Op) {
  4947. // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
  4948. auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
  4949. SplitRegs) {
  4950. unsigned Offset = 0;
  4951. for (const auto &RegAndSize : SplitRegs) {
  4952. // If the expression is already a fragment, the current register
  4953. // offset+size might extend beyond the fragment. In this case, only
  4954. // the register bits that are inside the fragment are relevant.
  4955. int RegFragmentSizeInBits = RegAndSize.second;
  4956. if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
  4957. uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
  4958. // The register is entirely outside the expression fragment,
  4959. // so is irrelevant for debug info.
  4960. if (Offset >= ExprFragmentSizeInBits)
  4961. break;
  4962. // The register is partially outside the expression fragment, only
  4963. // the low bits within the fragment are relevant for debug info.
  4964. if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
  4965. RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
  4966. }
  4967. }
  4968. auto FragmentExpr = DIExpression::createFragmentExpression(
  4969. Expr, Offset, RegFragmentSizeInBits);
  4970. Offset += RegAndSize.second;
  4971. // If a valid fragment expression cannot be created, the variable's
  4972. // correct value cannot be determined and so it is set as Undef.
  4973. if (!FragmentExpr) {
  4974. SDDbgValue *SDV = DAG.getConstantDbgValue(
  4975. Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
  4976. DAG.AddDbgValue(SDV, false);
  4977. continue;
  4978. }
  4979. MachineInstr *NewMI =
  4980. MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, IsDbgDeclare);
  4981. FuncInfo.ArgDbgValues.push_back(NewMI);
  4982. }
  4983. };
  4984. // Check if ValueMap has reg number.
  4985. DenseMap<const Value *, Register>::const_iterator
  4986. VMI = FuncInfo.ValueMap.find(V);
  4987. if (VMI != FuncInfo.ValueMap.end()) {
  4988. const auto &TLI = DAG.getTargetLoweringInfo();
  4989. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
  4990. V->getType(), None);
  4991. if (RFV.occupiesMultipleRegs()) {
  4992. splitMultiRegDbgValue(RFV.getRegsAndSizes());
  4993. return true;
  4994. }
  4995. Op = MachineOperand::CreateReg(VMI->second, false);
  4996. IsIndirect = IsDbgDeclare;
  4997. } else if (ArgRegsAndSizes.size() > 1) {
  4998. // This was split due to the calling convention, and no virtual register
  4999. // mapping exists for the value.
  5000. splitMultiRegDbgValue(ArgRegsAndSizes);
  5001. return true;
  5002. }
  5003. }
  5004. if (!Op)
  5005. return false;
  5006. assert(Variable->isValidLocationForIntrinsic(DL) &&
  5007. "Expected inlined-at fields to agree");
  5008. MachineInstr *NewMI = nullptr;
  5009. if (Op->isReg())
  5010. NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
  5011. else
  5012. NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
  5013. Variable, Expr);
  5014. FuncInfo.ArgDbgValues.push_back(NewMI);
  5015. return true;
  5016. }
  5017. /// Return the appropriate SDDbgValue based on N.
  5018. SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
  5019. DILocalVariable *Variable,
  5020. DIExpression *Expr,
  5021. const DebugLoc &dl,
  5022. unsigned DbgSDNodeOrder) {
  5023. if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
  5024. // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
  5025. // stack slot locations.
  5026. //
  5027. // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
  5028. // debug values here after optimization:
  5029. //
  5030. // dbg.value(i32* %px, !"int *px", !DIExpression()), and
  5031. // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
  5032. //
  5033. // Both describe the direct values of their associated variables.
  5034. return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
  5035. /*IsIndirect*/ false, dl, DbgSDNodeOrder);
  5036. }
  5037. return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
  5038. /*IsIndirect*/ false, dl, DbgSDNodeOrder);
  5039. }
  5040. static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
  5041. switch (Intrinsic) {
  5042. case Intrinsic::smul_fix:
  5043. return ISD::SMULFIX;
  5044. case Intrinsic::umul_fix:
  5045. return ISD::UMULFIX;
  5046. case Intrinsic::smul_fix_sat:
  5047. return ISD::SMULFIXSAT;
  5048. case Intrinsic::umul_fix_sat:
  5049. return ISD::UMULFIXSAT;
  5050. case Intrinsic::sdiv_fix:
  5051. return ISD::SDIVFIX;
  5052. case Intrinsic::udiv_fix:
  5053. return ISD::UDIVFIX;
  5054. case Intrinsic::sdiv_fix_sat:
  5055. return ISD::SDIVFIXSAT;
  5056. case Intrinsic::udiv_fix_sat:
  5057. return ISD::UDIVFIXSAT;
  5058. default:
  5059. llvm_unreachable("Unhandled fixed point intrinsic");
  5060. }
  5061. }
  5062. void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
  5063. const char *FunctionName) {
  5064. assert(FunctionName && "FunctionName must not be nullptr");
  5065. SDValue Callee = DAG.getExternalSymbol(
  5066. FunctionName,
  5067. DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
  5068. LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
  5069. }
  5070. /// Given a @llvm.call.preallocated.setup, return the corresponding
  5071. /// preallocated call.
  5072. static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
  5073. assert(cast<CallBase>(PreallocatedSetup)
  5074. ->getCalledFunction()
  5075. ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
  5076. "expected call_preallocated_setup Value");
  5077. for (auto *U : PreallocatedSetup->users()) {
  5078. auto *UseCall = cast<CallBase>(U);
  5079. const Function *Fn = UseCall->getCalledFunction();
  5080. if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
  5081. return UseCall;
  5082. }
  5083. }
  5084. llvm_unreachable("expected corresponding call to preallocated setup/arg");
  5085. }
  5086. /// Lower the call to the specified intrinsic function.
  5087. void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
  5088. unsigned Intrinsic) {
  5089. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5090. SDLoc sdl = getCurSDLoc();
  5091. DebugLoc dl = getCurDebugLoc();
  5092. SDValue Res;
  5093. SDNodeFlags Flags;
  5094. if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
  5095. Flags.copyFMF(*FPOp);
  5096. switch (Intrinsic) {
  5097. default:
  5098. // By default, turn this into a target intrinsic node.
  5099. visitTargetIntrinsic(I, Intrinsic);
  5100. return;
  5101. case Intrinsic::vscale: {
  5102. match(&I, m_VScale(DAG.getDataLayout()));
  5103. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5104. setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
  5105. return;
  5106. }
  5107. case Intrinsic::vastart: visitVAStart(I); return;
  5108. case Intrinsic::vaend: visitVAEnd(I); return;
  5109. case Intrinsic::vacopy: visitVACopy(I); return;
  5110. case Intrinsic::returnaddress:
  5111. setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
  5112. TLI.getPointerTy(DAG.getDataLayout()),
  5113. getValue(I.getArgOperand(0))));
  5114. return;
  5115. case Intrinsic::addressofreturnaddress:
  5116. setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
  5117. TLI.getPointerTy(DAG.getDataLayout())));
  5118. return;
  5119. case Intrinsic::sponentry:
  5120. setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
  5121. TLI.getFrameIndexTy(DAG.getDataLayout())));
  5122. return;
  5123. case Intrinsic::frameaddress:
  5124. setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
  5125. TLI.getFrameIndexTy(DAG.getDataLayout()),
  5126. getValue(I.getArgOperand(0))));
  5127. return;
  5128. case Intrinsic::read_volatile_register:
  5129. case Intrinsic::read_register: {
  5130. Value *Reg = I.getArgOperand(0);
  5131. SDValue Chain = getRoot();
  5132. SDValue RegName =
  5133. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  5134. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5135. Res = DAG.getNode(ISD::READ_REGISTER, sdl,
  5136. DAG.getVTList(VT, MVT::Other), Chain, RegName);
  5137. setValue(&I, Res);
  5138. DAG.setRoot(Res.getValue(1));
  5139. return;
  5140. }
  5141. case Intrinsic::write_register: {
  5142. Value *Reg = I.getArgOperand(0);
  5143. Value *RegValue = I.getArgOperand(1);
  5144. SDValue Chain = getRoot();
  5145. SDValue RegName =
  5146. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  5147. DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
  5148. RegName, getValue(RegValue)));
  5149. return;
  5150. }
  5151. case Intrinsic::memcpy: {
  5152. const auto &MCI = cast<MemCpyInst>(I);
  5153. SDValue Op1 = getValue(I.getArgOperand(0));
  5154. SDValue Op2 = getValue(I.getArgOperand(1));
  5155. SDValue Op3 = getValue(I.getArgOperand(2));
  5156. // @llvm.memcpy defines 0 and 1 to both mean no alignment.
  5157. Align DstAlign = MCI.getDestAlign().valueOrOne();
  5158. Align SrcAlign = MCI.getSourceAlign().valueOrOne();
  5159. Align Alignment = commonAlignment(DstAlign, SrcAlign);
  5160. bool isVol = MCI.isVolatile();
  5161. bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
  5162. // FIXME: Support passing different dest/src alignments to the memcpy DAG
  5163. // node.
  5164. SDValue Root = isVol ? getRoot() : getMemoryRoot();
  5165. SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
  5166. /* AlwaysInline */ false, isTC,
  5167. MachinePointerInfo(I.getArgOperand(0)),
  5168. MachinePointerInfo(I.getArgOperand(1)),
  5169. I.getAAMetadata());
  5170. updateDAGForMaybeTailCall(MC);
  5171. return;
  5172. }
  5173. case Intrinsic::memcpy_inline: {
  5174. const auto &MCI = cast<MemCpyInlineInst>(I);
  5175. SDValue Dst = getValue(I.getArgOperand(0));
  5176. SDValue Src = getValue(I.getArgOperand(1));
  5177. SDValue Size = getValue(I.getArgOperand(2));
  5178. assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
  5179. // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
  5180. Align DstAlign = MCI.getDestAlign().valueOrOne();
  5181. Align SrcAlign = MCI.getSourceAlign().valueOrOne();
  5182. Align Alignment = commonAlignment(DstAlign, SrcAlign);
  5183. bool isVol = MCI.isVolatile();
  5184. bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
  5185. // FIXME: Support passing different dest/src alignments to the memcpy DAG
  5186. // node.
  5187. SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
  5188. /* AlwaysInline */ true, isTC,
  5189. MachinePointerInfo(I.getArgOperand(0)),
  5190. MachinePointerInfo(I.getArgOperand(1)),
  5191. I.getAAMetadata());
  5192. updateDAGForMaybeTailCall(MC);
  5193. return;
  5194. }
  5195. case Intrinsic::memset: {
  5196. const auto &MSI = cast<MemSetInst>(I);
  5197. SDValue Op1 = getValue(I.getArgOperand(0));
  5198. SDValue Op2 = getValue(I.getArgOperand(1));
  5199. SDValue Op3 = getValue(I.getArgOperand(2));
  5200. // @llvm.memset defines 0 and 1 to both mean no alignment.
  5201. Align Alignment = MSI.getDestAlign().valueOrOne();
  5202. bool isVol = MSI.isVolatile();
  5203. bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
  5204. SDValue Root = isVol ? getRoot() : getMemoryRoot();
  5205. SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC,
  5206. MachinePointerInfo(I.getArgOperand(0)),
  5207. I.getAAMetadata());
  5208. updateDAGForMaybeTailCall(MS);
  5209. return;
  5210. }
  5211. case Intrinsic::memmove: {
  5212. const auto &MMI = cast<MemMoveInst>(I);
  5213. SDValue Op1 = getValue(I.getArgOperand(0));
  5214. SDValue Op2 = getValue(I.getArgOperand(1));
  5215. SDValue Op3 = getValue(I.getArgOperand(2));
  5216. // @llvm.memmove defines 0 and 1 to both mean no alignment.
  5217. Align DstAlign = MMI.getDestAlign().valueOrOne();
  5218. Align SrcAlign = MMI.getSourceAlign().valueOrOne();
  5219. Align Alignment = commonAlignment(DstAlign, SrcAlign);
  5220. bool isVol = MMI.isVolatile();
  5221. bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
  5222. // FIXME: Support passing different dest/src alignments to the memmove DAG
  5223. // node.
  5224. SDValue Root = isVol ? getRoot() : getMemoryRoot();
  5225. SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
  5226. isTC, MachinePointerInfo(I.getArgOperand(0)),
  5227. MachinePointerInfo(I.getArgOperand(1)),
  5228. I.getAAMetadata());
  5229. updateDAGForMaybeTailCall(MM);
  5230. return;
  5231. }
  5232. case Intrinsic::memcpy_element_unordered_atomic: {
  5233. const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
  5234. SDValue Dst = getValue(MI.getRawDest());
  5235. SDValue Src = getValue(MI.getRawSource());
  5236. SDValue Length = getValue(MI.getLength());
  5237. unsigned DstAlign = MI.getDestAlignment();
  5238. unsigned SrcAlign = MI.getSourceAlignment();
  5239. Type *LengthTy = MI.getLength()->getType();
  5240. unsigned ElemSz = MI.getElementSizeInBytes();
  5241. bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
  5242. SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
  5243. SrcAlign, Length, LengthTy, ElemSz, isTC,
  5244. MachinePointerInfo(MI.getRawDest()),
  5245. MachinePointerInfo(MI.getRawSource()));
  5246. updateDAGForMaybeTailCall(MC);
  5247. return;
  5248. }
  5249. case Intrinsic::memmove_element_unordered_atomic: {
  5250. auto &MI = cast<AtomicMemMoveInst>(I);
  5251. SDValue Dst = getValue(MI.getRawDest());
  5252. SDValue Src = getValue(MI.getRawSource());
  5253. SDValue Length = getValue(MI.getLength());
  5254. unsigned DstAlign = MI.getDestAlignment();
  5255. unsigned SrcAlign = MI.getSourceAlignment();
  5256. Type *LengthTy = MI.getLength()->getType();
  5257. unsigned ElemSz = MI.getElementSizeInBytes();
  5258. bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
  5259. SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
  5260. SrcAlign, Length, LengthTy, ElemSz, isTC,
  5261. MachinePointerInfo(MI.getRawDest()),
  5262. MachinePointerInfo(MI.getRawSource()));
  5263. updateDAGForMaybeTailCall(MC);
  5264. return;
  5265. }
  5266. case Intrinsic::memset_element_unordered_atomic: {
  5267. auto &MI = cast<AtomicMemSetInst>(I);
  5268. SDValue Dst = getValue(MI.getRawDest());
  5269. SDValue Val = getValue(MI.getValue());
  5270. SDValue Length = getValue(MI.getLength());
  5271. unsigned DstAlign = MI.getDestAlignment();
  5272. Type *LengthTy = MI.getLength()->getType();
  5273. unsigned ElemSz = MI.getElementSizeInBytes();
  5274. bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
  5275. SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
  5276. LengthTy, ElemSz, isTC,
  5277. MachinePointerInfo(MI.getRawDest()));
  5278. updateDAGForMaybeTailCall(MC);
  5279. return;
  5280. }
  5281. case Intrinsic::call_preallocated_setup: {
  5282. const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
  5283. SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
  5284. SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
  5285. getRoot(), SrcValue);
  5286. setValue(&I, Res);
  5287. DAG.setRoot(Res);
  5288. return;
  5289. }
  5290. case Intrinsic::call_preallocated_arg: {
  5291. const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
  5292. SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
  5293. SDValue Ops[3];
  5294. Ops[0] = getRoot();
  5295. Ops[1] = SrcValue;
  5296. Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
  5297. MVT::i32); // arg index
  5298. SDValue Res = DAG.getNode(
  5299. ISD::PREALLOCATED_ARG, sdl,
  5300. DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
  5301. setValue(&I, Res);
  5302. DAG.setRoot(Res.getValue(1));
  5303. return;
  5304. }
  5305. case Intrinsic::dbg_addr:
  5306. case Intrinsic::dbg_declare: {
  5307. // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e.
  5308. // they are non-variadic.
  5309. const auto &DI = cast<DbgVariableIntrinsic>(I);
  5310. assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
  5311. DILocalVariable *Variable = DI.getVariable();
  5312. DIExpression *Expression = DI.getExpression();
  5313. dropDanglingDebugInfo(Variable, Expression);
  5314. assert(Variable && "Missing variable");
  5315. LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
  5316. << "\n");
  5317. // Check if address has undef value.
  5318. const Value *Address = DI.getVariableLocationOp(0);
  5319. if (!Address || isa<UndefValue>(Address) ||
  5320. (Address->use_empty() && !isa<Argument>(Address))) {
  5321. LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
  5322. << " (bad/undef/unused-arg address)\n");
  5323. return;
  5324. }
  5325. bool isParameter = Variable->isParameter() || isa<Argument>(Address);
  5326. // Check if this variable can be described by a frame index, typically
  5327. // either as a static alloca or a byval parameter.
  5328. int FI = std::numeric_limits<int>::max();
  5329. if (const auto *AI =
  5330. dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
  5331. if (AI->isStaticAlloca()) {
  5332. auto I = FuncInfo.StaticAllocaMap.find(AI);
  5333. if (I != FuncInfo.StaticAllocaMap.end())
  5334. FI = I->second;
  5335. }
  5336. } else if (const auto *Arg = dyn_cast<Argument>(
  5337. Address->stripInBoundsConstantOffsets())) {
  5338. FI = FuncInfo.getArgumentFrameIndex(Arg);
  5339. }
  5340. // llvm.dbg.addr is control dependent and always generates indirect
  5341. // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
  5342. // the MachineFunction variable table.
  5343. if (FI != std::numeric_limits<int>::max()) {
  5344. if (Intrinsic == Intrinsic::dbg_addr) {
  5345. SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
  5346. Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true,
  5347. dl, SDNodeOrder);
  5348. DAG.AddDbgValue(SDV, isParameter);
  5349. } else {
  5350. LLVM_DEBUG(dbgs() << "Skipping " << DI
  5351. << " (variable info stashed in MF side table)\n");
  5352. }
  5353. return;
  5354. }
  5355. SDValue &N = NodeMap[Address];
  5356. if (!N.getNode() && isa<Argument>(Address))
  5357. // Check unused arguments map.
  5358. N = UnusedArgNodeMap[Address];
  5359. SDDbgValue *SDV;
  5360. if (N.getNode()) {
  5361. if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
  5362. Address = BCI->getOperand(0);
  5363. // Parameters are handled specially.
  5364. auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
  5365. if (isParameter && FINode) {
  5366. // Byval parameter. We have a frame index at this point.
  5367. SDV =
  5368. DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
  5369. /*IsIndirect*/ true, dl, SDNodeOrder);
  5370. } else if (isa<Argument>(Address)) {
  5371. // Address is an argument, so try to emit its dbg value using
  5372. // virtual register info from the FuncInfo.ValueMap.
  5373. EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
  5374. return;
  5375. } else {
  5376. SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
  5377. true, dl, SDNodeOrder);
  5378. }
  5379. DAG.AddDbgValue(SDV, isParameter);
  5380. } else {
  5381. // If Address is an argument then try to emit its dbg value using
  5382. // virtual register info from the FuncInfo.ValueMap.
  5383. if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
  5384. N)) {
  5385. LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
  5386. << " (could not emit func-arg dbg_value)\n");
  5387. }
  5388. }
  5389. return;
  5390. }
  5391. case Intrinsic::dbg_label: {
  5392. const DbgLabelInst &DI = cast<DbgLabelInst>(I);
  5393. DILabel *Label = DI.getLabel();
  5394. assert(Label && "Missing label");
  5395. SDDbgLabel *SDV;
  5396. SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
  5397. DAG.AddDbgLabel(SDV);
  5398. return;
  5399. }
  5400. case Intrinsic::dbg_value: {
  5401. const DbgValueInst &DI = cast<DbgValueInst>(I);
  5402. assert(DI.getVariable() && "Missing variable");
  5403. DILocalVariable *Variable = DI.getVariable();
  5404. DIExpression *Expression = DI.getExpression();
  5405. dropDanglingDebugInfo(Variable, Expression);
  5406. SmallVector<Value *, 4> Values(DI.getValues());
  5407. if (Values.empty())
  5408. return;
  5409. if (llvm::is_contained(Values, nullptr))
  5410. return;
  5411. bool IsVariadic = DI.hasArgList();
  5412. if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(),
  5413. SDNodeOrder, IsVariadic))
  5414. addDanglingDebugInfo(&DI, dl, SDNodeOrder);
  5415. return;
  5416. }
  5417. case Intrinsic::eh_typeid_for: {
  5418. // Find the type id for the given typeinfo.
  5419. GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
  5420. unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
  5421. Res = DAG.getConstant(TypeID, sdl, MVT::i32);
  5422. setValue(&I, Res);
  5423. return;
  5424. }
  5425. case Intrinsic::eh_return_i32:
  5426. case Intrinsic::eh_return_i64:
  5427. DAG.getMachineFunction().setCallsEHReturn(true);
  5428. DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
  5429. MVT::Other,
  5430. getControlRoot(),
  5431. getValue(I.getArgOperand(0)),
  5432. getValue(I.getArgOperand(1))));
  5433. return;
  5434. case Intrinsic::eh_unwind_init:
  5435. DAG.getMachineFunction().setCallsUnwindInit(true);
  5436. return;
  5437. case Intrinsic::eh_dwarf_cfa:
  5438. setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
  5439. TLI.getPointerTy(DAG.getDataLayout()),
  5440. getValue(I.getArgOperand(0))));
  5441. return;
  5442. case Intrinsic::eh_sjlj_callsite: {
  5443. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  5444. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
  5445. assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
  5446. assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
  5447. MMI.setCurrentCallSite(CI->getZExtValue());
  5448. return;
  5449. }
  5450. case Intrinsic::eh_sjlj_functioncontext: {
  5451. // Get and store the index of the function context.
  5452. MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
  5453. AllocaInst *FnCtx =
  5454. cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
  5455. int FI = FuncInfo.StaticAllocaMap[FnCtx];
  5456. MFI.setFunctionContextIndex(FI);
  5457. return;
  5458. }
  5459. case Intrinsic::eh_sjlj_setjmp: {
  5460. SDValue Ops[2];
  5461. Ops[0] = getRoot();
  5462. Ops[1] = getValue(I.getArgOperand(0));
  5463. SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
  5464. DAG.getVTList(MVT::i32, MVT::Other), Ops);
  5465. setValue(&I, Op.getValue(0));
  5466. DAG.setRoot(Op.getValue(1));
  5467. return;
  5468. }
  5469. case Intrinsic::eh_sjlj_longjmp:
  5470. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
  5471. getRoot(), getValue(I.getArgOperand(0))));
  5472. return;
  5473. case Intrinsic::eh_sjlj_setup_dispatch:
  5474. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
  5475. getRoot()));
  5476. return;
  5477. case Intrinsic::masked_gather:
  5478. visitMaskedGather(I);
  5479. return;
  5480. case Intrinsic::masked_load:
  5481. visitMaskedLoad(I);
  5482. return;
  5483. case Intrinsic::masked_scatter:
  5484. visitMaskedScatter(I);
  5485. return;
  5486. case Intrinsic::masked_store:
  5487. visitMaskedStore(I);
  5488. return;
  5489. case Intrinsic::masked_expandload:
  5490. visitMaskedLoad(I, true /* IsExpanding */);
  5491. return;
  5492. case Intrinsic::masked_compressstore:
  5493. visitMaskedStore(I, true /* IsCompressing */);
  5494. return;
  5495. case Intrinsic::powi:
  5496. setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
  5497. getValue(I.getArgOperand(1)), DAG));
  5498. return;
  5499. case Intrinsic::log:
  5500. setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
  5501. return;
  5502. case Intrinsic::log2:
  5503. setValue(&I,
  5504. expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
  5505. return;
  5506. case Intrinsic::log10:
  5507. setValue(&I,
  5508. expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
  5509. return;
  5510. case Intrinsic::exp:
  5511. setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
  5512. return;
  5513. case Intrinsic::exp2:
  5514. setValue(&I,
  5515. expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
  5516. return;
  5517. case Intrinsic::pow:
  5518. setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
  5519. getValue(I.getArgOperand(1)), DAG, TLI, Flags));
  5520. return;
  5521. case Intrinsic::sqrt:
  5522. case Intrinsic::fabs:
  5523. case Intrinsic::sin:
  5524. case Intrinsic::cos:
  5525. case Intrinsic::floor:
  5526. case Intrinsic::ceil:
  5527. case Intrinsic::trunc:
  5528. case Intrinsic::rint:
  5529. case Intrinsic::nearbyint:
  5530. case Intrinsic::round:
  5531. case Intrinsic::roundeven:
  5532. case Intrinsic::canonicalize: {
  5533. unsigned Opcode;
  5534. switch (Intrinsic) {
  5535. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5536. case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
  5537. case Intrinsic::fabs: Opcode = ISD::FABS; break;
  5538. case Intrinsic::sin: Opcode = ISD::FSIN; break;
  5539. case Intrinsic::cos: Opcode = ISD::FCOS; break;
  5540. case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
  5541. case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
  5542. case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
  5543. case Intrinsic::rint: Opcode = ISD::FRINT; break;
  5544. case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
  5545. case Intrinsic::round: Opcode = ISD::FROUND; break;
  5546. case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
  5547. case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
  5548. }
  5549. setValue(&I, DAG.getNode(Opcode, sdl,
  5550. getValue(I.getArgOperand(0)).getValueType(),
  5551. getValue(I.getArgOperand(0)), Flags));
  5552. return;
  5553. }
  5554. case Intrinsic::lround:
  5555. case Intrinsic::llround:
  5556. case Intrinsic::lrint:
  5557. case Intrinsic::llrint: {
  5558. unsigned Opcode;
  5559. switch (Intrinsic) {
  5560. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5561. case Intrinsic::lround: Opcode = ISD::LROUND; break;
  5562. case Intrinsic::llround: Opcode = ISD::LLROUND; break;
  5563. case Intrinsic::lrint: Opcode = ISD::LRINT; break;
  5564. case Intrinsic::llrint: Opcode = ISD::LLRINT; break;
  5565. }
  5566. EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5567. setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
  5568. getValue(I.getArgOperand(0))));
  5569. return;
  5570. }
  5571. case Intrinsic::minnum:
  5572. setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
  5573. getValue(I.getArgOperand(0)).getValueType(),
  5574. getValue(I.getArgOperand(0)),
  5575. getValue(I.getArgOperand(1)), Flags));
  5576. return;
  5577. case Intrinsic::maxnum:
  5578. setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
  5579. getValue(I.getArgOperand(0)).getValueType(),
  5580. getValue(I.getArgOperand(0)),
  5581. getValue(I.getArgOperand(1)), Flags));
  5582. return;
  5583. case Intrinsic::minimum:
  5584. setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
  5585. getValue(I.getArgOperand(0)).getValueType(),
  5586. getValue(I.getArgOperand(0)),
  5587. getValue(I.getArgOperand(1)), Flags));
  5588. return;
  5589. case Intrinsic::maximum:
  5590. setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
  5591. getValue(I.getArgOperand(0)).getValueType(),
  5592. getValue(I.getArgOperand(0)),
  5593. getValue(I.getArgOperand(1)), Flags));
  5594. return;
  5595. case Intrinsic::copysign:
  5596. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
  5597. getValue(I.getArgOperand(0)).getValueType(),
  5598. getValue(I.getArgOperand(0)),
  5599. getValue(I.getArgOperand(1)), Flags));
  5600. return;
  5601. case Intrinsic::arithmetic_fence: {
  5602. setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
  5603. getValue(I.getArgOperand(0)).getValueType(),
  5604. getValue(I.getArgOperand(0)), Flags));
  5605. return;
  5606. }
  5607. case Intrinsic::fma:
  5608. setValue(&I, DAG.getNode(
  5609. ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
  5610. getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
  5611. getValue(I.getArgOperand(2)), Flags));
  5612. return;
  5613. #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
  5614. case Intrinsic::INTRINSIC:
  5615. #include "llvm/IR/ConstrainedOps.def"
  5616. visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
  5617. return;
  5618. #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
  5619. #include "llvm/IR/VPIntrinsics.def"
  5620. visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
  5621. return;
  5622. case Intrinsic::fmuladd: {
  5623. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5624. if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
  5625. TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
  5626. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  5627. getValue(I.getArgOperand(0)).getValueType(),
  5628. getValue(I.getArgOperand(0)),
  5629. getValue(I.getArgOperand(1)),
  5630. getValue(I.getArgOperand(2)), Flags));
  5631. } else {
  5632. // TODO: Intrinsic calls should have fast-math-flags.
  5633. SDValue Mul = DAG.getNode(
  5634. ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
  5635. getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
  5636. SDValue Add = DAG.getNode(ISD::FADD, sdl,
  5637. getValue(I.getArgOperand(0)).getValueType(),
  5638. Mul, getValue(I.getArgOperand(2)), Flags);
  5639. setValue(&I, Add);
  5640. }
  5641. return;
  5642. }
  5643. case Intrinsic::convert_to_fp16:
  5644. setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
  5645. DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
  5646. getValue(I.getArgOperand(0)),
  5647. DAG.getTargetConstant(0, sdl,
  5648. MVT::i32))));
  5649. return;
  5650. case Intrinsic::convert_from_fp16:
  5651. setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
  5652. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  5653. DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
  5654. getValue(I.getArgOperand(0)))));
  5655. return;
  5656. case Intrinsic::fptosi_sat: {
  5657. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5658. setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
  5659. getValue(I.getArgOperand(0)),
  5660. DAG.getValueType(VT.getScalarType())));
  5661. return;
  5662. }
  5663. case Intrinsic::fptoui_sat: {
  5664. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5665. setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
  5666. getValue(I.getArgOperand(0)),
  5667. DAG.getValueType(VT.getScalarType())));
  5668. return;
  5669. }
  5670. case Intrinsic::set_rounding:
  5671. Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
  5672. {getRoot(), getValue(I.getArgOperand(0))});
  5673. setValue(&I, Res);
  5674. DAG.setRoot(Res.getValue(0));
  5675. return;
  5676. case Intrinsic::pcmarker: {
  5677. SDValue Tmp = getValue(I.getArgOperand(0));
  5678. DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
  5679. return;
  5680. }
  5681. case Intrinsic::readcyclecounter: {
  5682. SDValue Op = getRoot();
  5683. Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
  5684. DAG.getVTList(MVT::i64, MVT::Other), Op);
  5685. setValue(&I, Res);
  5686. DAG.setRoot(Res.getValue(1));
  5687. return;
  5688. }
  5689. case Intrinsic::bitreverse:
  5690. setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
  5691. getValue(I.getArgOperand(0)).getValueType(),
  5692. getValue(I.getArgOperand(0))));
  5693. return;
  5694. case Intrinsic::bswap:
  5695. setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
  5696. getValue(I.getArgOperand(0)).getValueType(),
  5697. getValue(I.getArgOperand(0))));
  5698. return;
  5699. case Intrinsic::cttz: {
  5700. SDValue Arg = getValue(I.getArgOperand(0));
  5701. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  5702. EVT Ty = Arg.getValueType();
  5703. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
  5704. sdl, Ty, Arg));
  5705. return;
  5706. }
  5707. case Intrinsic::ctlz: {
  5708. SDValue Arg = getValue(I.getArgOperand(0));
  5709. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  5710. EVT Ty = Arg.getValueType();
  5711. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
  5712. sdl, Ty, Arg));
  5713. return;
  5714. }
  5715. case Intrinsic::ctpop: {
  5716. SDValue Arg = getValue(I.getArgOperand(0));
  5717. EVT Ty = Arg.getValueType();
  5718. setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
  5719. return;
  5720. }
  5721. case Intrinsic::fshl:
  5722. case Intrinsic::fshr: {
  5723. bool IsFSHL = Intrinsic == Intrinsic::fshl;
  5724. SDValue X = getValue(I.getArgOperand(0));
  5725. SDValue Y = getValue(I.getArgOperand(1));
  5726. SDValue Z = getValue(I.getArgOperand(2));
  5727. EVT VT = X.getValueType();
  5728. if (X == Y) {
  5729. auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
  5730. setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
  5731. } else {
  5732. auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
  5733. setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
  5734. }
  5735. return;
  5736. }
  5737. case Intrinsic::sadd_sat: {
  5738. SDValue Op1 = getValue(I.getArgOperand(0));
  5739. SDValue Op2 = getValue(I.getArgOperand(1));
  5740. setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
  5741. return;
  5742. }
  5743. case Intrinsic::uadd_sat: {
  5744. SDValue Op1 = getValue(I.getArgOperand(0));
  5745. SDValue Op2 = getValue(I.getArgOperand(1));
  5746. setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
  5747. return;
  5748. }
  5749. case Intrinsic::ssub_sat: {
  5750. SDValue Op1 = getValue(I.getArgOperand(0));
  5751. SDValue Op2 = getValue(I.getArgOperand(1));
  5752. setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
  5753. return;
  5754. }
  5755. case Intrinsic::usub_sat: {
  5756. SDValue Op1 = getValue(I.getArgOperand(0));
  5757. SDValue Op2 = getValue(I.getArgOperand(1));
  5758. setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
  5759. return;
  5760. }
  5761. case Intrinsic::sshl_sat: {
  5762. SDValue Op1 = getValue(I.getArgOperand(0));
  5763. SDValue Op2 = getValue(I.getArgOperand(1));
  5764. setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
  5765. return;
  5766. }
  5767. case Intrinsic::ushl_sat: {
  5768. SDValue Op1 = getValue(I.getArgOperand(0));
  5769. SDValue Op2 = getValue(I.getArgOperand(1));
  5770. setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
  5771. return;
  5772. }
  5773. case Intrinsic::smul_fix:
  5774. case Intrinsic::umul_fix:
  5775. case Intrinsic::smul_fix_sat:
  5776. case Intrinsic::umul_fix_sat: {
  5777. SDValue Op1 = getValue(I.getArgOperand(0));
  5778. SDValue Op2 = getValue(I.getArgOperand(1));
  5779. SDValue Op3 = getValue(I.getArgOperand(2));
  5780. setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
  5781. Op1.getValueType(), Op1, Op2, Op3));
  5782. return;
  5783. }
  5784. case Intrinsic::sdiv_fix:
  5785. case Intrinsic::udiv_fix:
  5786. case Intrinsic::sdiv_fix_sat:
  5787. case Intrinsic::udiv_fix_sat: {
  5788. SDValue Op1 = getValue(I.getArgOperand(0));
  5789. SDValue Op2 = getValue(I.getArgOperand(1));
  5790. SDValue Op3 = getValue(I.getArgOperand(2));
  5791. setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
  5792. Op1, Op2, Op3, DAG, TLI));
  5793. return;
  5794. }
  5795. case Intrinsic::smax: {
  5796. SDValue Op1 = getValue(I.getArgOperand(0));
  5797. SDValue Op2 = getValue(I.getArgOperand(1));
  5798. setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
  5799. return;
  5800. }
  5801. case Intrinsic::smin: {
  5802. SDValue Op1 = getValue(I.getArgOperand(0));
  5803. SDValue Op2 = getValue(I.getArgOperand(1));
  5804. setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
  5805. return;
  5806. }
  5807. case Intrinsic::umax: {
  5808. SDValue Op1 = getValue(I.getArgOperand(0));
  5809. SDValue Op2 = getValue(I.getArgOperand(1));
  5810. setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
  5811. return;
  5812. }
  5813. case Intrinsic::umin: {
  5814. SDValue Op1 = getValue(I.getArgOperand(0));
  5815. SDValue Op2 = getValue(I.getArgOperand(1));
  5816. setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
  5817. return;
  5818. }
  5819. case Intrinsic::abs: {
  5820. // TODO: Preserve "int min is poison" arg in SDAG?
  5821. SDValue Op1 = getValue(I.getArgOperand(0));
  5822. setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
  5823. return;
  5824. }
  5825. case Intrinsic::stacksave: {
  5826. SDValue Op = getRoot();
  5827. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5828. Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
  5829. setValue(&I, Res);
  5830. DAG.setRoot(Res.getValue(1));
  5831. return;
  5832. }
  5833. case Intrinsic::stackrestore:
  5834. Res = getValue(I.getArgOperand(0));
  5835. DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
  5836. return;
  5837. case Intrinsic::get_dynamic_area_offset: {
  5838. SDValue Op = getRoot();
  5839. EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
  5840. EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5841. // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
  5842. // target.
  5843. if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
  5844. report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
  5845. " intrinsic!");
  5846. Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
  5847. Op);
  5848. DAG.setRoot(Op);
  5849. setValue(&I, Res);
  5850. return;
  5851. }
  5852. case Intrinsic::stackguard: {
  5853. MachineFunction &MF = DAG.getMachineFunction();
  5854. const Module &M = *MF.getFunction().getParent();
  5855. SDValue Chain = getRoot();
  5856. if (TLI.useLoadStackGuardNode()) {
  5857. Res = getLoadStackGuard(DAG, sdl, Chain);
  5858. } else {
  5859. EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5860. const Value *Global = TLI.getSDagStackGuard(M);
  5861. Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
  5862. Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
  5863. MachinePointerInfo(Global, 0), Align,
  5864. MachineMemOperand::MOVolatile);
  5865. }
  5866. if (TLI.useStackGuardXorFP())
  5867. Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
  5868. DAG.setRoot(Chain);
  5869. setValue(&I, Res);
  5870. return;
  5871. }
  5872. case Intrinsic::stackprotector: {
  5873. // Emit code into the DAG to store the stack guard onto the stack.
  5874. MachineFunction &MF = DAG.getMachineFunction();
  5875. MachineFrameInfo &MFI = MF.getFrameInfo();
  5876. SDValue Src, Chain = getRoot();
  5877. if (TLI.useLoadStackGuardNode())
  5878. Src = getLoadStackGuard(DAG, sdl, Chain);
  5879. else
  5880. Src = getValue(I.getArgOperand(0)); // The guard's value.
  5881. AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
  5882. int FI = FuncInfo.StaticAllocaMap[Slot];
  5883. MFI.setStackProtectorIndex(FI);
  5884. EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
  5885. SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
  5886. // Store the stack protector onto the stack.
  5887. Res = DAG.getStore(
  5888. Chain, sdl, Src, FIN,
  5889. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
  5890. MaybeAlign(), MachineMemOperand::MOVolatile);
  5891. setValue(&I, Res);
  5892. DAG.setRoot(Res);
  5893. return;
  5894. }
  5895. case Intrinsic::objectsize:
  5896. llvm_unreachable("llvm.objectsize.* should have been lowered already");
  5897. case Intrinsic::is_constant:
  5898. llvm_unreachable("llvm.is.constant.* should have been lowered already");
  5899. case Intrinsic::annotation:
  5900. case Intrinsic::ptr_annotation:
  5901. case Intrinsic::launder_invariant_group:
  5902. case Intrinsic::strip_invariant_group:
  5903. // Drop the intrinsic, but forward the value
  5904. setValue(&I, getValue(I.getOperand(0)));
  5905. return;
  5906. case Intrinsic::assume:
  5907. case Intrinsic::experimental_noalias_scope_decl:
  5908. case Intrinsic::var_annotation:
  5909. case Intrinsic::sideeffect:
  5910. // Discard annotate attributes, noalias scope declarations, assumptions, and
  5911. // artificial side-effects.
  5912. return;
  5913. case Intrinsic::codeview_annotation: {
  5914. // Emit a label associated with this metadata.
  5915. MachineFunction &MF = DAG.getMachineFunction();
  5916. MCSymbol *Label =
  5917. MF.getMMI().getContext().createTempSymbol("annotation", true);
  5918. Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
  5919. MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
  5920. Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
  5921. DAG.setRoot(Res);
  5922. return;
  5923. }
  5924. case Intrinsic::init_trampoline: {
  5925. const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
  5926. SDValue Ops[6];
  5927. Ops[0] = getRoot();
  5928. Ops[1] = getValue(I.getArgOperand(0));
  5929. Ops[2] = getValue(I.getArgOperand(1));
  5930. Ops[3] = getValue(I.getArgOperand(2));
  5931. Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
  5932. Ops[5] = DAG.getSrcValue(F);
  5933. Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
  5934. DAG.setRoot(Res);
  5935. return;
  5936. }
  5937. case Intrinsic::adjust_trampoline:
  5938. setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
  5939. TLI.getPointerTy(DAG.getDataLayout()),
  5940. getValue(I.getArgOperand(0))));
  5941. return;
  5942. case Intrinsic::gcroot: {
  5943. assert(DAG.getMachineFunction().getFunction().hasGC() &&
  5944. "only valid in functions with gc specified, enforced by Verifier");
  5945. assert(GFI && "implied by previous");
  5946. const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
  5947. const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
  5948. FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
  5949. GFI->addStackRoot(FI->getIndex(), TypeMap);
  5950. return;
  5951. }
  5952. case Intrinsic::gcread:
  5953. case Intrinsic::gcwrite:
  5954. llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
  5955. case Intrinsic::flt_rounds:
  5956. Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
  5957. setValue(&I, Res);
  5958. DAG.setRoot(Res.getValue(1));
  5959. return;
  5960. case Intrinsic::expect:
  5961. // Just replace __builtin_expect(exp, c) with EXP.
  5962. setValue(&I, getValue(I.getArgOperand(0)));
  5963. return;
  5964. case Intrinsic::ubsantrap:
  5965. case Intrinsic::debugtrap:
  5966. case Intrinsic::trap: {
  5967. StringRef TrapFuncName =
  5968. I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
  5969. if (TrapFuncName.empty()) {
  5970. switch (Intrinsic) {
  5971. case Intrinsic::trap:
  5972. DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
  5973. break;
  5974. case Intrinsic::debugtrap:
  5975. DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
  5976. break;
  5977. case Intrinsic::ubsantrap:
  5978. DAG.setRoot(DAG.getNode(
  5979. ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
  5980. DAG.getTargetConstant(
  5981. cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
  5982. MVT::i32)));
  5983. break;
  5984. default: llvm_unreachable("unknown trap intrinsic");
  5985. }
  5986. return;
  5987. }
  5988. TargetLowering::ArgListTy Args;
  5989. if (Intrinsic == Intrinsic::ubsantrap) {
  5990. Args.push_back(TargetLoweringBase::ArgListEntry());
  5991. Args[0].Val = I.getArgOperand(0);
  5992. Args[0].Node = getValue(Args[0].Val);
  5993. Args[0].Ty = Args[0].Val->getType();
  5994. }
  5995. TargetLowering::CallLoweringInfo CLI(DAG);
  5996. CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
  5997. CallingConv::C, I.getType(),
  5998. DAG.getExternalSymbol(TrapFuncName.data(),
  5999. TLI.getPointerTy(DAG.getDataLayout())),
  6000. std::move(Args));
  6001. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  6002. DAG.setRoot(Result.second);
  6003. return;
  6004. }
  6005. case Intrinsic::uadd_with_overflow:
  6006. case Intrinsic::sadd_with_overflow:
  6007. case Intrinsic::usub_with_overflow:
  6008. case Intrinsic::ssub_with_overflow:
  6009. case Intrinsic::umul_with_overflow:
  6010. case Intrinsic::smul_with_overflow: {
  6011. ISD::NodeType Op;
  6012. switch (Intrinsic) {
  6013. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  6014. case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
  6015. case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
  6016. case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
  6017. case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
  6018. case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
  6019. case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
  6020. }
  6021. SDValue Op1 = getValue(I.getArgOperand(0));
  6022. SDValue Op2 = getValue(I.getArgOperand(1));
  6023. EVT ResultVT = Op1.getValueType();
  6024. EVT OverflowVT = MVT::i1;
  6025. if (ResultVT.isVector())
  6026. OverflowVT = EVT::getVectorVT(
  6027. *Context, OverflowVT, ResultVT.getVectorElementCount());
  6028. SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
  6029. setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
  6030. return;
  6031. }
  6032. case Intrinsic::prefetch: {
  6033. SDValue Ops[5];
  6034. unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  6035. auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
  6036. Ops[0] = DAG.getRoot();
  6037. Ops[1] = getValue(I.getArgOperand(0));
  6038. Ops[2] = getValue(I.getArgOperand(1));
  6039. Ops[3] = getValue(I.getArgOperand(2));
  6040. Ops[4] = getValue(I.getArgOperand(3));
  6041. SDValue Result = DAG.getMemIntrinsicNode(
  6042. ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
  6043. EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
  6044. /* align */ None, Flags);
  6045. // Chain the prefetch in parallell with any pending loads, to stay out of
  6046. // the way of later optimizations.
  6047. PendingLoads.push_back(Result);
  6048. Result = getRoot();
  6049. DAG.setRoot(Result);
  6050. return;
  6051. }
  6052. case Intrinsic::lifetime_start:
  6053. case Intrinsic::lifetime_end: {
  6054. bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
  6055. // Stack coloring is not enabled in O0, discard region information.
  6056. if (TM.getOptLevel() == CodeGenOpt::None)
  6057. return;
  6058. const int64_t ObjectSize =
  6059. cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
  6060. Value *const ObjectPtr = I.getArgOperand(1);
  6061. SmallVector<const Value *, 4> Allocas;
  6062. getUnderlyingObjects(ObjectPtr, Allocas);
  6063. for (const Value *Alloca : Allocas) {
  6064. const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
  6065. // Could not find an Alloca.
  6066. if (!LifetimeObject)
  6067. continue;
  6068. // First check that the Alloca is static, otherwise it won't have a
  6069. // valid frame index.
  6070. auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
  6071. if (SI == FuncInfo.StaticAllocaMap.end())
  6072. return;
  6073. const int FrameIndex = SI->second;
  6074. int64_t Offset;
  6075. if (GetPointerBaseWithConstantOffset(
  6076. ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
  6077. Offset = -1; // Cannot determine offset from alloca to lifetime object.
  6078. Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
  6079. Offset);
  6080. DAG.setRoot(Res);
  6081. }
  6082. return;
  6083. }
  6084. case Intrinsic::pseudoprobe: {
  6085. auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
  6086. auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  6087. auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
  6088. Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
  6089. DAG.setRoot(Res);
  6090. return;
  6091. }
  6092. case Intrinsic::invariant_start:
  6093. // Discard region information.
  6094. setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
  6095. return;
  6096. case Intrinsic::invariant_end:
  6097. // Discard region information.
  6098. return;
  6099. case Intrinsic::clear_cache:
  6100. /// FunctionName may be null.
  6101. if (const char *FunctionName = TLI.getClearCacheBuiltinName())
  6102. lowerCallToExternalSymbol(I, FunctionName);
  6103. return;
  6104. case Intrinsic::donothing:
  6105. case Intrinsic::seh_try_begin:
  6106. case Intrinsic::seh_scope_begin:
  6107. case Intrinsic::seh_try_end:
  6108. case Intrinsic::seh_scope_end:
  6109. // ignore
  6110. return;
  6111. case Intrinsic::experimental_stackmap:
  6112. visitStackmap(I);
  6113. return;
  6114. case Intrinsic::experimental_patchpoint_void:
  6115. case Intrinsic::experimental_patchpoint_i64:
  6116. visitPatchpoint(I);
  6117. return;
  6118. case Intrinsic::experimental_gc_statepoint:
  6119. LowerStatepoint(cast<GCStatepointInst>(I));
  6120. return;
  6121. case Intrinsic::experimental_gc_result:
  6122. visitGCResult(cast<GCResultInst>(I));
  6123. return;
  6124. case Intrinsic::experimental_gc_relocate:
  6125. visitGCRelocate(cast<GCRelocateInst>(I));
  6126. return;
  6127. case Intrinsic::instrprof_cover:
  6128. llvm_unreachable("instrprof failed to lower a cover");
  6129. case Intrinsic::instrprof_increment:
  6130. llvm_unreachable("instrprof failed to lower an increment");
  6131. case Intrinsic::instrprof_value_profile:
  6132. llvm_unreachable("instrprof failed to lower a value profiling call");
  6133. case Intrinsic::localescape: {
  6134. MachineFunction &MF = DAG.getMachineFunction();
  6135. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  6136. // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
  6137. // is the same on all targets.
  6138. for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
  6139. Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
  6140. if (isa<ConstantPointerNull>(Arg))
  6141. continue; // Skip null pointers. They represent a hole in index space.
  6142. AllocaInst *Slot = cast<AllocaInst>(Arg);
  6143. assert(FuncInfo.StaticAllocaMap.count(Slot) &&
  6144. "can only escape static allocas");
  6145. int FI = FuncInfo.StaticAllocaMap[Slot];
  6146. MCSymbol *FrameAllocSym =
  6147. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  6148. GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
  6149. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
  6150. TII->get(TargetOpcode::LOCAL_ESCAPE))
  6151. .addSym(FrameAllocSym)
  6152. .addFrameIndex(FI);
  6153. }
  6154. return;
  6155. }
  6156. case Intrinsic::localrecover: {
  6157. // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
  6158. MachineFunction &MF = DAG.getMachineFunction();
  6159. // Get the symbol that defines the frame offset.
  6160. auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
  6161. auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
  6162. unsigned IdxVal =
  6163. unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
  6164. MCSymbol *FrameAllocSym =
  6165. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  6166. GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
  6167. Value *FP = I.getArgOperand(1);
  6168. SDValue FPVal = getValue(FP);
  6169. EVT PtrVT = FPVal.getValueType();
  6170. // Create a MCSymbol for the label to avoid any target lowering
  6171. // that would make this PC relative.
  6172. SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
  6173. SDValue OffsetVal =
  6174. DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
  6175. // Add the offset to the FP.
  6176. SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
  6177. setValue(&I, Add);
  6178. return;
  6179. }
  6180. case Intrinsic::eh_exceptionpointer:
  6181. case Intrinsic::eh_exceptioncode: {
  6182. // Get the exception pointer vreg, copy from it, and resize it to fit.
  6183. const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
  6184. MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
  6185. const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
  6186. unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
  6187. SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
  6188. if (Intrinsic == Intrinsic::eh_exceptioncode)
  6189. N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
  6190. setValue(&I, N);
  6191. return;
  6192. }
  6193. case Intrinsic::xray_customevent: {
  6194. // Here we want to make sure that the intrinsic behaves as if it has a
  6195. // specific calling convention, and only for x86_64.
  6196. // FIXME: Support other platforms later.
  6197. const auto &Triple = DAG.getTarget().getTargetTriple();
  6198. if (Triple.getArch() != Triple::x86_64)
  6199. return;
  6200. SmallVector<SDValue, 8> Ops;
  6201. // We want to say that we always want the arguments in registers.
  6202. SDValue LogEntryVal = getValue(I.getArgOperand(0));
  6203. SDValue StrSizeVal = getValue(I.getArgOperand(1));
  6204. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  6205. SDValue Chain = getRoot();
  6206. Ops.push_back(LogEntryVal);
  6207. Ops.push_back(StrSizeVal);
  6208. Ops.push_back(Chain);
  6209. // We need to enforce the calling convention for the callsite, so that
  6210. // argument ordering is enforced correctly, and that register allocation can
  6211. // see that some registers may be assumed clobbered and have to preserve
  6212. // them across calls to the intrinsic.
  6213. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
  6214. sdl, NodeTys, Ops);
  6215. SDValue patchableNode = SDValue(MN, 0);
  6216. DAG.setRoot(patchableNode);
  6217. setValue(&I, patchableNode);
  6218. return;
  6219. }
  6220. case Intrinsic::xray_typedevent: {
  6221. // Here we want to make sure that the intrinsic behaves as if it has a
  6222. // specific calling convention, and only for x86_64.
  6223. // FIXME: Support other platforms later.
  6224. const auto &Triple = DAG.getTarget().getTargetTriple();
  6225. if (Triple.getArch() != Triple::x86_64)
  6226. return;
  6227. SmallVector<SDValue, 8> Ops;
  6228. // We want to say that we always want the arguments in registers.
  6229. // It's unclear to me how manipulating the selection DAG here forces callers
  6230. // to provide arguments in registers instead of on the stack.
  6231. SDValue LogTypeId = getValue(I.getArgOperand(0));
  6232. SDValue LogEntryVal = getValue(I.getArgOperand(1));
  6233. SDValue StrSizeVal = getValue(I.getArgOperand(2));
  6234. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  6235. SDValue Chain = getRoot();
  6236. Ops.push_back(LogTypeId);
  6237. Ops.push_back(LogEntryVal);
  6238. Ops.push_back(StrSizeVal);
  6239. Ops.push_back(Chain);
  6240. // We need to enforce the calling convention for the callsite, so that
  6241. // argument ordering is enforced correctly, and that register allocation can
  6242. // see that some registers may be assumed clobbered and have to preserve
  6243. // them across calls to the intrinsic.
  6244. MachineSDNode *MN = DAG.getMachineNode(
  6245. TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
  6246. SDValue patchableNode = SDValue(MN, 0);
  6247. DAG.setRoot(patchableNode);
  6248. setValue(&I, patchableNode);
  6249. return;
  6250. }
  6251. case Intrinsic::experimental_deoptimize:
  6252. LowerDeoptimizeCall(&I);
  6253. return;
  6254. case Intrinsic::experimental_stepvector:
  6255. visitStepVector(I);
  6256. return;
  6257. case Intrinsic::vector_reduce_fadd:
  6258. case Intrinsic::vector_reduce_fmul:
  6259. case Intrinsic::vector_reduce_add:
  6260. case Intrinsic::vector_reduce_mul:
  6261. case Intrinsic::vector_reduce_and:
  6262. case Intrinsic::vector_reduce_or:
  6263. case Intrinsic::vector_reduce_xor:
  6264. case Intrinsic::vector_reduce_smax:
  6265. case Intrinsic::vector_reduce_smin:
  6266. case Intrinsic::vector_reduce_umax:
  6267. case Intrinsic::vector_reduce_umin:
  6268. case Intrinsic::vector_reduce_fmax:
  6269. case Intrinsic::vector_reduce_fmin:
  6270. visitVectorReduce(I, Intrinsic);
  6271. return;
  6272. case Intrinsic::icall_branch_funnel: {
  6273. SmallVector<SDValue, 16> Ops;
  6274. Ops.push_back(getValue(I.getArgOperand(0)));
  6275. int64_t Offset;
  6276. auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
  6277. I.getArgOperand(1), Offset, DAG.getDataLayout()));
  6278. if (!Base)
  6279. report_fatal_error(
  6280. "llvm.icall.branch.funnel operand must be a GlobalValue");
  6281. Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
  6282. struct BranchFunnelTarget {
  6283. int64_t Offset;
  6284. SDValue Target;
  6285. };
  6286. SmallVector<BranchFunnelTarget, 8> Targets;
  6287. for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
  6288. auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
  6289. I.getArgOperand(Op), Offset, DAG.getDataLayout()));
  6290. if (ElemBase != Base)
  6291. report_fatal_error("all llvm.icall.branch.funnel operands must refer "
  6292. "to the same GlobalValue");
  6293. SDValue Val = getValue(I.getArgOperand(Op + 1));
  6294. auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
  6295. if (!GA)
  6296. report_fatal_error(
  6297. "llvm.icall.branch.funnel operand must be a GlobalValue");
  6298. Targets.push_back({Offset, DAG.getTargetGlobalAddress(
  6299. GA->getGlobal(), sdl, Val.getValueType(),
  6300. GA->getOffset())});
  6301. }
  6302. llvm::sort(Targets,
  6303. [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
  6304. return T1.Offset < T2.Offset;
  6305. });
  6306. for (auto &T : Targets) {
  6307. Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
  6308. Ops.push_back(T.Target);
  6309. }
  6310. Ops.push_back(DAG.getRoot()); // Chain
  6311. SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
  6312. MVT::Other, Ops),
  6313. 0);
  6314. DAG.setRoot(N);
  6315. setValue(&I, N);
  6316. HasTailCall = true;
  6317. return;
  6318. }
  6319. case Intrinsic::wasm_landingpad_index:
  6320. // Information this intrinsic contained has been transferred to
  6321. // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
  6322. // delete it now.
  6323. return;
  6324. case Intrinsic::aarch64_settag:
  6325. case Intrinsic::aarch64_settag_zero: {
  6326. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6327. bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
  6328. SDValue Val = TSI.EmitTargetCodeForSetTag(
  6329. DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
  6330. getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
  6331. ZeroMemory);
  6332. DAG.setRoot(Val);
  6333. setValue(&I, Val);
  6334. return;
  6335. }
  6336. case Intrinsic::ptrmask: {
  6337. SDValue Ptr = getValue(I.getOperand(0));
  6338. SDValue Const = getValue(I.getOperand(1));
  6339. EVT PtrVT = Ptr.getValueType();
  6340. setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr,
  6341. DAG.getZExtOrTrunc(Const, sdl, PtrVT)));
  6342. return;
  6343. }
  6344. case Intrinsic::get_active_lane_mask: {
  6345. EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  6346. SDValue Index = getValue(I.getOperand(0));
  6347. EVT ElementVT = Index.getValueType();
  6348. if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
  6349. visitTargetIntrinsic(I, Intrinsic);
  6350. return;
  6351. }
  6352. SDValue TripCount = getValue(I.getOperand(1));
  6353. auto VecTy = CCVT.changeVectorElementType(ElementVT);
  6354. SDValue VectorIndex, VectorTripCount;
  6355. if (VecTy.isScalableVector()) {
  6356. VectorIndex = DAG.getSplatVector(VecTy, sdl, Index);
  6357. VectorTripCount = DAG.getSplatVector(VecTy, sdl, TripCount);
  6358. } else {
  6359. VectorIndex = DAG.getSplatBuildVector(VecTy, sdl, Index);
  6360. VectorTripCount = DAG.getSplatBuildVector(VecTy, sdl, TripCount);
  6361. }
  6362. SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
  6363. SDValue VectorInduction = DAG.getNode(
  6364. ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
  6365. SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
  6366. VectorTripCount, ISD::CondCode::SETULT);
  6367. setValue(&I, SetCC);
  6368. return;
  6369. }
  6370. case Intrinsic::experimental_vector_insert: {
  6371. SDValue Vec = getValue(I.getOperand(0));
  6372. SDValue SubVec = getValue(I.getOperand(1));
  6373. SDValue Index = getValue(I.getOperand(2));
  6374. // The intrinsic's index type is i64, but the SDNode requires an index type
  6375. // suitable for the target. Convert the index as required.
  6376. MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
  6377. if (Index.getValueType() != VectorIdxTy)
  6378. Index = DAG.getVectorIdxConstant(
  6379. cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
  6380. EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  6381. setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
  6382. Index));
  6383. return;
  6384. }
  6385. case Intrinsic::experimental_vector_extract: {
  6386. SDValue Vec = getValue(I.getOperand(0));
  6387. SDValue Index = getValue(I.getOperand(1));
  6388. EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  6389. // The intrinsic's index type is i64, but the SDNode requires an index type
  6390. // suitable for the target. Convert the index as required.
  6391. MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
  6392. if (Index.getValueType() != VectorIdxTy)
  6393. Index = DAG.getVectorIdxConstant(
  6394. cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
  6395. setValue(&I,
  6396. DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
  6397. return;
  6398. }
  6399. case Intrinsic::experimental_vector_reverse:
  6400. visitVectorReverse(I);
  6401. return;
  6402. case Intrinsic::experimental_vector_splice:
  6403. visitVectorSplice(I);
  6404. return;
  6405. }
  6406. }
  6407. void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
  6408. const ConstrainedFPIntrinsic &FPI) {
  6409. SDLoc sdl = getCurSDLoc();
  6410. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6411. SmallVector<EVT, 4> ValueVTs;
  6412. ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
  6413. ValueVTs.push_back(MVT::Other); // Out chain
  6414. // We do not need to serialize constrained FP intrinsics against
  6415. // each other or against (nonvolatile) loads, so they can be
  6416. // chained like loads.
  6417. SDValue Chain = DAG.getRoot();
  6418. SmallVector<SDValue, 4> Opers;
  6419. Opers.push_back(Chain);
  6420. if (FPI.isUnaryOp()) {
  6421. Opers.push_back(getValue(FPI.getArgOperand(0)));
  6422. } else if (FPI.isTernaryOp()) {
  6423. Opers.push_back(getValue(FPI.getArgOperand(0)));
  6424. Opers.push_back(getValue(FPI.getArgOperand(1)));
  6425. Opers.push_back(getValue(FPI.getArgOperand(2)));
  6426. } else {
  6427. Opers.push_back(getValue(FPI.getArgOperand(0)));
  6428. Opers.push_back(getValue(FPI.getArgOperand(1)));
  6429. }
  6430. auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
  6431. assert(Result.getNode()->getNumValues() == 2);
  6432. // Push node to the appropriate list so that future instructions can be
  6433. // chained up correctly.
  6434. SDValue OutChain = Result.getValue(1);
  6435. switch (EB) {
  6436. case fp::ExceptionBehavior::ebIgnore:
  6437. // The only reason why ebIgnore nodes still need to be chained is that
  6438. // they might depend on the current rounding mode, and therefore must
  6439. // not be moved across instruction that may change that mode.
  6440. LLVM_FALLTHROUGH;
  6441. case fp::ExceptionBehavior::ebMayTrap:
  6442. // These must not be moved across calls or instructions that may change
  6443. // floating-point exception masks.
  6444. PendingConstrainedFP.push_back(OutChain);
  6445. break;
  6446. case fp::ExceptionBehavior::ebStrict:
  6447. // These must not be moved across calls or instructions that may change
  6448. // floating-point exception masks or read floating-point exception flags.
  6449. // In addition, they cannot be optimized out even if unused.
  6450. PendingConstrainedFPStrict.push_back(OutChain);
  6451. break;
  6452. }
  6453. };
  6454. SDVTList VTs = DAG.getVTList(ValueVTs);
  6455. fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
  6456. SDNodeFlags Flags;
  6457. if (EB == fp::ExceptionBehavior::ebIgnore)
  6458. Flags.setNoFPExcept(true);
  6459. if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
  6460. Flags.copyFMF(*FPOp);
  6461. unsigned Opcode;
  6462. switch (FPI.getIntrinsicID()) {
  6463. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  6464. #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
  6465. case Intrinsic::INTRINSIC: \
  6466. Opcode = ISD::STRICT_##DAGN; \
  6467. break;
  6468. #include "llvm/IR/ConstrainedOps.def"
  6469. case Intrinsic::experimental_constrained_fmuladd: {
  6470. Opcode = ISD::STRICT_FMA;
  6471. // Break fmuladd into fmul and fadd.
  6472. if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
  6473. !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(),
  6474. ValueVTs[0])) {
  6475. Opers.pop_back();
  6476. SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
  6477. pushOutChain(Mul, EB);
  6478. Opcode = ISD::STRICT_FADD;
  6479. Opers.clear();
  6480. Opers.push_back(Mul.getValue(1));
  6481. Opers.push_back(Mul.getValue(0));
  6482. Opers.push_back(getValue(FPI.getArgOperand(2)));
  6483. }
  6484. break;
  6485. }
  6486. }
  6487. // A few strict DAG nodes carry additional operands that are not
  6488. // set up by the default code above.
  6489. switch (Opcode) {
  6490. default: break;
  6491. case ISD::STRICT_FP_ROUND:
  6492. Opers.push_back(
  6493. DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
  6494. break;
  6495. case ISD::STRICT_FSETCC:
  6496. case ISD::STRICT_FSETCCS: {
  6497. auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
  6498. ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
  6499. if (TM.Options.NoNaNsFPMath)
  6500. Condition = getFCmpCodeWithoutNaN(Condition);
  6501. Opers.push_back(DAG.getCondCode(Condition));
  6502. break;
  6503. }
  6504. }
  6505. SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
  6506. pushOutChain(Result, EB);
  6507. SDValue FPResult = Result.getValue(0);
  6508. setValue(&FPI, FPResult);
  6509. }
  6510. static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
  6511. Optional<unsigned> ResOPC;
  6512. switch (VPIntrin.getIntrinsicID()) {
  6513. #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
  6514. #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) ResOPC = ISD::VPSD;
  6515. #define END_REGISTER_VP_INTRINSIC(VPID) break;
  6516. #include "llvm/IR/VPIntrinsics.def"
  6517. }
  6518. if (!ResOPC.hasValue())
  6519. llvm_unreachable(
  6520. "Inconsistency: no SDNode available for this VPIntrinsic!");
  6521. if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
  6522. *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
  6523. if (VPIntrin.getFastMathFlags().allowReassoc())
  6524. return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
  6525. : ISD::VP_REDUCE_FMUL;
  6526. }
  6527. return ResOPC.getValue();
  6528. }
  6529. void SelectionDAGBuilder::visitVPLoadGather(const VPIntrinsic &VPIntrin, EVT VT,
  6530. SmallVector<SDValue, 7> &OpValues,
  6531. bool IsGather) {
  6532. SDLoc DL = getCurSDLoc();
  6533. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6534. Value *PtrOperand = VPIntrin.getArgOperand(0);
  6535. MaybeAlign Alignment = VPIntrin.getPointerAlignment();
  6536. AAMDNodes AAInfo = VPIntrin.getAAMetadata();
  6537. const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
  6538. SDValue LD;
  6539. bool AddToChain = true;
  6540. if (!IsGather) {
  6541. // Do not serialize variable-length loads of constant memory with
  6542. // anything.
  6543. if (!Alignment)
  6544. Alignment = DAG.getEVTAlign(VT);
  6545. MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
  6546. AddToChain = !AA || !AA->pointsToConstantMemory(ML);
  6547. SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
  6548. MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
  6549. MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
  6550. MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
  6551. LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
  6552. MMO, false /*IsExpanding */);
  6553. } else {
  6554. if (!Alignment)
  6555. Alignment = DAG.getEVTAlign(VT.getScalarType());
  6556. unsigned AS =
  6557. PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
  6558. MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
  6559. MachinePointerInfo(AS), MachineMemOperand::MOLoad,
  6560. MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
  6561. SDValue Base, Index, Scale;
  6562. ISD::MemIndexType IndexType;
  6563. bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
  6564. this, VPIntrin.getParent());
  6565. if (!UniformBase) {
  6566. Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
  6567. Index = getValue(PtrOperand);
  6568. IndexType = ISD::SIGNED_UNSCALED;
  6569. Scale =
  6570. DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
  6571. }
  6572. EVT IdxVT = Index.getValueType();
  6573. EVT EltTy = IdxVT.getVectorElementType();
  6574. if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
  6575. EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
  6576. Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
  6577. }
  6578. LD = DAG.getGatherVP(
  6579. DAG.getVTList(VT, MVT::Other), VT, DL,
  6580. {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
  6581. IndexType);
  6582. }
  6583. if (AddToChain)
  6584. PendingLoads.push_back(LD.getValue(1));
  6585. setValue(&VPIntrin, LD);
  6586. }
  6587. void SelectionDAGBuilder::visitVPStoreScatter(const VPIntrinsic &VPIntrin,
  6588. SmallVector<SDValue, 7> &OpValues,
  6589. bool IsScatter) {
  6590. SDLoc DL = getCurSDLoc();
  6591. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6592. Value *PtrOperand = VPIntrin.getArgOperand(1);
  6593. EVT VT = OpValues[0].getValueType();
  6594. MaybeAlign Alignment = VPIntrin.getPointerAlignment();
  6595. AAMDNodes AAInfo = VPIntrin.getAAMetadata();
  6596. SDValue ST;
  6597. if (!IsScatter) {
  6598. if (!Alignment)
  6599. Alignment = DAG.getEVTAlign(VT);
  6600. SDValue Ptr = OpValues[1];
  6601. SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
  6602. MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
  6603. MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
  6604. MemoryLocation::UnknownSize, *Alignment, AAInfo);
  6605. ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
  6606. OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
  6607. /* IsTruncating */ false, /*IsCompressing*/ false);
  6608. } else {
  6609. if (!Alignment)
  6610. Alignment = DAG.getEVTAlign(VT.getScalarType());
  6611. unsigned AS =
  6612. PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
  6613. MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
  6614. MachinePointerInfo(AS), MachineMemOperand::MOStore,
  6615. MemoryLocation::UnknownSize, *Alignment, AAInfo);
  6616. SDValue Base, Index, Scale;
  6617. ISD::MemIndexType IndexType;
  6618. bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
  6619. this, VPIntrin.getParent());
  6620. if (!UniformBase) {
  6621. Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
  6622. Index = getValue(PtrOperand);
  6623. IndexType = ISD::SIGNED_UNSCALED;
  6624. Scale =
  6625. DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
  6626. }
  6627. EVT IdxVT = Index.getValueType();
  6628. EVT EltTy = IdxVT.getVectorElementType();
  6629. if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
  6630. EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
  6631. Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
  6632. }
  6633. ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
  6634. {getMemoryRoot(), OpValues[0], Base, Index, Scale,
  6635. OpValues[2], OpValues[3]},
  6636. MMO, IndexType);
  6637. }
  6638. DAG.setRoot(ST);
  6639. setValue(&VPIntrin, ST);
  6640. }
  6641. void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
  6642. const VPIntrinsic &VPIntrin) {
  6643. SDLoc DL = getCurSDLoc();
  6644. unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
  6645. SmallVector<EVT, 4> ValueVTs;
  6646. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6647. ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
  6648. SDVTList VTs = DAG.getVTList(ValueVTs);
  6649. auto EVLParamPos =
  6650. VPIntrinsic::getVectorLengthParamPos(VPIntrin.getIntrinsicID());
  6651. MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
  6652. assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
  6653. "Unexpected target EVL type");
  6654. // Request operands.
  6655. SmallVector<SDValue, 7> OpValues;
  6656. for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
  6657. auto Op = getValue(VPIntrin.getArgOperand(I));
  6658. if (I == EVLParamPos)
  6659. Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
  6660. OpValues.push_back(Op);
  6661. }
  6662. switch (Opcode) {
  6663. default: {
  6664. SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues);
  6665. setValue(&VPIntrin, Result);
  6666. break;
  6667. }
  6668. case ISD::VP_LOAD:
  6669. case ISD::VP_GATHER:
  6670. visitVPLoadGather(VPIntrin, ValueVTs[0], OpValues,
  6671. Opcode == ISD::VP_GATHER);
  6672. break;
  6673. case ISD::VP_STORE:
  6674. case ISD::VP_SCATTER:
  6675. visitVPStoreScatter(VPIntrin, OpValues, Opcode == ISD::VP_SCATTER);
  6676. break;
  6677. }
  6678. }
  6679. SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
  6680. const BasicBlock *EHPadBB,
  6681. MCSymbol *&BeginLabel) {
  6682. MachineFunction &MF = DAG.getMachineFunction();
  6683. MachineModuleInfo &MMI = MF.getMMI();
  6684. // Insert a label before the invoke call to mark the try range. This can be
  6685. // used to detect deletion of the invoke via the MachineModuleInfo.
  6686. BeginLabel = MMI.getContext().createTempSymbol();
  6687. // For SjLj, keep track of which landing pads go with which invokes
  6688. // so as to maintain the ordering of pads in the LSDA.
  6689. unsigned CallSiteIndex = MMI.getCurrentCallSite();
  6690. if (CallSiteIndex) {
  6691. MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
  6692. LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
  6693. // Now that the call site is handled, stop tracking it.
  6694. MMI.setCurrentCallSite(0);
  6695. }
  6696. return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
  6697. }
  6698. SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
  6699. const BasicBlock *EHPadBB,
  6700. MCSymbol *BeginLabel) {
  6701. assert(BeginLabel && "BeginLabel should've been set");
  6702. MachineFunction &MF = DAG.getMachineFunction();
  6703. MachineModuleInfo &MMI = MF.getMMI();
  6704. // Insert a label at the end of the invoke call to mark the try range. This
  6705. // can be used to detect deletion of the invoke via the MachineModuleInfo.
  6706. MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
  6707. Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
  6708. // Inform MachineModuleInfo of range.
  6709. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  6710. // There is a platform (e.g. wasm) that uses funclet style IR but does not
  6711. // actually use outlined funclets and their LSDA info style.
  6712. if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
  6713. assert(II && "II should've been set");
  6714. WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
  6715. EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
  6716. } else if (!isScopedEHPersonality(Pers)) {
  6717. assert(EHPadBB);
  6718. MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
  6719. }
  6720. return Chain;
  6721. }
  6722. std::pair<SDValue, SDValue>
  6723. SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
  6724. const BasicBlock *EHPadBB) {
  6725. MCSymbol *BeginLabel = nullptr;
  6726. if (EHPadBB) {
  6727. // Both PendingLoads and PendingExports must be flushed here;
  6728. // this call might not return.
  6729. (void)getRoot();
  6730. DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
  6731. CLI.setChain(getRoot());
  6732. }
  6733. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6734. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  6735. assert((CLI.IsTailCall || Result.second.getNode()) &&
  6736. "Non-null chain expected with non-tail call!");
  6737. assert((Result.second.getNode() || !Result.first.getNode()) &&
  6738. "Null value expected with tail call!");
  6739. if (!Result.second.getNode()) {
  6740. // As a special case, a null chain means that a tail call has been emitted
  6741. // and the DAG root is already updated.
  6742. HasTailCall = true;
  6743. // Since there's no actual continuation from this block, nothing can be
  6744. // relying on us setting vregs for them.
  6745. PendingExports.clear();
  6746. } else {
  6747. DAG.setRoot(Result.second);
  6748. }
  6749. if (EHPadBB) {
  6750. DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
  6751. BeginLabel));
  6752. }
  6753. return Result;
  6754. }
  6755. void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
  6756. bool isTailCall,
  6757. bool isMustTailCall,
  6758. const BasicBlock *EHPadBB) {
  6759. auto &DL = DAG.getDataLayout();
  6760. FunctionType *FTy = CB.getFunctionType();
  6761. Type *RetTy = CB.getType();
  6762. TargetLowering::ArgListTy Args;
  6763. Args.reserve(CB.arg_size());
  6764. const Value *SwiftErrorVal = nullptr;
  6765. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6766. if (isTailCall) {
  6767. // Avoid emitting tail calls in functions with the disable-tail-calls
  6768. // attribute.
  6769. auto *Caller = CB.getParent()->getParent();
  6770. if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
  6771. "true" && !isMustTailCall)
  6772. isTailCall = false;
  6773. // We can't tail call inside a function with a swifterror argument. Lowering
  6774. // does not support this yet. It would have to move into the swifterror
  6775. // register before the call.
  6776. if (TLI.supportSwiftError() &&
  6777. Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
  6778. isTailCall = false;
  6779. }
  6780. for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
  6781. TargetLowering::ArgListEntry Entry;
  6782. const Value *V = *I;
  6783. // Skip empty types
  6784. if (V->getType()->isEmptyTy())
  6785. continue;
  6786. SDValue ArgNode = getValue(V);
  6787. Entry.Node = ArgNode; Entry.Ty = V->getType();
  6788. Entry.setAttributes(&CB, I - CB.arg_begin());
  6789. // Use swifterror virtual register as input to the call.
  6790. if (Entry.IsSwiftError && TLI.supportSwiftError()) {
  6791. SwiftErrorVal = V;
  6792. // We find the virtual register for the actual swifterror argument.
  6793. // Instead of using the Value, we use the virtual register instead.
  6794. Entry.Node =
  6795. DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
  6796. EVT(TLI.getPointerTy(DL)));
  6797. }
  6798. Args.push_back(Entry);
  6799. // If we have an explicit sret argument that is an Instruction, (i.e., it
  6800. // might point to function-local memory), we can't meaningfully tail-call.
  6801. if (Entry.IsSRet && isa<Instruction>(V))
  6802. isTailCall = false;
  6803. }
  6804. // If call site has a cfguardtarget operand bundle, create and add an
  6805. // additional ArgListEntry.
  6806. if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
  6807. TargetLowering::ArgListEntry Entry;
  6808. Value *V = Bundle->Inputs[0];
  6809. SDValue ArgNode = getValue(V);
  6810. Entry.Node = ArgNode;
  6811. Entry.Ty = V->getType();
  6812. Entry.IsCFGuardTarget = true;
  6813. Args.push_back(Entry);
  6814. }
  6815. // Check if target-independent constraints permit a tail call here.
  6816. // Target-dependent constraints are checked within TLI->LowerCallTo.
  6817. if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
  6818. isTailCall = false;
  6819. // Disable tail calls if there is an swifterror argument. Targets have not
  6820. // been updated to support tail calls.
  6821. if (TLI.supportSwiftError() && SwiftErrorVal)
  6822. isTailCall = false;
  6823. TargetLowering::CallLoweringInfo CLI(DAG);
  6824. CLI.setDebugLoc(getCurSDLoc())
  6825. .setChain(getRoot())
  6826. .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
  6827. .setTailCall(isTailCall)
  6828. .setConvergent(CB.isConvergent())
  6829. .setIsPreallocated(
  6830. CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
  6831. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  6832. if (Result.first.getNode()) {
  6833. Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
  6834. setValue(&CB, Result.first);
  6835. }
  6836. // The last element of CLI.InVals has the SDValue for swifterror return.
  6837. // Here we copy it to a virtual register and update SwiftErrorMap for
  6838. // book-keeping.
  6839. if (SwiftErrorVal && TLI.supportSwiftError()) {
  6840. // Get the last element of InVals.
  6841. SDValue Src = CLI.InVals.back();
  6842. Register VReg =
  6843. SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
  6844. SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
  6845. DAG.setRoot(CopyNode);
  6846. }
  6847. }
  6848. static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
  6849. SelectionDAGBuilder &Builder) {
  6850. // Check to see if this load can be trivially constant folded, e.g. if the
  6851. // input is from a string literal.
  6852. if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
  6853. // Cast pointer to the type we really want to load.
  6854. Type *LoadTy =
  6855. Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
  6856. if (LoadVT.isVector())
  6857. LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
  6858. LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
  6859. PointerType::getUnqual(LoadTy));
  6860. if (const Constant *LoadCst =
  6861. ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
  6862. LoadTy, Builder.DAG.getDataLayout()))
  6863. return Builder.getValue(LoadCst);
  6864. }
  6865. // Otherwise, we have to emit the load. If the pointer is to unfoldable but
  6866. // still constant memory, the input chain can be the entry node.
  6867. SDValue Root;
  6868. bool ConstantMemory = false;
  6869. // Do not serialize (non-volatile) loads of constant memory with anything.
  6870. if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
  6871. Root = Builder.DAG.getEntryNode();
  6872. ConstantMemory = true;
  6873. } else {
  6874. // Do not serialize non-volatile loads against each other.
  6875. Root = Builder.DAG.getRoot();
  6876. }
  6877. SDValue Ptr = Builder.getValue(PtrVal);
  6878. SDValue LoadVal =
  6879. Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
  6880. MachinePointerInfo(PtrVal), Align(1));
  6881. if (!ConstantMemory)
  6882. Builder.PendingLoads.push_back(LoadVal.getValue(1));
  6883. return LoadVal;
  6884. }
  6885. /// Record the value for an instruction that produces an integer result,
  6886. /// converting the type where necessary.
  6887. void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
  6888. SDValue Value,
  6889. bool IsSigned) {
  6890. EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  6891. I.getType(), true);
  6892. if (IsSigned)
  6893. Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
  6894. else
  6895. Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
  6896. setValue(&I, Value);
  6897. }
  6898. /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
  6899. /// true and lower it. Otherwise return false, and it will be lowered like a
  6900. /// normal call.
  6901. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6902. /// correct prototype.
  6903. bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
  6904. const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
  6905. const Value *Size = I.getArgOperand(2);
  6906. const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
  6907. if (CSize && CSize->getZExtValue() == 0) {
  6908. EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  6909. I.getType(), true);
  6910. setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
  6911. return true;
  6912. }
  6913. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6914. std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
  6915. DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
  6916. getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
  6917. if (Res.first.getNode()) {
  6918. processIntegerCallValue(I, Res.first, true);
  6919. PendingLoads.push_back(Res.second);
  6920. return true;
  6921. }
  6922. // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
  6923. // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
  6924. if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
  6925. return false;
  6926. // If the target has a fast compare for the given size, it will return a
  6927. // preferred load type for that size. Require that the load VT is legal and
  6928. // that the target supports unaligned loads of that type. Otherwise, return
  6929. // INVALID.
  6930. auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
  6931. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6932. MVT LVT = TLI.hasFastEqualityCompare(NumBits);
  6933. if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
  6934. // TODO: Handle 5 byte compare as 4-byte + 1 byte.
  6935. // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
  6936. // TODO: Check alignment of src and dest ptrs.
  6937. unsigned DstAS = LHS->getType()->getPointerAddressSpace();
  6938. unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
  6939. if (!TLI.isTypeLegal(LVT) ||
  6940. !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
  6941. !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
  6942. LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
  6943. }
  6944. return LVT;
  6945. };
  6946. // This turns into unaligned loads. We only do this if the target natively
  6947. // supports the MVT we'll be loading or if it is small enough (<= 4) that
  6948. // we'll only produce a small number of byte loads.
  6949. MVT LoadVT;
  6950. unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
  6951. switch (NumBitsToCompare) {
  6952. default:
  6953. return false;
  6954. case 16:
  6955. LoadVT = MVT::i16;
  6956. break;
  6957. case 32:
  6958. LoadVT = MVT::i32;
  6959. break;
  6960. case 64:
  6961. case 128:
  6962. case 256:
  6963. LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
  6964. break;
  6965. }
  6966. if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
  6967. return false;
  6968. SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
  6969. SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
  6970. // Bitcast to a wide integer type if the loads are vectors.
  6971. if (LoadVT.isVector()) {
  6972. EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
  6973. LoadL = DAG.getBitcast(CmpVT, LoadL);
  6974. LoadR = DAG.getBitcast(CmpVT, LoadR);
  6975. }
  6976. SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
  6977. processIntegerCallValue(I, Cmp, false);
  6978. return true;
  6979. }
  6980. /// See if we can lower a memchr call into an optimized form. If so, return
  6981. /// true and lower it. Otherwise return false, and it will be lowered like a
  6982. /// normal call.
  6983. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6984. /// correct prototype.
  6985. bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
  6986. const Value *Src = I.getArgOperand(0);
  6987. const Value *Char = I.getArgOperand(1);
  6988. const Value *Length = I.getArgOperand(2);
  6989. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6990. std::pair<SDValue, SDValue> Res =
  6991. TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
  6992. getValue(Src), getValue(Char), getValue(Length),
  6993. MachinePointerInfo(Src));
  6994. if (Res.first.getNode()) {
  6995. setValue(&I, Res.first);
  6996. PendingLoads.push_back(Res.second);
  6997. return true;
  6998. }
  6999. return false;
  7000. }
  7001. /// See if we can lower a mempcpy call into an optimized form. If so, return
  7002. /// true and lower it. Otherwise return false, and it will be lowered like a
  7003. /// normal call.
  7004. /// The caller already checked that \p I calls the appropriate LibFunc with a
  7005. /// correct prototype.
  7006. bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
  7007. SDValue Dst = getValue(I.getArgOperand(0));
  7008. SDValue Src = getValue(I.getArgOperand(1));
  7009. SDValue Size = getValue(I.getArgOperand(2));
  7010. Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
  7011. Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
  7012. // DAG::getMemcpy needs Alignment to be defined.
  7013. Align Alignment = std::min(DstAlign, SrcAlign);
  7014. bool isVol = false;
  7015. SDLoc sdl = getCurSDLoc();
  7016. // In the mempcpy context we need to pass in a false value for isTailCall
  7017. // because the return pointer needs to be adjusted by the size of
  7018. // the copied memory.
  7019. SDValue Root = isVol ? getRoot() : getMemoryRoot();
  7020. SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
  7021. /*isTailCall=*/false,
  7022. MachinePointerInfo(I.getArgOperand(0)),
  7023. MachinePointerInfo(I.getArgOperand(1)),
  7024. I.getAAMetadata());
  7025. assert(MC.getNode() != nullptr &&
  7026. "** memcpy should not be lowered as TailCall in mempcpy context **");
  7027. DAG.setRoot(MC);
  7028. // Check if Size needs to be truncated or extended.
  7029. Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
  7030. // Adjust return pointer to point just past the last dst byte.
  7031. SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
  7032. Dst, Size);
  7033. setValue(&I, DstPlusSize);
  7034. return true;
  7035. }
  7036. /// See if we can lower a strcpy call into an optimized form. If so, return
  7037. /// true and lower it, otherwise return false and it will be lowered like a
  7038. /// normal call.
  7039. /// The caller already checked that \p I calls the appropriate LibFunc with a
  7040. /// correct prototype.
  7041. bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
  7042. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  7043. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  7044. std::pair<SDValue, SDValue> Res =
  7045. TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
  7046. getValue(Arg0), getValue(Arg1),
  7047. MachinePointerInfo(Arg0),
  7048. MachinePointerInfo(Arg1), isStpcpy);
  7049. if (Res.first.getNode()) {
  7050. setValue(&I, Res.first);
  7051. DAG.setRoot(Res.second);
  7052. return true;
  7053. }
  7054. return false;
  7055. }
  7056. /// See if we can lower a strcmp call into an optimized form. If so, return
  7057. /// true and lower it, otherwise return false and it will be lowered like a
  7058. /// normal call.
  7059. /// The caller already checked that \p I calls the appropriate LibFunc with a
  7060. /// correct prototype.
  7061. bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
  7062. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  7063. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  7064. std::pair<SDValue, SDValue> Res =
  7065. TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
  7066. getValue(Arg0), getValue(Arg1),
  7067. MachinePointerInfo(Arg0),
  7068. MachinePointerInfo(Arg1));
  7069. if (Res.first.getNode()) {
  7070. processIntegerCallValue(I, Res.first, true);
  7071. PendingLoads.push_back(Res.second);
  7072. return true;
  7073. }
  7074. return false;
  7075. }
  7076. /// See if we can lower a strlen call into an optimized form. If so, return
  7077. /// true and lower it, otherwise return false and it will be lowered like a
  7078. /// normal call.
  7079. /// The caller already checked that \p I calls the appropriate LibFunc with a
  7080. /// correct prototype.
  7081. bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
  7082. const Value *Arg0 = I.getArgOperand(0);
  7083. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  7084. std::pair<SDValue, SDValue> Res =
  7085. TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
  7086. getValue(Arg0), MachinePointerInfo(Arg0));
  7087. if (Res.first.getNode()) {
  7088. processIntegerCallValue(I, Res.first, false);
  7089. PendingLoads.push_back(Res.second);
  7090. return true;
  7091. }
  7092. return false;
  7093. }
  7094. /// See if we can lower a strnlen call into an optimized form. If so, return
  7095. /// true and lower it, otherwise return false and it will be lowered like a
  7096. /// normal call.
  7097. /// The caller already checked that \p I calls the appropriate LibFunc with a
  7098. /// correct prototype.
  7099. bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
  7100. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  7101. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  7102. std::pair<SDValue, SDValue> Res =
  7103. TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
  7104. getValue(Arg0), getValue(Arg1),
  7105. MachinePointerInfo(Arg0));
  7106. if (Res.first.getNode()) {
  7107. processIntegerCallValue(I, Res.first, false);
  7108. PendingLoads.push_back(Res.second);
  7109. return true;
  7110. }
  7111. return false;
  7112. }
  7113. /// See if we can lower a unary floating-point operation into an SDNode with
  7114. /// the specified Opcode. If so, return true and lower it, otherwise return
  7115. /// false and it will be lowered like a normal call.
  7116. /// The caller already checked that \p I calls the appropriate LibFunc with a
  7117. /// correct prototype.
  7118. bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
  7119. unsigned Opcode) {
  7120. // We already checked this call's prototype; verify it doesn't modify errno.
  7121. if (!I.onlyReadsMemory())
  7122. return false;
  7123. SDNodeFlags Flags;
  7124. Flags.copyFMF(cast<FPMathOperator>(I));
  7125. SDValue Tmp = getValue(I.getArgOperand(0));
  7126. setValue(&I,
  7127. DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
  7128. return true;
  7129. }
  7130. /// See if we can lower a binary floating-point operation into an SDNode with
  7131. /// the specified Opcode. If so, return true and lower it. Otherwise return
  7132. /// false, and it will be lowered like a normal call.
  7133. /// The caller already checked that \p I calls the appropriate LibFunc with a
  7134. /// correct prototype.
  7135. bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
  7136. unsigned Opcode) {
  7137. // We already checked this call's prototype; verify it doesn't modify errno.
  7138. if (!I.onlyReadsMemory())
  7139. return false;
  7140. SDNodeFlags Flags;
  7141. Flags.copyFMF(cast<FPMathOperator>(I));
  7142. SDValue Tmp0 = getValue(I.getArgOperand(0));
  7143. SDValue Tmp1 = getValue(I.getArgOperand(1));
  7144. EVT VT = Tmp0.getValueType();
  7145. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
  7146. return true;
  7147. }
  7148. void SelectionDAGBuilder::visitCall(const CallInst &I) {
  7149. // Handle inline assembly differently.
  7150. if (I.isInlineAsm()) {
  7151. visitInlineAsm(I);
  7152. return;
  7153. }
  7154. if (Function *F = I.getCalledFunction()) {
  7155. diagnoseDontCall(I);
  7156. if (F->isDeclaration()) {
  7157. // Is this an LLVM intrinsic or a target-specific intrinsic?
  7158. unsigned IID = F->getIntrinsicID();
  7159. if (!IID)
  7160. if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
  7161. IID = II->getIntrinsicID(F);
  7162. if (IID) {
  7163. visitIntrinsicCall(I, IID);
  7164. return;
  7165. }
  7166. }
  7167. // Check for well-known libc/libm calls. If the function is internal, it
  7168. // can't be a library call. Don't do the check if marked as nobuiltin for
  7169. // some reason or the call site requires strict floating point semantics.
  7170. LibFunc Func;
  7171. if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
  7172. F->hasName() && LibInfo->getLibFunc(*F, Func) &&
  7173. LibInfo->hasOptimizedCodeGen(Func)) {
  7174. switch (Func) {
  7175. default: break;
  7176. case LibFunc_bcmp:
  7177. if (visitMemCmpBCmpCall(I))
  7178. return;
  7179. break;
  7180. case LibFunc_copysign:
  7181. case LibFunc_copysignf:
  7182. case LibFunc_copysignl:
  7183. // We already checked this call's prototype; verify it doesn't modify
  7184. // errno.
  7185. if (I.onlyReadsMemory()) {
  7186. SDValue LHS = getValue(I.getArgOperand(0));
  7187. SDValue RHS = getValue(I.getArgOperand(1));
  7188. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
  7189. LHS.getValueType(), LHS, RHS));
  7190. return;
  7191. }
  7192. break;
  7193. case LibFunc_fabs:
  7194. case LibFunc_fabsf:
  7195. case LibFunc_fabsl:
  7196. if (visitUnaryFloatCall(I, ISD::FABS))
  7197. return;
  7198. break;
  7199. case LibFunc_fmin:
  7200. case LibFunc_fminf:
  7201. case LibFunc_fminl:
  7202. if (visitBinaryFloatCall(I, ISD::FMINNUM))
  7203. return;
  7204. break;
  7205. case LibFunc_fmax:
  7206. case LibFunc_fmaxf:
  7207. case LibFunc_fmaxl:
  7208. if (visitBinaryFloatCall(I, ISD::FMAXNUM))
  7209. return;
  7210. break;
  7211. case LibFunc_sin:
  7212. case LibFunc_sinf:
  7213. case LibFunc_sinl:
  7214. if (visitUnaryFloatCall(I, ISD::FSIN))
  7215. return;
  7216. break;
  7217. case LibFunc_cos:
  7218. case LibFunc_cosf:
  7219. case LibFunc_cosl:
  7220. if (visitUnaryFloatCall(I, ISD::FCOS))
  7221. return;
  7222. break;
  7223. case LibFunc_sqrt:
  7224. case LibFunc_sqrtf:
  7225. case LibFunc_sqrtl:
  7226. case LibFunc_sqrt_finite:
  7227. case LibFunc_sqrtf_finite:
  7228. case LibFunc_sqrtl_finite:
  7229. if (visitUnaryFloatCall(I, ISD::FSQRT))
  7230. return;
  7231. break;
  7232. case LibFunc_floor:
  7233. case LibFunc_floorf:
  7234. case LibFunc_floorl:
  7235. if (visitUnaryFloatCall(I, ISD::FFLOOR))
  7236. return;
  7237. break;
  7238. case LibFunc_nearbyint:
  7239. case LibFunc_nearbyintf:
  7240. case LibFunc_nearbyintl:
  7241. if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
  7242. return;
  7243. break;
  7244. case LibFunc_ceil:
  7245. case LibFunc_ceilf:
  7246. case LibFunc_ceill:
  7247. if (visitUnaryFloatCall(I, ISD::FCEIL))
  7248. return;
  7249. break;
  7250. case LibFunc_rint:
  7251. case LibFunc_rintf:
  7252. case LibFunc_rintl:
  7253. if (visitUnaryFloatCall(I, ISD::FRINT))
  7254. return;
  7255. break;
  7256. case LibFunc_round:
  7257. case LibFunc_roundf:
  7258. case LibFunc_roundl:
  7259. if (visitUnaryFloatCall(I, ISD::FROUND))
  7260. return;
  7261. break;
  7262. case LibFunc_trunc:
  7263. case LibFunc_truncf:
  7264. case LibFunc_truncl:
  7265. if (visitUnaryFloatCall(I, ISD::FTRUNC))
  7266. return;
  7267. break;
  7268. case LibFunc_log2:
  7269. case LibFunc_log2f:
  7270. case LibFunc_log2l:
  7271. if (visitUnaryFloatCall(I, ISD::FLOG2))
  7272. return;
  7273. break;
  7274. case LibFunc_exp2:
  7275. case LibFunc_exp2f:
  7276. case LibFunc_exp2l:
  7277. if (visitUnaryFloatCall(I, ISD::FEXP2))
  7278. return;
  7279. break;
  7280. case LibFunc_memcmp:
  7281. if (visitMemCmpBCmpCall(I))
  7282. return;
  7283. break;
  7284. case LibFunc_mempcpy:
  7285. if (visitMemPCpyCall(I))
  7286. return;
  7287. break;
  7288. case LibFunc_memchr:
  7289. if (visitMemChrCall(I))
  7290. return;
  7291. break;
  7292. case LibFunc_strcpy:
  7293. if (visitStrCpyCall(I, false))
  7294. return;
  7295. break;
  7296. case LibFunc_stpcpy:
  7297. if (visitStrCpyCall(I, true))
  7298. return;
  7299. break;
  7300. case LibFunc_strcmp:
  7301. if (visitStrCmpCall(I))
  7302. return;
  7303. break;
  7304. case LibFunc_strlen:
  7305. if (visitStrLenCall(I))
  7306. return;
  7307. break;
  7308. case LibFunc_strnlen:
  7309. if (visitStrNLenCall(I))
  7310. return;
  7311. break;
  7312. }
  7313. }
  7314. }
  7315. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  7316. // have to do anything here to lower funclet bundles.
  7317. // CFGuardTarget bundles are lowered in LowerCallTo.
  7318. assert(!I.hasOperandBundlesOtherThan(
  7319. {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
  7320. LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
  7321. LLVMContext::OB_clang_arc_attachedcall}) &&
  7322. "Cannot lower calls with arbitrary operand bundles!");
  7323. SDValue Callee = getValue(I.getCalledOperand());
  7324. if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
  7325. LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
  7326. else
  7327. // Check if we can potentially perform a tail call. More detailed checking
  7328. // is be done within LowerCallTo, after more information about the call is
  7329. // known.
  7330. LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
  7331. }
  7332. namespace {
  7333. /// AsmOperandInfo - This contains information for each constraint that we are
  7334. /// lowering.
  7335. class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
  7336. public:
  7337. /// CallOperand - If this is the result output operand or a clobber
  7338. /// this is null, otherwise it is the incoming operand to the CallInst.
  7339. /// This gets modified as the asm is processed.
  7340. SDValue CallOperand;
  7341. /// AssignedRegs - If this is a register or register class operand, this
  7342. /// contains the set of register corresponding to the operand.
  7343. RegsForValue AssignedRegs;
  7344. explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
  7345. : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
  7346. }
  7347. /// Whether or not this operand accesses memory
  7348. bool hasMemory(const TargetLowering &TLI) const {
  7349. // Indirect operand accesses access memory.
  7350. if (isIndirect)
  7351. return true;
  7352. for (const auto &Code : Codes)
  7353. if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
  7354. return true;
  7355. return false;
  7356. }
  7357. /// getCallOperandValEVT - Return the EVT of the Value* that this operand
  7358. /// corresponds to. If there is no Value* for this operand, it returns
  7359. /// MVT::Other.
  7360. EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
  7361. const DataLayout &DL,
  7362. llvm::Type *ParamElemType) const {
  7363. if (!CallOperandVal) return MVT::Other;
  7364. if (isa<BasicBlock>(CallOperandVal))
  7365. return TLI.getProgramPointerTy(DL);
  7366. llvm::Type *OpTy = CallOperandVal->getType();
  7367. // FIXME: code duplicated from TargetLowering::ParseConstraints().
  7368. // If this is an indirect operand, the operand is a pointer to the
  7369. // accessed type.
  7370. if (isIndirect) {
  7371. OpTy = ParamElemType;
  7372. assert(OpTy && "Indirect opernad must have elementtype attribute");
  7373. }
  7374. // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
  7375. if (StructType *STy = dyn_cast<StructType>(OpTy))
  7376. if (STy->getNumElements() == 1)
  7377. OpTy = STy->getElementType(0);
  7378. // If OpTy is not a single value, it may be a struct/union that we
  7379. // can tile with integers.
  7380. if (!OpTy->isSingleValueType() && OpTy->isSized()) {
  7381. unsigned BitSize = DL.getTypeSizeInBits(OpTy);
  7382. switch (BitSize) {
  7383. default: break;
  7384. case 1:
  7385. case 8:
  7386. case 16:
  7387. case 32:
  7388. case 64:
  7389. case 128:
  7390. OpTy = IntegerType::get(Context, BitSize);
  7391. break;
  7392. }
  7393. }
  7394. return TLI.getAsmOperandValueType(DL, OpTy, true);
  7395. }
  7396. };
  7397. } // end anonymous namespace
  7398. /// Make sure that the output operand \p OpInfo and its corresponding input
  7399. /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
  7400. /// out).
  7401. static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
  7402. SDISelAsmOperandInfo &MatchingOpInfo,
  7403. SelectionDAG &DAG) {
  7404. if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
  7405. return;
  7406. const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
  7407. const auto &TLI = DAG.getTargetLoweringInfo();
  7408. std::pair<unsigned, const TargetRegisterClass *> MatchRC =
  7409. TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
  7410. OpInfo.ConstraintVT);
  7411. std::pair<unsigned, const TargetRegisterClass *> InputRC =
  7412. TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
  7413. MatchingOpInfo.ConstraintVT);
  7414. if ((OpInfo.ConstraintVT.isInteger() !=
  7415. MatchingOpInfo.ConstraintVT.isInteger()) ||
  7416. (MatchRC.second != InputRC.second)) {
  7417. // FIXME: error out in a more elegant fashion
  7418. report_fatal_error("Unsupported asm: input constraint"
  7419. " with a matching output constraint of"
  7420. " incompatible type!");
  7421. }
  7422. MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
  7423. }
  7424. /// Get a direct memory input to behave well as an indirect operand.
  7425. /// This may introduce stores, hence the need for a \p Chain.
  7426. /// \return The (possibly updated) chain.
  7427. static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
  7428. SDISelAsmOperandInfo &OpInfo,
  7429. SelectionDAG &DAG) {
  7430. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7431. // If we don't have an indirect input, put it in the constpool if we can,
  7432. // otherwise spill it to a stack slot.
  7433. // TODO: This isn't quite right. We need to handle these according to
  7434. // the addressing mode that the constraint wants. Also, this may take
  7435. // an additional register for the computation and we don't want that
  7436. // either.
  7437. // If the operand is a float, integer, or vector constant, spill to a
  7438. // constant pool entry to get its address.
  7439. const Value *OpVal = OpInfo.CallOperandVal;
  7440. if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
  7441. isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
  7442. OpInfo.CallOperand = DAG.getConstantPool(
  7443. cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
  7444. return Chain;
  7445. }
  7446. // Otherwise, create a stack slot and emit a store to it before the asm.
  7447. Type *Ty = OpVal->getType();
  7448. auto &DL = DAG.getDataLayout();
  7449. uint64_t TySize = DL.getTypeAllocSize(Ty);
  7450. MachineFunction &MF = DAG.getMachineFunction();
  7451. int SSFI = MF.getFrameInfo().CreateStackObject(
  7452. TySize, DL.getPrefTypeAlign(Ty), false);
  7453. SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
  7454. Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
  7455. MachinePointerInfo::getFixedStack(MF, SSFI),
  7456. TLI.getMemValueType(DL, Ty));
  7457. OpInfo.CallOperand = StackSlot;
  7458. return Chain;
  7459. }
  7460. /// GetRegistersForValue - Assign registers (virtual or physical) for the
  7461. /// specified operand. We prefer to assign virtual registers, to allow the
  7462. /// register allocator to handle the assignment process. However, if the asm
  7463. /// uses features that we can't model on machineinstrs, we have SDISel do the
  7464. /// allocation. This produces generally horrible, but correct, code.
  7465. ///
  7466. /// OpInfo describes the operand
  7467. /// RefOpInfo describes the matching operand if any, the operand otherwise
  7468. static llvm::Optional<unsigned>
  7469. getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
  7470. SDISelAsmOperandInfo &OpInfo,
  7471. SDISelAsmOperandInfo &RefOpInfo) {
  7472. LLVMContext &Context = *DAG.getContext();
  7473. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7474. MachineFunction &MF = DAG.getMachineFunction();
  7475. SmallVector<unsigned, 4> Regs;
  7476. const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
  7477. // No work to do for memory operations.
  7478. if (OpInfo.ConstraintType == TargetLowering::C_Memory)
  7479. return None;
  7480. // If this is a constraint for a single physreg, or a constraint for a
  7481. // register class, find it.
  7482. unsigned AssignedReg;
  7483. const TargetRegisterClass *RC;
  7484. std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
  7485. &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
  7486. // RC is unset only on failure. Return immediately.
  7487. if (!RC)
  7488. return None;
  7489. // Get the actual register value type. This is important, because the user
  7490. // may have asked for (e.g.) the AX register in i32 type. We need to
  7491. // remember that AX is actually i16 to get the right extension.
  7492. const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
  7493. if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
  7494. // If this is an FP operand in an integer register (or visa versa), or more
  7495. // generally if the operand value disagrees with the register class we plan
  7496. // to stick it in, fix the operand type.
  7497. //
  7498. // If this is an input value, the bitcast to the new type is done now.
  7499. // Bitcast for output value is done at the end of visitInlineAsm().
  7500. if ((OpInfo.Type == InlineAsm::isOutput ||
  7501. OpInfo.Type == InlineAsm::isInput) &&
  7502. !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
  7503. // Try to convert to the first EVT that the reg class contains. If the
  7504. // types are identical size, use a bitcast to convert (e.g. two differing
  7505. // vector types). Note: output bitcast is done at the end of
  7506. // visitInlineAsm().
  7507. if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
  7508. // Exclude indirect inputs while they are unsupported because the code
  7509. // to perform the load is missing and thus OpInfo.CallOperand still
  7510. // refers to the input address rather than the pointed-to value.
  7511. if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
  7512. OpInfo.CallOperand =
  7513. DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
  7514. OpInfo.ConstraintVT = RegVT;
  7515. // If the operand is an FP value and we want it in integer registers,
  7516. // use the corresponding integer type. This turns an f64 value into
  7517. // i64, which can be passed with two i32 values on a 32-bit machine.
  7518. } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
  7519. MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
  7520. if (OpInfo.Type == InlineAsm::isInput)
  7521. OpInfo.CallOperand =
  7522. DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
  7523. OpInfo.ConstraintVT = VT;
  7524. }
  7525. }
  7526. }
  7527. // No need to allocate a matching input constraint since the constraint it's
  7528. // matching to has already been allocated.
  7529. if (OpInfo.isMatchingInputConstraint())
  7530. return None;
  7531. EVT ValueVT = OpInfo.ConstraintVT;
  7532. if (OpInfo.ConstraintVT == MVT::Other)
  7533. ValueVT = RegVT;
  7534. // Initialize NumRegs.
  7535. unsigned NumRegs = 1;
  7536. if (OpInfo.ConstraintVT != MVT::Other)
  7537. NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
  7538. // If this is a constraint for a specific physical register, like {r17},
  7539. // assign it now.
  7540. // If this associated to a specific register, initialize iterator to correct
  7541. // place. If virtual, make sure we have enough registers
  7542. // Initialize iterator if necessary
  7543. TargetRegisterClass::iterator I = RC->begin();
  7544. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  7545. // Do not check for single registers.
  7546. if (AssignedReg) {
  7547. I = std::find(I, RC->end(), AssignedReg);
  7548. if (I == RC->end()) {
  7549. // RC does not contain the selected register, which indicates a
  7550. // mismatch between the register and the required type/bitwidth.
  7551. return {AssignedReg};
  7552. }
  7553. }
  7554. for (; NumRegs; --NumRegs, ++I) {
  7555. assert(I != RC->end() && "Ran out of registers to allocate!");
  7556. Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
  7557. Regs.push_back(R);
  7558. }
  7559. OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
  7560. return None;
  7561. }
  7562. static unsigned
  7563. findMatchingInlineAsmOperand(unsigned OperandNo,
  7564. const std::vector<SDValue> &AsmNodeOperands) {
  7565. // Scan until we find the definition we already emitted of this operand.
  7566. unsigned CurOp = InlineAsm::Op_FirstOperand;
  7567. for (; OperandNo; --OperandNo) {
  7568. // Advance to the next operand.
  7569. unsigned OpFlag =
  7570. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  7571. assert((InlineAsm::isRegDefKind(OpFlag) ||
  7572. InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
  7573. InlineAsm::isMemKind(OpFlag)) &&
  7574. "Skipped past definitions?");
  7575. CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
  7576. }
  7577. return CurOp;
  7578. }
  7579. namespace {
  7580. class ExtraFlags {
  7581. unsigned Flags = 0;
  7582. public:
  7583. explicit ExtraFlags(const CallBase &Call) {
  7584. const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
  7585. if (IA->hasSideEffects())
  7586. Flags |= InlineAsm::Extra_HasSideEffects;
  7587. if (IA->isAlignStack())
  7588. Flags |= InlineAsm::Extra_IsAlignStack;
  7589. if (Call.isConvergent())
  7590. Flags |= InlineAsm::Extra_IsConvergent;
  7591. Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
  7592. }
  7593. void update(const TargetLowering::AsmOperandInfo &OpInfo) {
  7594. // Ideally, we would only check against memory constraints. However, the
  7595. // meaning of an Other constraint can be target-specific and we can't easily
  7596. // reason about it. Therefore, be conservative and set MayLoad/MayStore
  7597. // for Other constraints as well.
  7598. if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
  7599. OpInfo.ConstraintType == TargetLowering::C_Other) {
  7600. if (OpInfo.Type == InlineAsm::isInput)
  7601. Flags |= InlineAsm::Extra_MayLoad;
  7602. else if (OpInfo.Type == InlineAsm::isOutput)
  7603. Flags |= InlineAsm::Extra_MayStore;
  7604. else if (OpInfo.Type == InlineAsm::isClobber)
  7605. Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
  7606. }
  7607. }
  7608. unsigned get() const { return Flags; }
  7609. };
  7610. } // end anonymous namespace
  7611. /// visitInlineAsm - Handle a call to an InlineAsm object.
  7612. void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
  7613. const BasicBlock *EHPadBB) {
  7614. const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
  7615. /// ConstraintOperands - Information about all of the constraints.
  7616. SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
  7617. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7618. TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
  7619. DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
  7620. // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
  7621. // AsmDialect, MayLoad, MayStore).
  7622. bool HasSideEffect = IA->hasSideEffects();
  7623. ExtraFlags ExtraInfo(Call);
  7624. unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
  7625. unsigned ResNo = 0; // ResNo - The result number of the next output.
  7626. for (auto &T : TargetConstraints) {
  7627. ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
  7628. SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
  7629. // Compute the value type for each operand.
  7630. if (OpInfo.hasArg()) {
  7631. OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
  7632. OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
  7633. Type *ParamElemTy = Call.getAttributes().getParamElementType(ArgNo);
  7634. EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI,
  7635. DAG.getDataLayout(), ParamElemTy);
  7636. OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
  7637. ArgNo++;
  7638. } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
  7639. // The return value of the call is this value. As such, there is no
  7640. // corresponding argument.
  7641. assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
  7642. if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
  7643. OpInfo.ConstraintVT = TLI.getSimpleValueType(
  7644. DAG.getDataLayout(), STy->getElementType(ResNo));
  7645. } else {
  7646. assert(ResNo == 0 && "Asm only has one result!");
  7647. OpInfo.ConstraintVT = TLI.getAsmOperandValueType(
  7648. DAG.getDataLayout(), Call.getType()).getSimpleVT();
  7649. }
  7650. ++ResNo;
  7651. } else {
  7652. OpInfo.ConstraintVT = MVT::Other;
  7653. }
  7654. if (!HasSideEffect)
  7655. HasSideEffect = OpInfo.hasMemory(TLI);
  7656. // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
  7657. // FIXME: Could we compute this on OpInfo rather than T?
  7658. // Compute the constraint code and ConstraintType to use.
  7659. TLI.ComputeConstraintToUse(T, SDValue());
  7660. if (T.ConstraintType == TargetLowering::C_Immediate &&
  7661. OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
  7662. // We've delayed emitting a diagnostic like the "n" constraint because
  7663. // inlining could cause an integer showing up.
  7664. return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
  7665. "' expects an integer constant "
  7666. "expression");
  7667. ExtraInfo.update(T);
  7668. }
  7669. // We won't need to flush pending loads if this asm doesn't touch
  7670. // memory and is nonvolatile.
  7671. SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
  7672. bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow();
  7673. if (EmitEHLabels) {
  7674. assert(EHPadBB && "InvokeInst must have an EHPadBB");
  7675. }
  7676. bool IsCallBr = isa<CallBrInst>(Call);
  7677. if (IsCallBr || EmitEHLabels) {
  7678. // If this is a callbr or invoke we need to flush pending exports since
  7679. // inlineasm_br and invoke are terminators.
  7680. // We need to do this before nodes are glued to the inlineasm_br node.
  7681. Chain = getControlRoot();
  7682. }
  7683. MCSymbol *BeginLabel = nullptr;
  7684. if (EmitEHLabels) {
  7685. Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
  7686. }
  7687. // Second pass over the constraints: compute which constraint option to use.
  7688. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7689. // If this is an output operand with a matching input operand, look up the
  7690. // matching input. If their types mismatch, e.g. one is an integer, the
  7691. // other is floating point, or their sizes are different, flag it as an
  7692. // error.
  7693. if (OpInfo.hasMatchingInput()) {
  7694. SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
  7695. patchMatchingInput(OpInfo, Input, DAG);
  7696. }
  7697. // Compute the constraint code and ConstraintType to use.
  7698. TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
  7699. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  7700. OpInfo.Type == InlineAsm::isClobber)
  7701. continue;
  7702. // If this is a memory input, and if the operand is not indirect, do what we
  7703. // need to provide an address for the memory input.
  7704. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  7705. !OpInfo.isIndirect) {
  7706. assert((OpInfo.isMultipleAlternative ||
  7707. (OpInfo.Type == InlineAsm::isInput)) &&
  7708. "Can only indirectify direct input operands!");
  7709. // Memory operands really want the address of the value.
  7710. Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
  7711. // There is no longer a Value* corresponding to this operand.
  7712. OpInfo.CallOperandVal = nullptr;
  7713. // It is now an indirect operand.
  7714. OpInfo.isIndirect = true;
  7715. }
  7716. }
  7717. // AsmNodeOperands - The operands for the ISD::INLINEASM node.
  7718. std::vector<SDValue> AsmNodeOperands;
  7719. AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
  7720. AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
  7721. IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
  7722. // If we have a !srcloc metadata node associated with it, we want to attach
  7723. // this to the ultimately generated inline asm machineinstr. To do this, we
  7724. // pass in the third operand as this (potentially null) inline asm MDNode.
  7725. const MDNode *SrcLoc = Call.getMetadata("srcloc");
  7726. AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
  7727. // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
  7728. // bits as operand 3.
  7729. AsmNodeOperands.push_back(DAG.getTargetConstant(
  7730. ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  7731. // Third pass: Loop over operands to prepare DAG-level operands.. As part of
  7732. // this, assign virtual and physical registers for inputs and otput.
  7733. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7734. // Assign Registers.
  7735. SDISelAsmOperandInfo &RefOpInfo =
  7736. OpInfo.isMatchingInputConstraint()
  7737. ? ConstraintOperands[OpInfo.getMatchedOperand()]
  7738. : OpInfo;
  7739. const auto RegError =
  7740. getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
  7741. if (RegError.hasValue()) {
  7742. const MachineFunction &MF = DAG.getMachineFunction();
  7743. const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
  7744. const char *RegName = TRI.getName(RegError.getValue());
  7745. emitInlineAsmError(Call, "register '" + Twine(RegName) +
  7746. "' allocated for constraint '" +
  7747. Twine(OpInfo.ConstraintCode) +
  7748. "' does not match required type");
  7749. return;
  7750. }
  7751. auto DetectWriteToReservedRegister = [&]() {
  7752. const MachineFunction &MF = DAG.getMachineFunction();
  7753. const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
  7754. for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
  7755. if (Register::isPhysicalRegister(Reg) &&
  7756. TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
  7757. const char *RegName = TRI.getName(Reg);
  7758. emitInlineAsmError(Call, "write to reserved register '" +
  7759. Twine(RegName) + "'");
  7760. return true;
  7761. }
  7762. }
  7763. return false;
  7764. };
  7765. switch (OpInfo.Type) {
  7766. case InlineAsm::isOutput:
  7767. if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
  7768. unsigned ConstraintID =
  7769. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  7770. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  7771. "Failed to convert memory constraint code to constraint id.");
  7772. // Add information to the INLINEASM node to know about this output.
  7773. unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  7774. OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
  7775. AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
  7776. MVT::i32));
  7777. AsmNodeOperands.push_back(OpInfo.CallOperand);
  7778. } else {
  7779. // Otherwise, this outputs to a register (directly for C_Register /
  7780. // C_RegisterClass, and a target-defined fashion for
  7781. // C_Immediate/C_Other). Find a register that we can use.
  7782. if (OpInfo.AssignedRegs.Regs.empty()) {
  7783. emitInlineAsmError(
  7784. Call, "couldn't allocate output register for constraint '" +
  7785. Twine(OpInfo.ConstraintCode) + "'");
  7786. return;
  7787. }
  7788. if (DetectWriteToReservedRegister())
  7789. return;
  7790. // Add information to the INLINEASM node to know that this register is
  7791. // set.
  7792. OpInfo.AssignedRegs.AddInlineAsmOperands(
  7793. OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
  7794. : InlineAsm::Kind_RegDef,
  7795. false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
  7796. }
  7797. break;
  7798. case InlineAsm::isInput: {
  7799. SDValue InOperandVal = OpInfo.CallOperand;
  7800. if (OpInfo.isMatchingInputConstraint()) {
  7801. // If this is required to match an output register we have already set,
  7802. // just use its register.
  7803. auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
  7804. AsmNodeOperands);
  7805. unsigned OpFlag =
  7806. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  7807. if (InlineAsm::isRegDefKind(OpFlag) ||
  7808. InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
  7809. // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
  7810. if (OpInfo.isIndirect) {
  7811. // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
  7812. emitInlineAsmError(Call, "inline asm not supported yet: "
  7813. "don't know how to handle tied "
  7814. "indirect register inputs");
  7815. return;
  7816. }
  7817. SmallVector<unsigned, 4> Regs;
  7818. MachineFunction &MF = DAG.getMachineFunction();
  7819. MachineRegisterInfo &MRI = MF.getRegInfo();
  7820. const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
  7821. auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
  7822. Register TiedReg = R->getReg();
  7823. MVT RegVT = R->getSimpleValueType(0);
  7824. const TargetRegisterClass *RC =
  7825. TiedReg.isVirtual() ? MRI.getRegClass(TiedReg)
  7826. : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
  7827. : TRI.getMinimalPhysRegClass(TiedReg);
  7828. unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
  7829. for (unsigned i = 0; i != NumRegs; ++i)
  7830. Regs.push_back(MRI.createVirtualRegister(RC));
  7831. RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
  7832. SDLoc dl = getCurSDLoc();
  7833. // Use the produced MatchedRegs object to
  7834. MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
  7835. MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
  7836. true, OpInfo.getMatchedOperand(), dl,
  7837. DAG, AsmNodeOperands);
  7838. break;
  7839. }
  7840. assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
  7841. assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
  7842. "Unexpected number of operands");
  7843. // Add information to the INLINEASM node to know about this input.
  7844. // See InlineAsm.h isUseOperandTiedToDef.
  7845. OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
  7846. OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
  7847. OpInfo.getMatchedOperand());
  7848. AsmNodeOperands.push_back(DAG.getTargetConstant(
  7849. OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  7850. AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
  7851. break;
  7852. }
  7853. // Treat indirect 'X' constraint as memory.
  7854. if (OpInfo.ConstraintType == TargetLowering::C_Other &&
  7855. OpInfo.isIndirect)
  7856. OpInfo.ConstraintType = TargetLowering::C_Memory;
  7857. if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
  7858. OpInfo.ConstraintType == TargetLowering::C_Other) {
  7859. std::vector<SDValue> Ops;
  7860. TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
  7861. Ops, DAG);
  7862. if (Ops.empty()) {
  7863. if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
  7864. if (isa<ConstantSDNode>(InOperandVal)) {
  7865. emitInlineAsmError(Call, "value out of range for constraint '" +
  7866. Twine(OpInfo.ConstraintCode) + "'");
  7867. return;
  7868. }
  7869. emitInlineAsmError(Call,
  7870. "invalid operand for inline asm constraint '" +
  7871. Twine(OpInfo.ConstraintCode) + "'");
  7872. return;
  7873. }
  7874. // Add information to the INLINEASM node to know about this input.
  7875. unsigned ResOpType =
  7876. InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
  7877. AsmNodeOperands.push_back(DAG.getTargetConstant(
  7878. ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  7879. llvm::append_range(AsmNodeOperands, Ops);
  7880. break;
  7881. }
  7882. if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
  7883. assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
  7884. assert(InOperandVal.getValueType() ==
  7885. TLI.getPointerTy(DAG.getDataLayout()) &&
  7886. "Memory operands expect pointer values");
  7887. unsigned ConstraintID =
  7888. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  7889. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  7890. "Failed to convert memory constraint code to constraint id.");
  7891. // Add information to the INLINEASM node to know about this input.
  7892. unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  7893. ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
  7894. AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
  7895. getCurSDLoc(),
  7896. MVT::i32));
  7897. AsmNodeOperands.push_back(InOperandVal);
  7898. break;
  7899. }
  7900. assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
  7901. OpInfo.ConstraintType == TargetLowering::C_Register) &&
  7902. "Unknown constraint type!");
  7903. // TODO: Support this.
  7904. if (OpInfo.isIndirect) {
  7905. emitInlineAsmError(
  7906. Call, "Don't know how to handle indirect register inputs yet "
  7907. "for constraint '" +
  7908. Twine(OpInfo.ConstraintCode) + "'");
  7909. return;
  7910. }
  7911. // Copy the input into the appropriate registers.
  7912. if (OpInfo.AssignedRegs.Regs.empty()) {
  7913. emitInlineAsmError(Call,
  7914. "couldn't allocate input reg for constraint '" +
  7915. Twine(OpInfo.ConstraintCode) + "'");
  7916. return;
  7917. }
  7918. if (DetectWriteToReservedRegister())
  7919. return;
  7920. SDLoc dl = getCurSDLoc();
  7921. OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
  7922. &Call);
  7923. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
  7924. dl, DAG, AsmNodeOperands);
  7925. break;
  7926. }
  7927. case InlineAsm::isClobber:
  7928. // Add the clobbered value to the operand list, so that the register
  7929. // allocator is aware that the physreg got clobbered.
  7930. if (!OpInfo.AssignedRegs.Regs.empty())
  7931. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
  7932. false, 0, getCurSDLoc(), DAG,
  7933. AsmNodeOperands);
  7934. break;
  7935. }
  7936. }
  7937. // Finish up input operands. Set the input chain and add the flag last.
  7938. AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
  7939. if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
  7940. unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
  7941. Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
  7942. DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
  7943. Flag = Chain.getValue(1);
  7944. // Do additional work to generate outputs.
  7945. SmallVector<EVT, 1> ResultVTs;
  7946. SmallVector<SDValue, 1> ResultValues;
  7947. SmallVector<SDValue, 8> OutChains;
  7948. llvm::Type *CallResultType = Call.getType();
  7949. ArrayRef<Type *> ResultTypes;
  7950. if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
  7951. ResultTypes = StructResult->elements();
  7952. else if (!CallResultType->isVoidTy())
  7953. ResultTypes = makeArrayRef(CallResultType);
  7954. auto CurResultType = ResultTypes.begin();
  7955. auto handleRegAssign = [&](SDValue V) {
  7956. assert(CurResultType != ResultTypes.end() && "Unexpected value");
  7957. assert((*CurResultType)->isSized() && "Unexpected unsized type");
  7958. EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
  7959. ++CurResultType;
  7960. // If the type of the inline asm call site return value is different but has
  7961. // same size as the type of the asm output bitcast it. One example of this
  7962. // is for vectors with different width / number of elements. This can
  7963. // happen for register classes that can contain multiple different value
  7964. // types. The preg or vreg allocated may not have the same VT as was
  7965. // expected.
  7966. //
  7967. // This can also happen for a return value that disagrees with the register
  7968. // class it is put in, eg. a double in a general-purpose register on a
  7969. // 32-bit machine.
  7970. if (ResultVT != V.getValueType() &&
  7971. ResultVT.getSizeInBits() == V.getValueSizeInBits())
  7972. V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
  7973. else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
  7974. V.getValueType().isInteger()) {
  7975. // If a result value was tied to an input value, the computed result
  7976. // may have a wider width than the expected result. Extract the
  7977. // relevant portion.
  7978. V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
  7979. }
  7980. assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
  7981. ResultVTs.push_back(ResultVT);
  7982. ResultValues.push_back(V);
  7983. };
  7984. // Deal with output operands.
  7985. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7986. if (OpInfo.Type == InlineAsm::isOutput) {
  7987. SDValue Val;
  7988. // Skip trivial output operands.
  7989. if (OpInfo.AssignedRegs.Regs.empty())
  7990. continue;
  7991. switch (OpInfo.ConstraintType) {
  7992. case TargetLowering::C_Register:
  7993. case TargetLowering::C_RegisterClass:
  7994. Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
  7995. Chain, &Flag, &Call);
  7996. break;
  7997. case TargetLowering::C_Immediate:
  7998. case TargetLowering::C_Other:
  7999. Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
  8000. OpInfo, DAG);
  8001. break;
  8002. case TargetLowering::C_Memory:
  8003. break; // Already handled.
  8004. case TargetLowering::C_Unknown:
  8005. assert(false && "Unexpected unknown constraint");
  8006. }
  8007. // Indirect output manifest as stores. Record output chains.
  8008. if (OpInfo.isIndirect) {
  8009. const Value *Ptr = OpInfo.CallOperandVal;
  8010. assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
  8011. SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
  8012. MachinePointerInfo(Ptr));
  8013. OutChains.push_back(Store);
  8014. } else {
  8015. // generate CopyFromRegs to associated registers.
  8016. assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
  8017. if (Val.getOpcode() == ISD::MERGE_VALUES) {
  8018. for (const SDValue &V : Val->op_values())
  8019. handleRegAssign(V);
  8020. } else
  8021. handleRegAssign(Val);
  8022. }
  8023. }
  8024. }
  8025. // Set results.
  8026. if (!ResultValues.empty()) {
  8027. assert(CurResultType == ResultTypes.end() &&
  8028. "Mismatch in number of ResultTypes");
  8029. assert(ResultValues.size() == ResultTypes.size() &&
  8030. "Mismatch in number of output operands in asm result");
  8031. SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  8032. DAG.getVTList(ResultVTs), ResultValues);
  8033. setValue(&Call, V);
  8034. }
  8035. // Collect store chains.
  8036. if (!OutChains.empty())
  8037. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
  8038. if (EmitEHLabels) {
  8039. Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
  8040. }
  8041. // Only Update Root if inline assembly has a memory effect.
  8042. if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
  8043. EmitEHLabels)
  8044. DAG.setRoot(Chain);
  8045. }
  8046. void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
  8047. const Twine &Message) {
  8048. LLVMContext &Ctx = *DAG.getContext();
  8049. Ctx.emitError(&Call, Message);
  8050. // Make sure we leave the DAG in a valid state
  8051. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8052. SmallVector<EVT, 1> ValueVTs;
  8053. ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
  8054. if (ValueVTs.empty())
  8055. return;
  8056. SmallVector<SDValue, 1> Ops;
  8057. for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
  8058. Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
  8059. setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
  8060. }
  8061. void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
  8062. DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
  8063. MVT::Other, getRoot(),
  8064. getValue(I.getArgOperand(0)),
  8065. DAG.getSrcValue(I.getArgOperand(0))));
  8066. }
  8067. void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
  8068. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8069. const DataLayout &DL = DAG.getDataLayout();
  8070. SDValue V = DAG.getVAArg(
  8071. TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
  8072. getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
  8073. DL.getABITypeAlign(I.getType()).value());
  8074. DAG.setRoot(V.getValue(1));
  8075. if (I.getType()->isPointerTy())
  8076. V = DAG.getPtrExtOrTrunc(
  8077. V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
  8078. setValue(&I, V);
  8079. }
  8080. void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
  8081. DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
  8082. MVT::Other, getRoot(),
  8083. getValue(I.getArgOperand(0)),
  8084. DAG.getSrcValue(I.getArgOperand(0))));
  8085. }
  8086. void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
  8087. DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
  8088. MVT::Other, getRoot(),
  8089. getValue(I.getArgOperand(0)),
  8090. getValue(I.getArgOperand(1)),
  8091. DAG.getSrcValue(I.getArgOperand(0)),
  8092. DAG.getSrcValue(I.getArgOperand(1))));
  8093. }
  8094. SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
  8095. const Instruction &I,
  8096. SDValue Op) {
  8097. const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
  8098. if (!Range)
  8099. return Op;
  8100. ConstantRange CR = getConstantRangeFromMetadata(*Range);
  8101. if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
  8102. return Op;
  8103. APInt Lo = CR.getUnsignedMin();
  8104. if (!Lo.isMinValue())
  8105. return Op;
  8106. APInt Hi = CR.getUnsignedMax();
  8107. unsigned Bits = std::max(Hi.getActiveBits(),
  8108. static_cast<unsigned>(IntegerType::MIN_INT_BITS));
  8109. EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
  8110. SDLoc SL = getCurSDLoc();
  8111. SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
  8112. DAG.getValueType(SmallVT));
  8113. unsigned NumVals = Op.getNode()->getNumValues();
  8114. if (NumVals == 1)
  8115. return ZExt;
  8116. SmallVector<SDValue, 4> Ops;
  8117. Ops.push_back(ZExt);
  8118. for (unsigned I = 1; I != NumVals; ++I)
  8119. Ops.push_back(Op.getValue(I));
  8120. return DAG.getMergeValues(Ops, SL);
  8121. }
  8122. /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
  8123. /// the call being lowered.
  8124. ///
  8125. /// This is a helper for lowering intrinsics that follow a target calling
  8126. /// convention or require stack pointer adjustment. Only a subset of the
  8127. /// intrinsic's operands need to participate in the calling convention.
  8128. void SelectionDAGBuilder::populateCallLoweringInfo(
  8129. TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
  8130. unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
  8131. bool IsPatchPoint) {
  8132. TargetLowering::ArgListTy Args;
  8133. Args.reserve(NumArgs);
  8134. // Populate the argument list.
  8135. // Attributes for args start at offset 1, after the return attribute.
  8136. for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
  8137. ArgI != ArgE; ++ArgI) {
  8138. const Value *V = Call->getOperand(ArgI);
  8139. assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
  8140. TargetLowering::ArgListEntry Entry;
  8141. Entry.Node = getValue(V);
  8142. Entry.Ty = V->getType();
  8143. Entry.setAttributes(Call, ArgI);
  8144. Args.push_back(Entry);
  8145. }
  8146. CLI.setDebugLoc(getCurSDLoc())
  8147. .setChain(getRoot())
  8148. .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
  8149. .setDiscardResult(Call->use_empty())
  8150. .setIsPatchPoint(IsPatchPoint)
  8151. .setIsPreallocated(
  8152. Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
  8153. }
  8154. /// Add a stack map intrinsic call's live variable operands to a stackmap
  8155. /// or patchpoint target node's operand list.
  8156. ///
  8157. /// Constants are converted to TargetConstants purely as an optimization to
  8158. /// avoid constant materialization and register allocation.
  8159. ///
  8160. /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
  8161. /// generate addess computation nodes, and so FinalizeISel can convert the
  8162. /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
  8163. /// address materialization and register allocation, but may also be required
  8164. /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
  8165. /// alloca in the entry block, then the runtime may assume that the alloca's
  8166. /// StackMap location can be read immediately after compilation and that the
  8167. /// location is valid at any point during execution (this is similar to the
  8168. /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
  8169. /// only available in a register, then the runtime would need to trap when
  8170. /// execution reaches the StackMap in order to read the alloca's location.
  8171. static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
  8172. const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
  8173. SelectionDAGBuilder &Builder) {
  8174. for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) {
  8175. SDValue OpVal = Builder.getValue(Call.getArgOperand(i));
  8176. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
  8177. Ops.push_back(
  8178. Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
  8179. Ops.push_back(
  8180. Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
  8181. } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
  8182. const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
  8183. Ops.push_back(Builder.DAG.getTargetFrameIndex(
  8184. FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
  8185. } else
  8186. Ops.push_back(OpVal);
  8187. }
  8188. }
  8189. /// Lower llvm.experimental.stackmap directly to its target opcode.
  8190. void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
  8191. // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
  8192. // [live variables...])
  8193. assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
  8194. SDValue Chain, InFlag, Callee, NullPtr;
  8195. SmallVector<SDValue, 32> Ops;
  8196. SDLoc DL = getCurSDLoc();
  8197. Callee = getValue(CI.getCalledOperand());
  8198. NullPtr = DAG.getIntPtrConstant(0, DL, true);
  8199. // The stackmap intrinsic only records the live variables (the arguments
  8200. // passed to it) and emits NOPS (if requested). Unlike the patchpoint
  8201. // intrinsic, this won't be lowered to a function call. This means we don't
  8202. // have to worry about calling conventions and target specific lowering code.
  8203. // Instead we perform the call lowering right here.
  8204. //
  8205. // chain, flag = CALLSEQ_START(chain, 0, 0)
  8206. // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
  8207. // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
  8208. //
  8209. Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
  8210. InFlag = Chain.getValue(1);
  8211. // Add the <id> and <numBytes> constants.
  8212. SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
  8213. Ops.push_back(DAG.getTargetConstant(
  8214. cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
  8215. SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
  8216. Ops.push_back(DAG.getTargetConstant(
  8217. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
  8218. MVT::i32));
  8219. // Push live variables for the stack map.
  8220. addStackMapLiveVars(CI, 2, DL, Ops, *this);
  8221. // We are not pushing any register mask info here on the operands list,
  8222. // because the stackmap doesn't clobber anything.
  8223. // Push the chain and the glue flag.
  8224. Ops.push_back(Chain);
  8225. Ops.push_back(InFlag);
  8226. // Create the STACKMAP node.
  8227. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  8228. SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
  8229. Chain = SDValue(SM, 0);
  8230. InFlag = Chain.getValue(1);
  8231. Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
  8232. // Stackmaps don't generate values, so nothing goes into the NodeMap.
  8233. // Set the root to the target-lowered call chain.
  8234. DAG.setRoot(Chain);
  8235. // Inform the Frame Information that we have a stackmap in this function.
  8236. FuncInfo.MF->getFrameInfo().setHasStackMap();
  8237. }
  8238. /// Lower llvm.experimental.patchpoint directly to its target opcode.
  8239. void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
  8240. const BasicBlock *EHPadBB) {
  8241. // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
  8242. // i32 <numBytes>,
  8243. // i8* <target>,
  8244. // i32 <numArgs>,
  8245. // [Args...],
  8246. // [live variables...])
  8247. CallingConv::ID CC = CB.getCallingConv();
  8248. bool IsAnyRegCC = CC == CallingConv::AnyReg;
  8249. bool HasDef = !CB.getType()->isVoidTy();
  8250. SDLoc dl = getCurSDLoc();
  8251. SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
  8252. // Handle immediate and symbolic callees.
  8253. if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
  8254. Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
  8255. /*isTarget=*/true);
  8256. else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
  8257. Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
  8258. SDLoc(SymbolicCallee),
  8259. SymbolicCallee->getValueType(0));
  8260. // Get the real number of arguments participating in the call <numArgs>
  8261. SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
  8262. unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
  8263. // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
  8264. // Intrinsics include all meta-operands up to but not including CC.
  8265. unsigned NumMetaOpers = PatchPointOpers::CCPos;
  8266. assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
  8267. "Not enough arguments provided to the patchpoint intrinsic");
  8268. // For AnyRegCC the arguments are lowered later on manually.
  8269. unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
  8270. Type *ReturnTy =
  8271. IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
  8272. TargetLowering::CallLoweringInfo CLI(DAG);
  8273. populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
  8274. ReturnTy, true);
  8275. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  8276. SDNode *CallEnd = Result.second.getNode();
  8277. if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
  8278. CallEnd = CallEnd->getOperand(0).getNode();
  8279. /// Get a call instruction from the call sequence chain.
  8280. /// Tail calls are not allowed.
  8281. assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
  8282. "Expected a callseq node.");
  8283. SDNode *Call = CallEnd->getOperand(0).getNode();
  8284. bool HasGlue = Call->getGluedNode();
  8285. // Replace the target specific call node with the patchable intrinsic.
  8286. SmallVector<SDValue, 8> Ops;
  8287. // Add the <id> and <numBytes> constants.
  8288. SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
  8289. Ops.push_back(DAG.getTargetConstant(
  8290. cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
  8291. SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
  8292. Ops.push_back(DAG.getTargetConstant(
  8293. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
  8294. MVT::i32));
  8295. // Add the callee.
  8296. Ops.push_back(Callee);
  8297. // Adjust <numArgs> to account for any arguments that have been passed on the
  8298. // stack instead.
  8299. // Call Node: Chain, Target, {Args}, RegMask, [Glue]
  8300. unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
  8301. NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
  8302. Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
  8303. // Add the calling convention
  8304. Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
  8305. // Add the arguments we omitted previously. The register allocator should
  8306. // place these in any free register.
  8307. if (IsAnyRegCC)
  8308. for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
  8309. Ops.push_back(getValue(CB.getArgOperand(i)));
  8310. // Push the arguments from the call instruction up to the register mask.
  8311. SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
  8312. Ops.append(Call->op_begin() + 2, e);
  8313. // Push live variables for the stack map.
  8314. addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
  8315. // Push the register mask info.
  8316. if (HasGlue)
  8317. Ops.push_back(*(Call->op_end()-2));
  8318. else
  8319. Ops.push_back(*(Call->op_end()-1));
  8320. // Push the chain (this is originally the first operand of the call, but
  8321. // becomes now the last or second to last operand).
  8322. Ops.push_back(*(Call->op_begin()));
  8323. // Push the glue flag (last operand).
  8324. if (HasGlue)
  8325. Ops.push_back(*(Call->op_end()-1));
  8326. SDVTList NodeTys;
  8327. if (IsAnyRegCC && HasDef) {
  8328. // Create the return types based on the intrinsic definition
  8329. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8330. SmallVector<EVT, 3> ValueVTs;
  8331. ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
  8332. assert(ValueVTs.size() == 1 && "Expected only one return value type.");
  8333. // There is always a chain and a glue type at the end
  8334. ValueVTs.push_back(MVT::Other);
  8335. ValueVTs.push_back(MVT::Glue);
  8336. NodeTys = DAG.getVTList(ValueVTs);
  8337. } else
  8338. NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  8339. // Replace the target specific call node with a PATCHPOINT node.
  8340. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
  8341. dl, NodeTys, Ops);
  8342. // Update the NodeMap.
  8343. if (HasDef) {
  8344. if (IsAnyRegCC)
  8345. setValue(&CB, SDValue(MN, 0));
  8346. else
  8347. setValue(&CB, Result.first);
  8348. }
  8349. // Fixup the consumers of the intrinsic. The chain and glue may be used in the
  8350. // call sequence. Furthermore the location of the chain and glue can change
  8351. // when the AnyReg calling convention is used and the intrinsic returns a
  8352. // value.
  8353. if (IsAnyRegCC && HasDef) {
  8354. SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
  8355. SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
  8356. DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
  8357. } else
  8358. DAG.ReplaceAllUsesWith(Call, MN);
  8359. DAG.DeleteNode(Call);
  8360. // Inform the Frame Information that we have a patchpoint in this function.
  8361. FuncInfo.MF->getFrameInfo().setHasPatchPoint();
  8362. }
  8363. void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
  8364. unsigned Intrinsic) {
  8365. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8366. SDValue Op1 = getValue(I.getArgOperand(0));
  8367. SDValue Op2;
  8368. if (I.arg_size() > 1)
  8369. Op2 = getValue(I.getArgOperand(1));
  8370. SDLoc dl = getCurSDLoc();
  8371. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  8372. SDValue Res;
  8373. SDNodeFlags SDFlags;
  8374. if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
  8375. SDFlags.copyFMF(*FPMO);
  8376. switch (Intrinsic) {
  8377. case Intrinsic::vector_reduce_fadd:
  8378. if (SDFlags.hasAllowReassociation())
  8379. Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
  8380. DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
  8381. SDFlags);
  8382. else
  8383. Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
  8384. break;
  8385. case Intrinsic::vector_reduce_fmul:
  8386. if (SDFlags.hasAllowReassociation())
  8387. Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
  8388. DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
  8389. SDFlags);
  8390. else
  8391. Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
  8392. break;
  8393. case Intrinsic::vector_reduce_add:
  8394. Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
  8395. break;
  8396. case Intrinsic::vector_reduce_mul:
  8397. Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
  8398. break;
  8399. case Intrinsic::vector_reduce_and:
  8400. Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
  8401. break;
  8402. case Intrinsic::vector_reduce_or:
  8403. Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
  8404. break;
  8405. case Intrinsic::vector_reduce_xor:
  8406. Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
  8407. break;
  8408. case Intrinsic::vector_reduce_smax:
  8409. Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
  8410. break;
  8411. case Intrinsic::vector_reduce_smin:
  8412. Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
  8413. break;
  8414. case Intrinsic::vector_reduce_umax:
  8415. Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
  8416. break;
  8417. case Intrinsic::vector_reduce_umin:
  8418. Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
  8419. break;
  8420. case Intrinsic::vector_reduce_fmax:
  8421. Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
  8422. break;
  8423. case Intrinsic::vector_reduce_fmin:
  8424. Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
  8425. break;
  8426. default:
  8427. llvm_unreachable("Unhandled vector reduce intrinsic");
  8428. }
  8429. setValue(&I, Res);
  8430. }
  8431. /// Returns an AttributeList representing the attributes applied to the return
  8432. /// value of the given call.
  8433. static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
  8434. SmallVector<Attribute::AttrKind, 2> Attrs;
  8435. if (CLI.RetSExt)
  8436. Attrs.push_back(Attribute::SExt);
  8437. if (CLI.RetZExt)
  8438. Attrs.push_back(Attribute::ZExt);
  8439. if (CLI.IsInReg)
  8440. Attrs.push_back(Attribute::InReg);
  8441. return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
  8442. Attrs);
  8443. }
  8444. /// TargetLowering::LowerCallTo - This is the default LowerCallTo
  8445. /// implementation, which just calls LowerCall.
  8446. /// FIXME: When all targets are
  8447. /// migrated to using LowerCall, this hook should be integrated into SDISel.
  8448. std::pair<SDValue, SDValue>
  8449. TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
  8450. // Handle the incoming return values from the call.
  8451. CLI.Ins.clear();
  8452. Type *OrigRetTy = CLI.RetTy;
  8453. SmallVector<EVT, 4> RetTys;
  8454. SmallVector<uint64_t, 4> Offsets;
  8455. auto &DL = CLI.DAG.getDataLayout();
  8456. ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
  8457. if (CLI.IsPostTypeLegalization) {
  8458. // If we are lowering a libcall after legalization, split the return type.
  8459. SmallVector<EVT, 4> OldRetTys;
  8460. SmallVector<uint64_t, 4> OldOffsets;
  8461. RetTys.swap(OldRetTys);
  8462. Offsets.swap(OldOffsets);
  8463. for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
  8464. EVT RetVT = OldRetTys[i];
  8465. uint64_t Offset = OldOffsets[i];
  8466. MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
  8467. unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
  8468. unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
  8469. RetTys.append(NumRegs, RegisterVT);
  8470. for (unsigned j = 0; j != NumRegs; ++j)
  8471. Offsets.push_back(Offset + j * RegisterVTByteSZ);
  8472. }
  8473. }
  8474. SmallVector<ISD::OutputArg, 4> Outs;
  8475. GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
  8476. bool CanLowerReturn =
  8477. this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
  8478. CLI.IsVarArg, Outs, CLI.RetTy->getContext());
  8479. SDValue DemoteStackSlot;
  8480. int DemoteStackIdx = -100;
  8481. if (!CanLowerReturn) {
  8482. // FIXME: equivalent assert?
  8483. // assert(!CS.hasInAllocaArgument() &&
  8484. // "sret demotion is incompatible with inalloca");
  8485. uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
  8486. Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
  8487. MachineFunction &MF = CLI.DAG.getMachineFunction();
  8488. DemoteStackIdx =
  8489. MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
  8490. Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
  8491. DL.getAllocaAddrSpace());
  8492. DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
  8493. ArgListEntry Entry;
  8494. Entry.Node = DemoteStackSlot;
  8495. Entry.Ty = StackSlotPtrType;
  8496. Entry.IsSExt = false;
  8497. Entry.IsZExt = false;
  8498. Entry.IsInReg = false;
  8499. Entry.IsSRet = true;
  8500. Entry.IsNest = false;
  8501. Entry.IsByVal = false;
  8502. Entry.IsByRef = false;
  8503. Entry.IsReturned = false;
  8504. Entry.IsSwiftSelf = false;
  8505. Entry.IsSwiftAsync = false;
  8506. Entry.IsSwiftError = false;
  8507. Entry.IsCFGuardTarget = false;
  8508. Entry.Alignment = Alignment;
  8509. CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
  8510. CLI.NumFixedArgs += 1;
  8511. CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
  8512. // sret demotion isn't compatible with tail-calls, since the sret argument
  8513. // points into the callers stack frame.
  8514. CLI.IsTailCall = false;
  8515. } else {
  8516. bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
  8517. CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
  8518. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  8519. ISD::ArgFlagsTy Flags;
  8520. if (NeedsRegBlock) {
  8521. Flags.setInConsecutiveRegs();
  8522. if (I == RetTys.size() - 1)
  8523. Flags.setInConsecutiveRegsLast();
  8524. }
  8525. EVT VT = RetTys[I];
  8526. MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  8527. CLI.CallConv, VT);
  8528. unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  8529. CLI.CallConv, VT);
  8530. for (unsigned i = 0; i != NumRegs; ++i) {
  8531. ISD::InputArg MyFlags;
  8532. MyFlags.Flags = Flags;
  8533. MyFlags.VT = RegisterVT;
  8534. MyFlags.ArgVT = VT;
  8535. MyFlags.Used = CLI.IsReturnValueUsed;
  8536. if (CLI.RetTy->isPointerTy()) {
  8537. MyFlags.Flags.setPointer();
  8538. MyFlags.Flags.setPointerAddrSpace(
  8539. cast<PointerType>(CLI.RetTy)->getAddressSpace());
  8540. }
  8541. if (CLI.RetSExt)
  8542. MyFlags.Flags.setSExt();
  8543. if (CLI.RetZExt)
  8544. MyFlags.Flags.setZExt();
  8545. if (CLI.IsInReg)
  8546. MyFlags.Flags.setInReg();
  8547. CLI.Ins.push_back(MyFlags);
  8548. }
  8549. }
  8550. }
  8551. // We push in swifterror return as the last element of CLI.Ins.
  8552. ArgListTy &Args = CLI.getArgs();
  8553. if (supportSwiftError()) {
  8554. for (const ArgListEntry &Arg : Args) {
  8555. if (Arg.IsSwiftError) {
  8556. ISD::InputArg MyFlags;
  8557. MyFlags.VT = getPointerTy(DL);
  8558. MyFlags.ArgVT = EVT(getPointerTy(DL));
  8559. MyFlags.Flags.setSwiftError();
  8560. CLI.Ins.push_back(MyFlags);
  8561. }
  8562. }
  8563. }
  8564. // Handle all of the outgoing arguments.
  8565. CLI.Outs.clear();
  8566. CLI.OutVals.clear();
  8567. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  8568. SmallVector<EVT, 4> ValueVTs;
  8569. ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
  8570. // FIXME: Split arguments if CLI.IsPostTypeLegalization
  8571. Type *FinalType = Args[i].Ty;
  8572. if (Args[i].IsByVal)
  8573. FinalType = Args[i].IndirectType;
  8574. bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
  8575. FinalType, CLI.CallConv, CLI.IsVarArg, DL);
  8576. for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
  8577. ++Value) {
  8578. EVT VT = ValueVTs[Value];
  8579. Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
  8580. SDValue Op = SDValue(Args[i].Node.getNode(),
  8581. Args[i].Node.getResNo() + Value);
  8582. ISD::ArgFlagsTy Flags;
  8583. // Certain targets (such as MIPS), may have a different ABI alignment
  8584. // for a type depending on the context. Give the target a chance to
  8585. // specify the alignment it wants.
  8586. const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
  8587. Flags.setOrigAlign(OriginalAlignment);
  8588. if (Args[i].Ty->isPointerTy()) {
  8589. Flags.setPointer();
  8590. Flags.setPointerAddrSpace(
  8591. cast<PointerType>(Args[i].Ty)->getAddressSpace());
  8592. }
  8593. if (Args[i].IsZExt)
  8594. Flags.setZExt();
  8595. if (Args[i].IsSExt)
  8596. Flags.setSExt();
  8597. if (Args[i].IsInReg) {
  8598. // If we are using vectorcall calling convention, a structure that is
  8599. // passed InReg - is surely an HVA
  8600. if (CLI.CallConv == CallingConv::X86_VectorCall &&
  8601. isa<StructType>(FinalType)) {
  8602. // The first value of a structure is marked
  8603. if (0 == Value)
  8604. Flags.setHvaStart();
  8605. Flags.setHva();
  8606. }
  8607. // Set InReg Flag
  8608. Flags.setInReg();
  8609. }
  8610. if (Args[i].IsSRet)
  8611. Flags.setSRet();
  8612. if (Args[i].IsSwiftSelf)
  8613. Flags.setSwiftSelf();
  8614. if (Args[i].IsSwiftAsync)
  8615. Flags.setSwiftAsync();
  8616. if (Args[i].IsSwiftError)
  8617. Flags.setSwiftError();
  8618. if (Args[i].IsCFGuardTarget)
  8619. Flags.setCFGuardTarget();
  8620. if (Args[i].IsByVal)
  8621. Flags.setByVal();
  8622. if (Args[i].IsByRef)
  8623. Flags.setByRef();
  8624. if (Args[i].IsPreallocated) {
  8625. Flags.setPreallocated();
  8626. // Set the byval flag for CCAssignFn callbacks that don't know about
  8627. // preallocated. This way we can know how many bytes we should've
  8628. // allocated and how many bytes a callee cleanup function will pop. If
  8629. // we port preallocated to more targets, we'll have to add custom
  8630. // preallocated handling in the various CC lowering callbacks.
  8631. Flags.setByVal();
  8632. }
  8633. if (Args[i].IsInAlloca) {
  8634. Flags.setInAlloca();
  8635. // Set the byval flag for CCAssignFn callbacks that don't know about
  8636. // inalloca. This way we can know how many bytes we should've allocated
  8637. // and how many bytes a callee cleanup function will pop. If we port
  8638. // inalloca to more targets, we'll have to add custom inalloca handling
  8639. // in the various CC lowering callbacks.
  8640. Flags.setByVal();
  8641. }
  8642. Align MemAlign;
  8643. if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
  8644. unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
  8645. Flags.setByValSize(FrameSize);
  8646. // info is not there but there are cases it cannot get right.
  8647. if (auto MA = Args[i].Alignment)
  8648. MemAlign = *MA;
  8649. else
  8650. MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
  8651. } else if (auto MA = Args[i].Alignment) {
  8652. MemAlign = *MA;
  8653. } else {
  8654. MemAlign = OriginalAlignment;
  8655. }
  8656. Flags.setMemAlign(MemAlign);
  8657. if (Args[i].IsNest)
  8658. Flags.setNest();
  8659. if (NeedsRegBlock)
  8660. Flags.setInConsecutiveRegs();
  8661. MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  8662. CLI.CallConv, VT);
  8663. unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  8664. CLI.CallConv, VT);
  8665. SmallVector<SDValue, 4> Parts(NumParts);
  8666. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  8667. if (Args[i].IsSExt)
  8668. ExtendKind = ISD::SIGN_EXTEND;
  8669. else if (Args[i].IsZExt)
  8670. ExtendKind = ISD::ZERO_EXTEND;
  8671. // Conservatively only handle 'returned' on non-vectors that can be lowered,
  8672. // for now.
  8673. if (Args[i].IsReturned && !Op.getValueType().isVector() &&
  8674. CanLowerReturn) {
  8675. assert((CLI.RetTy == Args[i].Ty ||
  8676. (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
  8677. CLI.RetTy->getPointerAddressSpace() ==
  8678. Args[i].Ty->getPointerAddressSpace())) &&
  8679. RetTys.size() == NumValues && "unexpected use of 'returned'");
  8680. // Before passing 'returned' to the target lowering code, ensure that
  8681. // either the register MVT and the actual EVT are the same size or that
  8682. // the return value and argument are extended in the same way; in these
  8683. // cases it's safe to pass the argument register value unchanged as the
  8684. // return register value (although it's at the target's option whether
  8685. // to do so)
  8686. // TODO: allow code generation to take advantage of partially preserved
  8687. // registers rather than clobbering the entire register when the
  8688. // parameter extension method is not compatible with the return
  8689. // extension method
  8690. if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
  8691. (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
  8692. CLI.RetZExt == Args[i].IsZExt))
  8693. Flags.setReturned();
  8694. }
  8695. getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
  8696. CLI.CallConv, ExtendKind);
  8697. for (unsigned j = 0; j != NumParts; ++j) {
  8698. // if it isn't first piece, alignment must be 1
  8699. // For scalable vectors the scalable part is currently handled
  8700. // by individual targets, so we just use the known minimum size here.
  8701. ISD::OutputArg MyFlags(
  8702. Flags, Parts[j].getValueType().getSimpleVT(), VT,
  8703. i < CLI.NumFixedArgs, i,
  8704. j * Parts[j].getValueType().getStoreSize().getKnownMinSize());
  8705. if (NumParts > 1 && j == 0)
  8706. MyFlags.Flags.setSplit();
  8707. else if (j != 0) {
  8708. MyFlags.Flags.setOrigAlign(Align(1));
  8709. if (j == NumParts - 1)
  8710. MyFlags.Flags.setSplitEnd();
  8711. }
  8712. CLI.Outs.push_back(MyFlags);
  8713. CLI.OutVals.push_back(Parts[j]);
  8714. }
  8715. if (NeedsRegBlock && Value == NumValues - 1)
  8716. CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
  8717. }
  8718. }
  8719. SmallVector<SDValue, 4> InVals;
  8720. CLI.Chain = LowerCall(CLI, InVals);
  8721. // Update CLI.InVals to use outside of this function.
  8722. CLI.InVals = InVals;
  8723. // Verify that the target's LowerCall behaved as expected.
  8724. assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
  8725. "LowerCall didn't return a valid chain!");
  8726. assert((!CLI.IsTailCall || InVals.empty()) &&
  8727. "LowerCall emitted a return value for a tail call!");
  8728. assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
  8729. "LowerCall didn't emit the correct number of values!");
  8730. // For a tail call, the return value is merely live-out and there aren't
  8731. // any nodes in the DAG representing it. Return a special value to
  8732. // indicate that a tail call has been emitted and no more Instructions
  8733. // should be processed in the current block.
  8734. if (CLI.IsTailCall) {
  8735. CLI.DAG.setRoot(CLI.Chain);
  8736. return std::make_pair(SDValue(), SDValue());
  8737. }
  8738. #ifndef NDEBUG
  8739. for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
  8740. assert(InVals[i].getNode() && "LowerCall emitted a null value!");
  8741. assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
  8742. "LowerCall emitted a value with the wrong type!");
  8743. }
  8744. #endif
  8745. SmallVector<SDValue, 4> ReturnValues;
  8746. if (!CanLowerReturn) {
  8747. // The instruction result is the result of loading from the
  8748. // hidden sret parameter.
  8749. SmallVector<EVT, 1> PVTs;
  8750. Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
  8751. ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
  8752. assert(PVTs.size() == 1 && "Pointers should fit in one register");
  8753. EVT PtrVT = PVTs[0];
  8754. unsigned NumValues = RetTys.size();
  8755. ReturnValues.resize(NumValues);
  8756. SmallVector<SDValue, 4> Chains(NumValues);
  8757. // An aggregate return value cannot wrap around the address space, so
  8758. // offsets to its parts don't wrap either.
  8759. SDNodeFlags Flags;
  8760. Flags.setNoUnsignedWrap(true);
  8761. MachineFunction &MF = CLI.DAG.getMachineFunction();
  8762. Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
  8763. for (unsigned i = 0; i < NumValues; ++i) {
  8764. SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
  8765. CLI.DAG.getConstant(Offsets[i], CLI.DL,
  8766. PtrVT), Flags);
  8767. SDValue L = CLI.DAG.getLoad(
  8768. RetTys[i], CLI.DL, CLI.Chain, Add,
  8769. MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
  8770. DemoteStackIdx, Offsets[i]),
  8771. HiddenSRetAlign);
  8772. ReturnValues[i] = L;
  8773. Chains[i] = L.getValue(1);
  8774. }
  8775. CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
  8776. } else {
  8777. // Collect the legal value parts into potentially illegal values
  8778. // that correspond to the original function's return values.
  8779. Optional<ISD::NodeType> AssertOp;
  8780. if (CLI.RetSExt)
  8781. AssertOp = ISD::AssertSext;
  8782. else if (CLI.RetZExt)
  8783. AssertOp = ISD::AssertZext;
  8784. unsigned CurReg = 0;
  8785. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  8786. EVT VT = RetTys[I];
  8787. MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  8788. CLI.CallConv, VT);
  8789. unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  8790. CLI.CallConv, VT);
  8791. ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
  8792. NumRegs, RegisterVT, VT, nullptr,
  8793. CLI.CallConv, AssertOp));
  8794. CurReg += NumRegs;
  8795. }
  8796. // For a function returning void, there is no return value. We can't create
  8797. // such a node, so we just return a null return value in that case. In
  8798. // that case, nothing will actually look at the value.
  8799. if (ReturnValues.empty())
  8800. return std::make_pair(SDValue(), CLI.Chain);
  8801. }
  8802. SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
  8803. CLI.DAG.getVTList(RetTys), ReturnValues);
  8804. return std::make_pair(Res, CLI.Chain);
  8805. }
  8806. /// Places new result values for the node in Results (their number
  8807. /// and types must exactly match those of the original return values of
  8808. /// the node), or leaves Results empty, which indicates that the node is not
  8809. /// to be custom lowered after all.
  8810. void TargetLowering::LowerOperationWrapper(SDNode *N,
  8811. SmallVectorImpl<SDValue> &Results,
  8812. SelectionDAG &DAG) const {
  8813. SDValue Res = LowerOperation(SDValue(N, 0), DAG);
  8814. if (!Res.getNode())
  8815. return;
  8816. // If the original node has one result, take the return value from
  8817. // LowerOperation as is. It might not be result number 0.
  8818. if (N->getNumValues() == 1) {
  8819. Results.push_back(Res);
  8820. return;
  8821. }
  8822. // If the original node has multiple results, then the return node should
  8823. // have the same number of results.
  8824. assert((N->getNumValues() == Res->getNumValues()) &&
  8825. "Lowering returned the wrong number of results!");
  8826. // Places new result values base on N result number.
  8827. for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
  8828. Results.push_back(Res.getValue(I));
  8829. }
  8830. SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
  8831. llvm_unreachable("LowerOperation not implemented for this target!");
  8832. }
  8833. void
  8834. SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
  8835. SDValue Op = getNonRegisterValue(V);
  8836. assert((Op.getOpcode() != ISD::CopyFromReg ||
  8837. cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
  8838. "Copy from a reg to the same reg!");
  8839. assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
  8840. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8841. // If this is an InlineAsm we have to match the registers required, not the
  8842. // notional registers required by the type.
  8843. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
  8844. None); // This is not an ABI copy.
  8845. SDValue Chain = DAG.getEntryNode();
  8846. ISD::NodeType ExtendType = ISD::ANY_EXTEND;
  8847. auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
  8848. if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
  8849. ExtendType = PreferredExtendIt->second;
  8850. RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
  8851. PendingExports.push_back(Chain);
  8852. }
  8853. #include "llvm/CodeGen/SelectionDAGISel.h"
  8854. /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
  8855. /// entry block, return true. This includes arguments used by switches, since
  8856. /// the switch may expand into multiple basic blocks.
  8857. static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
  8858. // With FastISel active, we may be splitting blocks, so force creation
  8859. // of virtual registers for all non-dead arguments.
  8860. if (FastISel)
  8861. return A->use_empty();
  8862. const BasicBlock &Entry = A->getParent()->front();
  8863. for (const User *U : A->users())
  8864. if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
  8865. return false; // Use not in entry block.
  8866. return true;
  8867. }
  8868. using ArgCopyElisionMapTy =
  8869. DenseMap<const Argument *,
  8870. std::pair<const AllocaInst *, const StoreInst *>>;
  8871. /// Scan the entry block of the function in FuncInfo for arguments that look
  8872. /// like copies into a local alloca. Record any copied arguments in
  8873. /// ArgCopyElisionCandidates.
  8874. static void
  8875. findArgumentCopyElisionCandidates(const DataLayout &DL,
  8876. FunctionLoweringInfo *FuncInfo,
  8877. ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
  8878. // Record the state of every static alloca used in the entry block. Argument
  8879. // allocas are all used in the entry block, so we need approximately as many
  8880. // entries as we have arguments.
  8881. enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
  8882. SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
  8883. unsigned NumArgs = FuncInfo->Fn->arg_size();
  8884. StaticAllocas.reserve(NumArgs * 2);
  8885. auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
  8886. if (!V)
  8887. return nullptr;
  8888. V = V->stripPointerCasts();
  8889. const auto *AI = dyn_cast<AllocaInst>(V);
  8890. if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
  8891. return nullptr;
  8892. auto Iter = StaticAllocas.insert({AI, Unknown});
  8893. return &Iter.first->second;
  8894. };
  8895. // Look for stores of arguments to static allocas. Look through bitcasts and
  8896. // GEPs to handle type coercions, as long as the alloca is fully initialized
  8897. // by the store. Any non-store use of an alloca escapes it and any subsequent
  8898. // unanalyzed store might write it.
  8899. // FIXME: Handle structs initialized with multiple stores.
  8900. for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
  8901. // Look for stores, and handle non-store uses conservatively.
  8902. const auto *SI = dyn_cast<StoreInst>(&I);
  8903. if (!SI) {
  8904. // We will look through cast uses, so ignore them completely.
  8905. if (I.isCast())
  8906. continue;
  8907. // Ignore debug info and pseudo op intrinsics, they don't escape or store
  8908. // to allocas.
  8909. if (I.isDebugOrPseudoInst())
  8910. continue;
  8911. // This is an unknown instruction. Assume it escapes or writes to all
  8912. // static alloca operands.
  8913. for (const Use &U : I.operands()) {
  8914. if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
  8915. *Info = StaticAllocaInfo::Clobbered;
  8916. }
  8917. continue;
  8918. }
  8919. // If the stored value is a static alloca, mark it as escaped.
  8920. if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
  8921. *Info = StaticAllocaInfo::Clobbered;
  8922. // Check if the destination is a static alloca.
  8923. const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
  8924. StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
  8925. if (!Info)
  8926. continue;
  8927. const AllocaInst *AI = cast<AllocaInst>(Dst);
  8928. // Skip allocas that have been initialized or clobbered.
  8929. if (*Info != StaticAllocaInfo::Unknown)
  8930. continue;
  8931. // Check if the stored value is an argument, and that this store fully
  8932. // initializes the alloca.
  8933. // If the argument type has padding bits we can't directly forward a pointer
  8934. // as the upper bits may contain garbage.
  8935. // Don't elide copies from the same argument twice.
  8936. const Value *Val = SI->getValueOperand()->stripPointerCasts();
  8937. const auto *Arg = dyn_cast<Argument>(Val);
  8938. if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
  8939. Arg->getType()->isEmptyTy() ||
  8940. DL.getTypeStoreSize(Arg->getType()) !=
  8941. DL.getTypeAllocSize(AI->getAllocatedType()) ||
  8942. !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
  8943. ArgCopyElisionCandidates.count(Arg)) {
  8944. *Info = StaticAllocaInfo::Clobbered;
  8945. continue;
  8946. }
  8947. LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
  8948. << '\n');
  8949. // Mark this alloca and store for argument copy elision.
  8950. *Info = StaticAllocaInfo::Elidable;
  8951. ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
  8952. // Stop scanning if we've seen all arguments. This will happen early in -O0
  8953. // builds, which is useful, because -O0 builds have large entry blocks and
  8954. // many allocas.
  8955. if (ArgCopyElisionCandidates.size() == NumArgs)
  8956. break;
  8957. }
  8958. }
  8959. /// Try to elide argument copies from memory into a local alloca. Succeeds if
  8960. /// ArgVal is a load from a suitable fixed stack object.
  8961. static void tryToElideArgumentCopy(
  8962. FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
  8963. DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
  8964. SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
  8965. ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
  8966. SDValue ArgVal, bool &ArgHasUses) {
  8967. // Check if this is a load from a fixed stack object.
  8968. auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
  8969. if (!LNode)
  8970. return;
  8971. auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
  8972. if (!FINode)
  8973. return;
  8974. // Check that the fixed stack object is the right size and alignment.
  8975. // Look at the alignment that the user wrote on the alloca instead of looking
  8976. // at the stack object.
  8977. auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
  8978. assert(ArgCopyIter != ArgCopyElisionCandidates.end());
  8979. const AllocaInst *AI = ArgCopyIter->second.first;
  8980. int FixedIndex = FINode->getIndex();
  8981. int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
  8982. int OldIndex = AllocaIndex;
  8983. MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
  8984. if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
  8985. LLVM_DEBUG(
  8986. dbgs() << " argument copy elision failed due to bad fixed stack "
  8987. "object size\n");
  8988. return;
  8989. }
  8990. Align RequiredAlignment = AI->getAlign();
  8991. if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
  8992. LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca "
  8993. "greater than stack argument alignment ("
  8994. << DebugStr(RequiredAlignment) << " vs "
  8995. << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
  8996. return;
  8997. }
  8998. // Perform the elision. Delete the old stack object and replace its only use
  8999. // in the variable info map. Mark the stack object as mutable.
  9000. LLVM_DEBUG({
  9001. dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
  9002. << " Replacing frame index " << OldIndex << " with " << FixedIndex
  9003. << '\n';
  9004. });
  9005. MFI.RemoveStackObject(OldIndex);
  9006. MFI.setIsImmutableObjectIndex(FixedIndex, false);
  9007. AllocaIndex = FixedIndex;
  9008. ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
  9009. Chains.push_back(ArgVal.getValue(1));
  9010. // Avoid emitting code for the store implementing the copy.
  9011. const StoreInst *SI = ArgCopyIter->second.second;
  9012. ElidedArgCopyInstrs.insert(SI);
  9013. // Check for uses of the argument again so that we can avoid exporting ArgVal
  9014. // if it is't used by anything other than the store.
  9015. for (const Value *U : Arg.users()) {
  9016. if (U != SI) {
  9017. ArgHasUses = true;
  9018. break;
  9019. }
  9020. }
  9021. }
  9022. void SelectionDAGISel::LowerArguments(const Function &F) {
  9023. SelectionDAG &DAG = SDB->DAG;
  9024. SDLoc dl = SDB->getCurSDLoc();
  9025. const DataLayout &DL = DAG.getDataLayout();
  9026. SmallVector<ISD::InputArg, 16> Ins;
  9027. // In Naked functions we aren't going to save any registers.
  9028. if (F.hasFnAttribute(Attribute::Naked))
  9029. return;
  9030. if (!FuncInfo->CanLowerReturn) {
  9031. // Put in an sret pointer parameter before all the other parameters.
  9032. SmallVector<EVT, 1> ValueVTs;
  9033. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  9034. F.getReturnType()->getPointerTo(
  9035. DAG.getDataLayout().getAllocaAddrSpace()),
  9036. ValueVTs);
  9037. // NOTE: Assuming that a pointer will never break down to more than one VT
  9038. // or one register.
  9039. ISD::ArgFlagsTy Flags;
  9040. Flags.setSRet();
  9041. MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
  9042. ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
  9043. ISD::InputArg::NoArgIndex, 0);
  9044. Ins.push_back(RetArg);
  9045. }
  9046. // Look for stores of arguments to static allocas. Mark such arguments with a
  9047. // flag to ask the target to give us the memory location of that argument if
  9048. // available.
  9049. ArgCopyElisionMapTy ArgCopyElisionCandidates;
  9050. findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
  9051. ArgCopyElisionCandidates);
  9052. // Set up the incoming argument description vector.
  9053. for (const Argument &Arg : F.args()) {
  9054. unsigned ArgNo = Arg.getArgNo();
  9055. SmallVector<EVT, 4> ValueVTs;
  9056. ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
  9057. bool isArgValueUsed = !Arg.use_empty();
  9058. unsigned PartBase = 0;
  9059. Type *FinalType = Arg.getType();
  9060. if (Arg.hasAttribute(Attribute::ByVal))
  9061. FinalType = Arg.getParamByValType();
  9062. bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
  9063. FinalType, F.getCallingConv(), F.isVarArg(), DL);
  9064. for (unsigned Value = 0, NumValues = ValueVTs.size();
  9065. Value != NumValues; ++Value) {
  9066. EVT VT = ValueVTs[Value];
  9067. Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
  9068. ISD::ArgFlagsTy Flags;
  9069. if (Arg.getType()->isPointerTy()) {
  9070. Flags.setPointer();
  9071. Flags.setPointerAddrSpace(
  9072. cast<PointerType>(Arg.getType())->getAddressSpace());
  9073. }
  9074. if (Arg.hasAttribute(Attribute::ZExt))
  9075. Flags.setZExt();
  9076. if (Arg.hasAttribute(Attribute::SExt))
  9077. Flags.setSExt();
  9078. if (Arg.hasAttribute(Attribute::InReg)) {
  9079. // If we are using vectorcall calling convention, a structure that is
  9080. // passed InReg - is surely an HVA
  9081. if (F.getCallingConv() == CallingConv::X86_VectorCall &&
  9082. isa<StructType>(Arg.getType())) {
  9083. // The first value of a structure is marked
  9084. if (0 == Value)
  9085. Flags.setHvaStart();
  9086. Flags.setHva();
  9087. }
  9088. // Set InReg Flag
  9089. Flags.setInReg();
  9090. }
  9091. if (Arg.hasAttribute(Attribute::StructRet))
  9092. Flags.setSRet();
  9093. if (Arg.hasAttribute(Attribute::SwiftSelf))
  9094. Flags.setSwiftSelf();
  9095. if (Arg.hasAttribute(Attribute::SwiftAsync))
  9096. Flags.setSwiftAsync();
  9097. if (Arg.hasAttribute(Attribute::SwiftError))
  9098. Flags.setSwiftError();
  9099. if (Arg.hasAttribute(Attribute::ByVal))
  9100. Flags.setByVal();
  9101. if (Arg.hasAttribute(Attribute::ByRef))
  9102. Flags.setByRef();
  9103. if (Arg.hasAttribute(Attribute::InAlloca)) {
  9104. Flags.setInAlloca();
  9105. // Set the byval flag for CCAssignFn callbacks that don't know about
  9106. // inalloca. This way we can know how many bytes we should've allocated
  9107. // and how many bytes a callee cleanup function will pop. If we port
  9108. // inalloca to more targets, we'll have to add custom inalloca handling
  9109. // in the various CC lowering callbacks.
  9110. Flags.setByVal();
  9111. }
  9112. if (Arg.hasAttribute(Attribute::Preallocated)) {
  9113. Flags.setPreallocated();
  9114. // Set the byval flag for CCAssignFn callbacks that don't know about
  9115. // preallocated. This way we can know how many bytes we should've
  9116. // allocated and how many bytes a callee cleanup function will pop. If
  9117. // we port preallocated to more targets, we'll have to add custom
  9118. // preallocated handling in the various CC lowering callbacks.
  9119. Flags.setByVal();
  9120. }
  9121. // Certain targets (such as MIPS), may have a different ABI alignment
  9122. // for a type depending on the context. Give the target a chance to
  9123. // specify the alignment it wants.
  9124. const Align OriginalAlignment(
  9125. TLI->getABIAlignmentForCallingConv(ArgTy, DL));
  9126. Flags.setOrigAlign(OriginalAlignment);
  9127. Align MemAlign;
  9128. Type *ArgMemTy = nullptr;
  9129. if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
  9130. Flags.isByRef()) {
  9131. if (!ArgMemTy)
  9132. ArgMemTy = Arg.getPointeeInMemoryValueType();
  9133. uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
  9134. // For in-memory arguments, size and alignment should be passed from FE.
  9135. // BE will guess if this info is not there but there are cases it cannot
  9136. // get right.
  9137. if (auto ParamAlign = Arg.getParamStackAlign())
  9138. MemAlign = *ParamAlign;
  9139. else if ((ParamAlign = Arg.getParamAlign()))
  9140. MemAlign = *ParamAlign;
  9141. else
  9142. MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
  9143. if (Flags.isByRef())
  9144. Flags.setByRefSize(MemSize);
  9145. else
  9146. Flags.setByValSize(MemSize);
  9147. } else if (auto ParamAlign = Arg.getParamStackAlign()) {
  9148. MemAlign = *ParamAlign;
  9149. } else {
  9150. MemAlign = OriginalAlignment;
  9151. }
  9152. Flags.setMemAlign(MemAlign);
  9153. if (Arg.hasAttribute(Attribute::Nest))
  9154. Flags.setNest();
  9155. if (NeedsRegBlock)
  9156. Flags.setInConsecutiveRegs();
  9157. if (ArgCopyElisionCandidates.count(&Arg))
  9158. Flags.setCopyElisionCandidate();
  9159. if (Arg.hasAttribute(Attribute::Returned))
  9160. Flags.setReturned();
  9161. MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
  9162. *CurDAG->getContext(), F.getCallingConv(), VT);
  9163. unsigned NumRegs = TLI->getNumRegistersForCallingConv(
  9164. *CurDAG->getContext(), F.getCallingConv(), VT);
  9165. for (unsigned i = 0; i != NumRegs; ++i) {
  9166. // For scalable vectors, use the minimum size; individual targets
  9167. // are responsible for handling scalable vector arguments and
  9168. // return values.
  9169. ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
  9170. ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
  9171. if (NumRegs > 1 && i == 0)
  9172. MyFlags.Flags.setSplit();
  9173. // if it isn't first piece, alignment must be 1
  9174. else if (i > 0) {
  9175. MyFlags.Flags.setOrigAlign(Align(1));
  9176. if (i == NumRegs - 1)
  9177. MyFlags.Flags.setSplitEnd();
  9178. }
  9179. Ins.push_back(MyFlags);
  9180. }
  9181. if (NeedsRegBlock && Value == NumValues - 1)
  9182. Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
  9183. PartBase += VT.getStoreSize().getKnownMinSize();
  9184. }
  9185. }
  9186. // Call the target to set up the argument values.
  9187. SmallVector<SDValue, 8> InVals;
  9188. SDValue NewRoot = TLI->LowerFormalArguments(
  9189. DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
  9190. // Verify that the target's LowerFormalArguments behaved as expected.
  9191. assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
  9192. "LowerFormalArguments didn't return a valid chain!");
  9193. assert(InVals.size() == Ins.size() &&
  9194. "LowerFormalArguments didn't emit the correct number of values!");
  9195. LLVM_DEBUG({
  9196. for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
  9197. assert(InVals[i].getNode() &&
  9198. "LowerFormalArguments emitted a null value!");
  9199. assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
  9200. "LowerFormalArguments emitted a value with the wrong type!");
  9201. }
  9202. });
  9203. // Update the DAG with the new chain value resulting from argument lowering.
  9204. DAG.setRoot(NewRoot);
  9205. // Set up the argument values.
  9206. unsigned i = 0;
  9207. if (!FuncInfo->CanLowerReturn) {
  9208. // Create a virtual register for the sret pointer, and put in a copy
  9209. // from the sret argument into it.
  9210. SmallVector<EVT, 1> ValueVTs;
  9211. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  9212. F.getReturnType()->getPointerTo(
  9213. DAG.getDataLayout().getAllocaAddrSpace()),
  9214. ValueVTs);
  9215. MVT VT = ValueVTs[0].getSimpleVT();
  9216. MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
  9217. Optional<ISD::NodeType> AssertOp = None;
  9218. SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
  9219. nullptr, F.getCallingConv(), AssertOp);
  9220. MachineFunction& MF = SDB->DAG.getMachineFunction();
  9221. MachineRegisterInfo& RegInfo = MF.getRegInfo();
  9222. Register SRetReg =
  9223. RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
  9224. FuncInfo->DemoteRegister = SRetReg;
  9225. NewRoot =
  9226. SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
  9227. DAG.setRoot(NewRoot);
  9228. // i indexes lowered arguments. Bump it past the hidden sret argument.
  9229. ++i;
  9230. }
  9231. SmallVector<SDValue, 4> Chains;
  9232. DenseMap<int, int> ArgCopyElisionFrameIndexMap;
  9233. for (const Argument &Arg : F.args()) {
  9234. SmallVector<SDValue, 4> ArgValues;
  9235. SmallVector<EVT, 4> ValueVTs;
  9236. ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
  9237. unsigned NumValues = ValueVTs.size();
  9238. if (NumValues == 0)
  9239. continue;
  9240. bool ArgHasUses = !Arg.use_empty();
  9241. // Elide the copying store if the target loaded this argument from a
  9242. // suitable fixed stack object.
  9243. if (Ins[i].Flags.isCopyElisionCandidate()) {
  9244. tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
  9245. ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
  9246. InVals[i], ArgHasUses);
  9247. }
  9248. // If this argument is unused then remember its value. It is used to generate
  9249. // debugging information.
  9250. bool isSwiftErrorArg =
  9251. TLI->supportSwiftError() &&
  9252. Arg.hasAttribute(Attribute::SwiftError);
  9253. if (!ArgHasUses && !isSwiftErrorArg) {
  9254. SDB->setUnusedArgValue(&Arg, InVals[i]);
  9255. // Also remember any frame index for use in FastISel.
  9256. if (FrameIndexSDNode *FI =
  9257. dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
  9258. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  9259. }
  9260. for (unsigned Val = 0; Val != NumValues; ++Val) {
  9261. EVT VT = ValueVTs[Val];
  9262. MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
  9263. F.getCallingConv(), VT);
  9264. unsigned NumParts = TLI->getNumRegistersForCallingConv(
  9265. *CurDAG->getContext(), F.getCallingConv(), VT);
  9266. // Even an apparent 'unused' swifterror argument needs to be returned. So
  9267. // we do generate a copy for it that can be used on return from the
  9268. // function.
  9269. if (ArgHasUses || isSwiftErrorArg) {
  9270. Optional<ISD::NodeType> AssertOp;
  9271. if (Arg.hasAttribute(Attribute::SExt))
  9272. AssertOp = ISD::AssertSext;
  9273. else if (Arg.hasAttribute(Attribute::ZExt))
  9274. AssertOp = ISD::AssertZext;
  9275. ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
  9276. PartVT, VT, nullptr,
  9277. F.getCallingConv(), AssertOp));
  9278. }
  9279. i += NumParts;
  9280. }
  9281. // We don't need to do anything else for unused arguments.
  9282. if (ArgValues.empty())
  9283. continue;
  9284. // Note down frame index.
  9285. if (FrameIndexSDNode *FI =
  9286. dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
  9287. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  9288. SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
  9289. SDB->getCurSDLoc());
  9290. SDB->setValue(&Arg, Res);
  9291. if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
  9292. // We want to associate the argument with the frame index, among
  9293. // involved operands, that correspond to the lowest address. The
  9294. // getCopyFromParts function, called earlier, is swapping the order of
  9295. // the operands to BUILD_PAIR depending on endianness. The result of
  9296. // that swapping is that the least significant bits of the argument will
  9297. // be in the first operand of the BUILD_PAIR node, and the most
  9298. // significant bits will be in the second operand.
  9299. unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
  9300. if (LoadSDNode *LNode =
  9301. dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
  9302. if (FrameIndexSDNode *FI =
  9303. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  9304. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  9305. }
  9306. // Analyses past this point are naive and don't expect an assertion.
  9307. if (Res.getOpcode() == ISD::AssertZext)
  9308. Res = Res.getOperand(0);
  9309. // Update the SwiftErrorVRegDefMap.
  9310. if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
  9311. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  9312. if (Register::isVirtualRegister(Reg))
  9313. SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
  9314. Reg);
  9315. }
  9316. // If this argument is live outside of the entry block, insert a copy from
  9317. // wherever we got it to the vreg that other BB's will reference it as.
  9318. if (Res.getOpcode() == ISD::CopyFromReg) {
  9319. // If we can, though, try to skip creating an unnecessary vreg.
  9320. // FIXME: This isn't very clean... it would be nice to make this more
  9321. // general.
  9322. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  9323. if (Register::isVirtualRegister(Reg)) {
  9324. FuncInfo->ValueMap[&Arg] = Reg;
  9325. continue;
  9326. }
  9327. }
  9328. if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
  9329. FuncInfo->InitializeRegForValue(&Arg);
  9330. SDB->CopyToExportRegsIfNeeded(&Arg);
  9331. }
  9332. }
  9333. if (!Chains.empty()) {
  9334. Chains.push_back(NewRoot);
  9335. NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  9336. }
  9337. DAG.setRoot(NewRoot);
  9338. assert(i == InVals.size() && "Argument register count mismatch!");
  9339. // If any argument copy elisions occurred and we have debug info, update the
  9340. // stale frame indices used in the dbg.declare variable info table.
  9341. MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
  9342. if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
  9343. for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
  9344. auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
  9345. if (I != ArgCopyElisionFrameIndexMap.end())
  9346. VI.Slot = I->second;
  9347. }
  9348. }
  9349. // Finally, if the target has anything special to do, allow it to do so.
  9350. emitFunctionEntryCode();
  9351. }
  9352. /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
  9353. /// ensure constants are generated when needed. Remember the virtual registers
  9354. /// that need to be added to the Machine PHI nodes as input. We cannot just
  9355. /// directly add them, because expansion might result in multiple MBB's for one
  9356. /// BB. As such, the start of the BB might correspond to a different MBB than
  9357. /// the end.
  9358. void
  9359. SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
  9360. const Instruction *TI = LLVMBB->getTerminator();
  9361. SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
  9362. // Check PHI nodes in successors that expect a value to be available from this
  9363. // block.
  9364. for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
  9365. const BasicBlock *SuccBB = TI->getSuccessor(succ);
  9366. if (!isa<PHINode>(SuccBB->begin())) continue;
  9367. MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
  9368. // If this terminator has multiple identical successors (common for
  9369. // switches), only handle each succ once.
  9370. if (!SuccsHandled.insert(SuccMBB).second)
  9371. continue;
  9372. MachineBasicBlock::iterator MBBI = SuccMBB->begin();
  9373. // At this point we know that there is a 1-1 correspondence between LLVM PHI
  9374. // nodes and Machine PHI nodes, but the incoming operands have not been
  9375. // emitted yet.
  9376. for (const PHINode &PN : SuccBB->phis()) {
  9377. // Ignore dead phi's.
  9378. if (PN.use_empty())
  9379. continue;
  9380. // Skip empty types
  9381. if (PN.getType()->isEmptyTy())
  9382. continue;
  9383. unsigned Reg;
  9384. const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
  9385. if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
  9386. unsigned &RegOut = ConstantsOut[C];
  9387. if (RegOut == 0) {
  9388. RegOut = FuncInfo.CreateRegs(C);
  9389. CopyValueToVirtualRegister(C, RegOut);
  9390. }
  9391. Reg = RegOut;
  9392. } else {
  9393. DenseMap<const Value *, Register>::iterator I =
  9394. FuncInfo.ValueMap.find(PHIOp);
  9395. if (I != FuncInfo.ValueMap.end())
  9396. Reg = I->second;
  9397. else {
  9398. assert(isa<AllocaInst>(PHIOp) &&
  9399. FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
  9400. "Didn't codegen value into a register!??");
  9401. Reg = FuncInfo.CreateRegs(PHIOp);
  9402. CopyValueToVirtualRegister(PHIOp, Reg);
  9403. }
  9404. }
  9405. // Remember that this register needs to added to the machine PHI node as
  9406. // the input for this MBB.
  9407. SmallVector<EVT, 4> ValueVTs;
  9408. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  9409. ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
  9410. for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
  9411. EVT VT = ValueVTs[vti];
  9412. unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
  9413. for (unsigned i = 0, e = NumRegisters; i != e; ++i)
  9414. FuncInfo.PHINodesToUpdate.push_back(
  9415. std::make_pair(&*MBBI++, Reg + i));
  9416. Reg += NumRegisters;
  9417. }
  9418. }
  9419. }
  9420. ConstantsOut.clear();
  9421. }
  9422. MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
  9423. MachineFunction::iterator I(MBB);
  9424. if (++I == FuncInfo.MF->end())
  9425. return nullptr;
  9426. return &*I;
  9427. }
  9428. /// During lowering new call nodes can be created (such as memset, etc.).
  9429. /// Those will become new roots of the current DAG, but complications arise
  9430. /// when they are tail calls. In such cases, the call lowering will update
  9431. /// the root, but the builder still needs to know that a tail call has been
  9432. /// lowered in order to avoid generating an additional return.
  9433. void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
  9434. // If the node is null, we do have a tail call.
  9435. if (MaybeTC.getNode() != nullptr)
  9436. DAG.setRoot(MaybeTC);
  9437. else
  9438. HasTailCall = true;
  9439. }
  9440. void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
  9441. MachineBasicBlock *SwitchMBB,
  9442. MachineBasicBlock *DefaultMBB) {
  9443. MachineFunction *CurMF = FuncInfo.MF;
  9444. MachineBasicBlock *NextMBB = nullptr;
  9445. MachineFunction::iterator BBI(W.MBB);
  9446. if (++BBI != FuncInfo.MF->end())
  9447. NextMBB = &*BBI;
  9448. unsigned Size = W.LastCluster - W.FirstCluster + 1;
  9449. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  9450. if (Size == 2 && W.MBB == SwitchMBB) {
  9451. // If any two of the cases has the same destination, and if one value
  9452. // is the same as the other, but has one bit unset that the other has set,
  9453. // use bit manipulation to do two compares at once. For example:
  9454. // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
  9455. // TODO: This could be extended to merge any 2 cases in switches with 3
  9456. // cases.
  9457. // TODO: Handle cases where W.CaseBB != SwitchBB.
  9458. CaseCluster &Small = *W.FirstCluster;
  9459. CaseCluster &Big = *W.LastCluster;
  9460. if (Small.Low == Small.High && Big.Low == Big.High &&
  9461. Small.MBB == Big.MBB) {
  9462. const APInt &SmallValue = Small.Low->getValue();
  9463. const APInt &BigValue = Big.Low->getValue();
  9464. // Check that there is only one bit different.
  9465. APInt CommonBit = BigValue ^ SmallValue;
  9466. if (CommonBit.isPowerOf2()) {
  9467. SDValue CondLHS = getValue(Cond);
  9468. EVT VT = CondLHS.getValueType();
  9469. SDLoc DL = getCurSDLoc();
  9470. SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
  9471. DAG.getConstant(CommonBit, DL, VT));
  9472. SDValue Cond = DAG.getSetCC(
  9473. DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
  9474. ISD::SETEQ);
  9475. // Update successor info.
  9476. // Both Small and Big will jump to Small.BB, so we sum up the
  9477. // probabilities.
  9478. addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
  9479. if (BPI)
  9480. addSuccessorWithProb(
  9481. SwitchMBB, DefaultMBB,
  9482. // The default destination is the first successor in IR.
  9483. BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
  9484. else
  9485. addSuccessorWithProb(SwitchMBB, DefaultMBB);
  9486. // Insert the true branch.
  9487. SDValue BrCond =
  9488. DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
  9489. DAG.getBasicBlock(Small.MBB));
  9490. // Insert the false branch.
  9491. BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
  9492. DAG.getBasicBlock(DefaultMBB));
  9493. DAG.setRoot(BrCond);
  9494. return;
  9495. }
  9496. }
  9497. }
  9498. if (TM.getOptLevel() != CodeGenOpt::None) {
  9499. // Here, we order cases by probability so the most likely case will be
  9500. // checked first. However, two clusters can have the same probability in
  9501. // which case their relative ordering is non-deterministic. So we use Low
  9502. // as a tie-breaker as clusters are guaranteed to never overlap.
  9503. llvm::sort(W.FirstCluster, W.LastCluster + 1,
  9504. [](const CaseCluster &a, const CaseCluster &b) {
  9505. return a.Prob != b.Prob ?
  9506. a.Prob > b.Prob :
  9507. a.Low->getValue().slt(b.Low->getValue());
  9508. });
  9509. // Rearrange the case blocks so that the last one falls through if possible
  9510. // without changing the order of probabilities.
  9511. for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
  9512. --I;
  9513. if (I->Prob > W.LastCluster->Prob)
  9514. break;
  9515. if (I->Kind == CC_Range && I->MBB == NextMBB) {
  9516. std::swap(*I, *W.LastCluster);
  9517. break;
  9518. }
  9519. }
  9520. }
  9521. // Compute total probability.
  9522. BranchProbability DefaultProb = W.DefaultProb;
  9523. BranchProbability UnhandledProbs = DefaultProb;
  9524. for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
  9525. UnhandledProbs += I->Prob;
  9526. MachineBasicBlock *CurMBB = W.MBB;
  9527. for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
  9528. bool FallthroughUnreachable = false;
  9529. MachineBasicBlock *Fallthrough;
  9530. if (I == W.LastCluster) {
  9531. // For the last cluster, fall through to the default destination.
  9532. Fallthrough = DefaultMBB;
  9533. FallthroughUnreachable = isa<UnreachableInst>(
  9534. DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
  9535. } else {
  9536. Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
  9537. CurMF->insert(BBI, Fallthrough);
  9538. // Put Cond in a virtual register to make it available from the new blocks.
  9539. ExportFromCurrentBlock(Cond);
  9540. }
  9541. UnhandledProbs -= I->Prob;
  9542. switch (I->Kind) {
  9543. case CC_JumpTable: {
  9544. // FIXME: Optimize away range check based on pivot comparisons.
  9545. JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
  9546. SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
  9547. // The jump block hasn't been inserted yet; insert it here.
  9548. MachineBasicBlock *JumpMBB = JT->MBB;
  9549. CurMF->insert(BBI, JumpMBB);
  9550. auto JumpProb = I->Prob;
  9551. auto FallthroughProb = UnhandledProbs;
  9552. // If the default statement is a target of the jump table, we evenly
  9553. // distribute the default probability to successors of CurMBB. Also
  9554. // update the probability on the edge from JumpMBB to Fallthrough.
  9555. for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
  9556. SE = JumpMBB->succ_end();
  9557. SI != SE; ++SI) {
  9558. if (*SI == DefaultMBB) {
  9559. JumpProb += DefaultProb / 2;
  9560. FallthroughProb -= DefaultProb / 2;
  9561. JumpMBB->setSuccProbability(SI, DefaultProb / 2);
  9562. JumpMBB->normalizeSuccProbs();
  9563. break;
  9564. }
  9565. }
  9566. if (FallthroughUnreachable)
  9567. JTH->FallthroughUnreachable = true;
  9568. if (!JTH->FallthroughUnreachable)
  9569. addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
  9570. addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
  9571. CurMBB->normalizeSuccProbs();
  9572. // The jump table header will be inserted in our current block, do the
  9573. // range check, and fall through to our fallthrough block.
  9574. JTH->HeaderBB = CurMBB;
  9575. JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
  9576. // If we're in the right place, emit the jump table header right now.
  9577. if (CurMBB == SwitchMBB) {
  9578. visitJumpTableHeader(*JT, *JTH, SwitchMBB);
  9579. JTH->Emitted = true;
  9580. }
  9581. break;
  9582. }
  9583. case CC_BitTests: {
  9584. // FIXME: Optimize away range check based on pivot comparisons.
  9585. BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
  9586. // The bit test blocks haven't been inserted yet; insert them here.
  9587. for (BitTestCase &BTC : BTB->Cases)
  9588. CurMF->insert(BBI, BTC.ThisBB);
  9589. // Fill in fields of the BitTestBlock.
  9590. BTB->Parent = CurMBB;
  9591. BTB->Default = Fallthrough;
  9592. BTB->DefaultProb = UnhandledProbs;
  9593. // If the cases in bit test don't form a contiguous range, we evenly
  9594. // distribute the probability on the edge to Fallthrough to two
  9595. // successors of CurMBB.
  9596. if (!BTB->ContiguousRange) {
  9597. BTB->Prob += DefaultProb / 2;
  9598. BTB->DefaultProb -= DefaultProb / 2;
  9599. }
  9600. if (FallthroughUnreachable)
  9601. BTB->FallthroughUnreachable = true;
  9602. // If we're in the right place, emit the bit test header right now.
  9603. if (CurMBB == SwitchMBB) {
  9604. visitBitTestHeader(*BTB, SwitchMBB);
  9605. BTB->Emitted = true;
  9606. }
  9607. break;
  9608. }
  9609. case CC_Range: {
  9610. const Value *RHS, *LHS, *MHS;
  9611. ISD::CondCode CC;
  9612. if (I->Low == I->High) {
  9613. // Check Cond == I->Low.
  9614. CC = ISD::SETEQ;
  9615. LHS = Cond;
  9616. RHS=I->Low;
  9617. MHS = nullptr;
  9618. } else {
  9619. // Check I->Low <= Cond <= I->High.
  9620. CC = ISD::SETLE;
  9621. LHS = I->Low;
  9622. MHS = Cond;
  9623. RHS = I->High;
  9624. }
  9625. // If Fallthrough is unreachable, fold away the comparison.
  9626. if (FallthroughUnreachable)
  9627. CC = ISD::SETTRUE;
  9628. // The false probability is the sum of all unhandled cases.
  9629. CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
  9630. getCurSDLoc(), I->Prob, UnhandledProbs);
  9631. if (CurMBB == SwitchMBB)
  9632. visitSwitchCase(CB, SwitchMBB);
  9633. else
  9634. SL->SwitchCases.push_back(CB);
  9635. break;
  9636. }
  9637. }
  9638. CurMBB = Fallthrough;
  9639. }
  9640. }
  9641. unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
  9642. CaseClusterIt First,
  9643. CaseClusterIt Last) {
  9644. return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
  9645. if (X.Prob != CC.Prob)
  9646. return X.Prob > CC.Prob;
  9647. // Ties are broken by comparing the case value.
  9648. return X.Low->getValue().slt(CC.Low->getValue());
  9649. });
  9650. }
  9651. void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
  9652. const SwitchWorkListItem &W,
  9653. Value *Cond,
  9654. MachineBasicBlock *SwitchMBB) {
  9655. assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
  9656. "Clusters not sorted?");
  9657. assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
  9658. // Balance the tree based on branch probabilities to create a near-optimal (in
  9659. // terms of search time given key frequency) binary search tree. See e.g. Kurt
  9660. // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
  9661. CaseClusterIt LastLeft = W.FirstCluster;
  9662. CaseClusterIt FirstRight = W.LastCluster;
  9663. auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
  9664. auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
  9665. // Move LastLeft and FirstRight towards each other from opposite directions to
  9666. // find a partitioning of the clusters which balances the probability on both
  9667. // sides. If LeftProb and RightProb are equal, alternate which side is
  9668. // taken to ensure 0-probability nodes are distributed evenly.
  9669. unsigned I = 0;
  9670. while (LastLeft + 1 < FirstRight) {
  9671. if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
  9672. LeftProb += (++LastLeft)->Prob;
  9673. else
  9674. RightProb += (--FirstRight)->Prob;
  9675. I++;
  9676. }
  9677. while (true) {
  9678. // Our binary search tree differs from a typical BST in that ours can have up
  9679. // to three values in each leaf. The pivot selection above doesn't take that
  9680. // into account, which means the tree might require more nodes and be less
  9681. // efficient. We compensate for this here.
  9682. unsigned NumLeft = LastLeft - W.FirstCluster + 1;
  9683. unsigned NumRight = W.LastCluster - FirstRight + 1;
  9684. if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
  9685. // If one side has less than 3 clusters, and the other has more than 3,
  9686. // consider taking a cluster from the other side.
  9687. if (NumLeft < NumRight) {
  9688. // Consider moving the first cluster on the right to the left side.
  9689. CaseCluster &CC = *FirstRight;
  9690. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  9691. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  9692. if (LeftSideRank <= RightSideRank) {
  9693. // Moving the cluster to the left does not demote it.
  9694. ++LastLeft;
  9695. ++FirstRight;
  9696. continue;
  9697. }
  9698. } else {
  9699. assert(NumRight < NumLeft);
  9700. // Consider moving the last element on the left to the right side.
  9701. CaseCluster &CC = *LastLeft;
  9702. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  9703. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  9704. if (RightSideRank <= LeftSideRank) {
  9705. // Moving the cluster to the right does not demot it.
  9706. --LastLeft;
  9707. --FirstRight;
  9708. continue;
  9709. }
  9710. }
  9711. }
  9712. break;
  9713. }
  9714. assert(LastLeft + 1 == FirstRight);
  9715. assert(LastLeft >= W.FirstCluster);
  9716. assert(FirstRight <= W.LastCluster);
  9717. // Use the first element on the right as pivot since we will make less-than
  9718. // comparisons against it.
  9719. CaseClusterIt PivotCluster = FirstRight;
  9720. assert(PivotCluster > W.FirstCluster);
  9721. assert(PivotCluster <= W.LastCluster);
  9722. CaseClusterIt FirstLeft = W.FirstCluster;
  9723. CaseClusterIt LastRight = W.LastCluster;
  9724. const ConstantInt *Pivot = PivotCluster->Low;
  9725. // New blocks will be inserted immediately after the current one.
  9726. MachineFunction::iterator BBI(W.MBB);
  9727. ++BBI;
  9728. // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
  9729. // we can branch to its destination directly if it's squeezed exactly in
  9730. // between the known lower bound and Pivot - 1.
  9731. MachineBasicBlock *LeftMBB;
  9732. if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
  9733. FirstLeft->Low == W.GE &&
  9734. (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
  9735. LeftMBB = FirstLeft->MBB;
  9736. } else {
  9737. LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  9738. FuncInfo.MF->insert(BBI, LeftMBB);
  9739. WorkList.push_back(
  9740. {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
  9741. // Put Cond in a virtual register to make it available from the new blocks.
  9742. ExportFromCurrentBlock(Cond);
  9743. }
  9744. // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
  9745. // single cluster, RHS.Low == Pivot, and we can branch to its destination
  9746. // directly if RHS.High equals the current upper bound.
  9747. MachineBasicBlock *RightMBB;
  9748. if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
  9749. W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
  9750. RightMBB = FirstRight->MBB;
  9751. } else {
  9752. RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  9753. FuncInfo.MF->insert(BBI, RightMBB);
  9754. WorkList.push_back(
  9755. {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
  9756. // Put Cond in a virtual register to make it available from the new blocks.
  9757. ExportFromCurrentBlock(Cond);
  9758. }
  9759. // Create the CaseBlock record that will be used to lower the branch.
  9760. CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
  9761. getCurSDLoc(), LeftProb, RightProb);
  9762. if (W.MBB == SwitchMBB)
  9763. visitSwitchCase(CB, SwitchMBB);
  9764. else
  9765. SL->SwitchCases.push_back(CB);
  9766. }
  9767. // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
  9768. // from the swith statement.
  9769. static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
  9770. BranchProbability PeeledCaseProb) {
  9771. if (PeeledCaseProb == BranchProbability::getOne())
  9772. return BranchProbability::getZero();
  9773. BranchProbability SwitchProb = PeeledCaseProb.getCompl();
  9774. uint32_t Numerator = CaseProb.getNumerator();
  9775. uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
  9776. return BranchProbability(Numerator, std::max(Numerator, Denominator));
  9777. }
  9778. // Try to peel the top probability case if it exceeds the threshold.
  9779. // Return current MachineBasicBlock for the switch statement if the peeling
  9780. // does not occur.
  9781. // If the peeling is performed, return the newly created MachineBasicBlock
  9782. // for the peeled switch statement. Also update Clusters to remove the peeled
  9783. // case. PeeledCaseProb is the BranchProbability for the peeled case.
  9784. MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
  9785. const SwitchInst &SI, CaseClusterVector &Clusters,
  9786. BranchProbability &PeeledCaseProb) {
  9787. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  9788. // Don't perform if there is only one cluster or optimizing for size.
  9789. if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
  9790. TM.getOptLevel() == CodeGenOpt::None ||
  9791. SwitchMBB->getParent()->getFunction().hasMinSize())
  9792. return SwitchMBB;
  9793. BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
  9794. unsigned PeeledCaseIndex = 0;
  9795. bool SwitchPeeled = false;
  9796. for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
  9797. CaseCluster &CC = Clusters[Index];
  9798. if (CC.Prob < TopCaseProb)
  9799. continue;
  9800. TopCaseProb = CC.Prob;
  9801. PeeledCaseIndex = Index;
  9802. SwitchPeeled = true;
  9803. }
  9804. if (!SwitchPeeled)
  9805. return SwitchMBB;
  9806. LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
  9807. << TopCaseProb << "\n");
  9808. // Record the MBB for the peeled switch statement.
  9809. MachineFunction::iterator BBI(SwitchMBB);
  9810. ++BBI;
  9811. MachineBasicBlock *PeeledSwitchMBB =
  9812. FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
  9813. FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
  9814. ExportFromCurrentBlock(SI.getCondition());
  9815. auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
  9816. SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
  9817. nullptr, nullptr, TopCaseProb.getCompl()};
  9818. lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
  9819. Clusters.erase(PeeledCaseIt);
  9820. for (CaseCluster &CC : Clusters) {
  9821. LLVM_DEBUG(
  9822. dbgs() << "Scale the probablity for one cluster, before scaling: "
  9823. << CC.Prob << "\n");
  9824. CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
  9825. LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
  9826. }
  9827. PeeledCaseProb = TopCaseProb;
  9828. return PeeledSwitchMBB;
  9829. }
  9830. void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
  9831. // Extract cases from the switch.
  9832. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  9833. CaseClusterVector Clusters;
  9834. Clusters.reserve(SI.getNumCases());
  9835. for (auto I : SI.cases()) {
  9836. MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
  9837. const ConstantInt *CaseVal = I.getCaseValue();
  9838. BranchProbability Prob =
  9839. BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
  9840. : BranchProbability(1, SI.getNumCases() + 1);
  9841. Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
  9842. }
  9843. MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
  9844. // Cluster adjacent cases with the same destination. We do this at all
  9845. // optimization levels because it's cheap to do and will make codegen faster
  9846. // if there are many clusters.
  9847. sortAndRangeify(Clusters);
  9848. // The branch probablity of the peeled case.
  9849. BranchProbability PeeledCaseProb = BranchProbability::getZero();
  9850. MachineBasicBlock *PeeledSwitchMBB =
  9851. peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
  9852. // If there is only the default destination, jump there directly.
  9853. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  9854. if (Clusters.empty()) {
  9855. assert(PeeledSwitchMBB == SwitchMBB);
  9856. SwitchMBB->addSuccessor(DefaultMBB);
  9857. if (DefaultMBB != NextBlock(SwitchMBB)) {
  9858. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  9859. getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
  9860. }
  9861. return;
  9862. }
  9863. SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
  9864. SL->findBitTestClusters(Clusters, &SI);
  9865. LLVM_DEBUG({
  9866. dbgs() << "Case clusters: ";
  9867. for (const CaseCluster &C : Clusters) {
  9868. if (C.Kind == CC_JumpTable)
  9869. dbgs() << "JT:";
  9870. if (C.Kind == CC_BitTests)
  9871. dbgs() << "BT:";
  9872. C.Low->getValue().print(dbgs(), true);
  9873. if (C.Low != C.High) {
  9874. dbgs() << '-';
  9875. C.High->getValue().print(dbgs(), true);
  9876. }
  9877. dbgs() << ' ';
  9878. }
  9879. dbgs() << '\n';
  9880. });
  9881. assert(!Clusters.empty());
  9882. SwitchWorkList WorkList;
  9883. CaseClusterIt First = Clusters.begin();
  9884. CaseClusterIt Last = Clusters.end() - 1;
  9885. auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
  9886. // Scale the branchprobability for DefaultMBB if the peel occurs and
  9887. // DefaultMBB is not replaced.
  9888. if (PeeledCaseProb != BranchProbability::getZero() &&
  9889. DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
  9890. DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
  9891. WorkList.push_back(
  9892. {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
  9893. while (!WorkList.empty()) {
  9894. SwitchWorkListItem W = WorkList.pop_back_val();
  9895. unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
  9896. if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
  9897. !DefaultMBB->getParent()->getFunction().hasMinSize()) {
  9898. // For optimized builds, lower large range as a balanced binary tree.
  9899. splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
  9900. continue;
  9901. }
  9902. lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
  9903. }
  9904. }
  9905. void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
  9906. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  9907. auto DL = getCurSDLoc();
  9908. EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  9909. setValue(&I, DAG.getStepVector(DL, ResultVT));
  9910. }
  9911. void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
  9912. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  9913. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  9914. SDLoc DL = getCurSDLoc();
  9915. SDValue V = getValue(I.getOperand(0));
  9916. assert(VT == V.getValueType() && "Malformed vector.reverse!");
  9917. if (VT.isScalableVector()) {
  9918. setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
  9919. return;
  9920. }
  9921. // Use VECTOR_SHUFFLE for the fixed-length vector
  9922. // to maintain existing behavior.
  9923. SmallVector<int, 8> Mask;
  9924. unsigned NumElts = VT.getVectorMinNumElements();
  9925. for (unsigned i = 0; i != NumElts; ++i)
  9926. Mask.push_back(NumElts - 1 - i);
  9927. setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
  9928. }
  9929. void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
  9930. SmallVector<EVT, 4> ValueVTs;
  9931. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
  9932. ValueVTs);
  9933. unsigned NumValues = ValueVTs.size();
  9934. if (NumValues == 0) return;
  9935. SmallVector<SDValue, 4> Values(NumValues);
  9936. SDValue Op = getValue(I.getOperand(0));
  9937. for (unsigned i = 0; i != NumValues; ++i)
  9938. Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
  9939. SDValue(Op.getNode(), Op.getResNo() + i));
  9940. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  9941. DAG.getVTList(ValueVTs), Values));
  9942. }
  9943. void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
  9944. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  9945. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  9946. SDLoc DL = getCurSDLoc();
  9947. SDValue V1 = getValue(I.getOperand(0));
  9948. SDValue V2 = getValue(I.getOperand(1));
  9949. int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
  9950. // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
  9951. if (VT.isScalableVector()) {
  9952. MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
  9953. setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
  9954. DAG.getConstant(Imm, DL, IdxVT)));
  9955. return;
  9956. }
  9957. unsigned NumElts = VT.getVectorNumElements();
  9958. uint64_t Idx = (NumElts + Imm) % NumElts;
  9959. // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
  9960. SmallVector<int, 8> Mask;
  9961. for (unsigned i = 0; i < NumElts; ++i)
  9962. Mask.push_back(Idx + i);
  9963. setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
  9964. }