SelectionDAGBuilder.cpp 403 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362
  1. //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This implements routines for translating from LLVM IR into SelectionDAG IR.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "SelectionDAGBuilder.h"
  14. #include "SDNodeDbgValue.h"
  15. #include "llvm/ADT/APFloat.h"
  16. #include "llvm/ADT/APInt.h"
  17. #include "llvm/ADT/ArrayRef.h"
  18. #include "llvm/ADT/BitVector.h"
  19. #include "llvm/ADT/DenseMap.h"
  20. #include "llvm/ADT/None.h"
  21. #include "llvm/ADT/Optional.h"
  22. #include "llvm/ADT/STLExtras.h"
  23. #include "llvm/ADT/SmallPtrSet.h"
  24. #include "llvm/ADT/SmallSet.h"
  25. #include "llvm/ADT/SmallVector.h"
  26. #include "llvm/ADT/StringRef.h"
  27. #include "llvm/ADT/Triple.h"
  28. #include "llvm/ADT/Twine.h"
  29. #include "llvm/Analysis/AliasAnalysis.h"
  30. #include "llvm/Analysis/BranchProbabilityInfo.h"
  31. #include "llvm/Analysis/ConstantFolding.h"
  32. #include "llvm/Analysis/EHPersonalities.h"
  33. #include "llvm/Analysis/Loads.h"
  34. #include "llvm/Analysis/MemoryLocation.h"
  35. #include "llvm/Analysis/TargetLibraryInfo.h"
  36. #include "llvm/Analysis/ValueTracking.h"
  37. #include "llvm/Analysis/VectorUtils.h"
  38. #include "llvm/CodeGen/Analysis.h"
  39. #include "llvm/CodeGen/FunctionLoweringInfo.h"
  40. #include "llvm/CodeGen/GCMetadata.h"
  41. #include "llvm/CodeGen/ISDOpcodes.h"
  42. #include "llvm/CodeGen/MachineBasicBlock.h"
  43. #include "llvm/CodeGen/MachineFrameInfo.h"
  44. #include "llvm/CodeGen/MachineFunction.h"
  45. #include "llvm/CodeGen/MachineInstr.h"
  46. #include "llvm/CodeGen/MachineInstrBuilder.h"
  47. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  48. #include "llvm/CodeGen/MachineMemOperand.h"
  49. #include "llvm/CodeGen/MachineModuleInfo.h"
  50. #include "llvm/CodeGen/MachineOperand.h"
  51. #include "llvm/CodeGen/MachineRegisterInfo.h"
  52. #include "llvm/CodeGen/RuntimeLibcalls.h"
  53. #include "llvm/CodeGen/SelectionDAG.h"
  54. #include "llvm/CodeGen/SelectionDAGNodes.h"
  55. #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
  56. #include "llvm/CodeGen/StackMaps.h"
  57. #include "llvm/CodeGen/TargetFrameLowering.h"
  58. #include "llvm/CodeGen/TargetInstrInfo.h"
  59. #include "llvm/CodeGen/TargetLowering.h"
  60. #include "llvm/CodeGen/TargetOpcodes.h"
  61. #include "llvm/CodeGen/TargetRegisterInfo.h"
  62. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  63. #include "llvm/CodeGen/ValueTypes.h"
  64. #include "llvm/CodeGen/WinEHFuncInfo.h"
  65. #include "llvm/IR/Argument.h"
  66. #include "llvm/IR/Attributes.h"
  67. #include "llvm/IR/BasicBlock.h"
  68. #include "llvm/IR/CFG.h"
  69. #include "llvm/IR/CallSite.h"
  70. #include "llvm/IR/CallingConv.h"
  71. #include "llvm/IR/Constant.h"
  72. #include "llvm/IR/ConstantRange.h"
  73. #include "llvm/IR/Constants.h"
  74. #include "llvm/IR/DataLayout.h"
  75. #include "llvm/IR/DebugInfoMetadata.h"
  76. #include "llvm/IR/DebugLoc.h"
  77. #include "llvm/IR/DerivedTypes.h"
  78. #include "llvm/IR/Function.h"
  79. #include "llvm/IR/GetElementPtrTypeIterator.h"
  80. #include "llvm/IR/InlineAsm.h"
  81. #include "llvm/IR/InstrTypes.h"
  82. #include "llvm/IR/Instruction.h"
  83. #include "llvm/IR/Instructions.h"
  84. #include "llvm/IR/IntrinsicInst.h"
  85. #include "llvm/IR/Intrinsics.h"
  86. #include "llvm/IR/LLVMContext.h"
  87. #include "llvm/IR/Metadata.h"
  88. #include "llvm/IR/Module.h"
  89. #include "llvm/IR/Operator.h"
  90. #include "llvm/IR/Statepoint.h"
  91. #include "llvm/IR/Type.h"
  92. #include "llvm/IR/User.h"
  93. #include "llvm/IR/Value.h"
  94. #include "llvm/MC/MCContext.h"
  95. #include "llvm/MC/MCSymbol.h"
  96. #include "llvm/Support/AtomicOrdering.h"
  97. #include "llvm/Support/BranchProbability.h"
  98. #include "llvm/Support/Casting.h"
  99. #include "llvm/Support/CodeGen.h"
  100. #include "llvm/Support/CommandLine.h"
  101. #include "llvm/Support/Compiler.h"
  102. #include "llvm/Support/Debug.h"
  103. #include "llvm/Support/ErrorHandling.h"
  104. #include "llvm/Support/MachineValueType.h"
  105. #include "llvm/Support/MathExtras.h"
  106. #include "llvm/Support/raw_ostream.h"
  107. #include "llvm/Target/TargetIntrinsicInfo.h"
  108. #include "llvm/Target/TargetMachine.h"
  109. #include "llvm/Target/TargetOptions.h"
  110. #include <algorithm>
  111. #include <cassert>
  112. #include <cstddef>
  113. #include <cstdint>
  114. #include <cstring>
  115. #include <iterator>
  116. #include <limits>
  117. #include <numeric>
  118. #include <tuple>
  119. #include <utility>
  120. #include <vector>
  121. using namespace llvm;
  122. #define DEBUG_TYPE "isel"
  123. /// LimitFloatPrecision - Generate low-precision inline sequences for
  124. /// some float libcalls (6, 8 or 12 bits).
  125. static unsigned LimitFloatPrecision;
  126. static cl::opt<unsigned, true>
  127. LimitFPPrecision("limit-float-precision",
  128. cl::desc("Generate low-precision inline sequences "
  129. "for some float libcalls"),
  130. cl::location(LimitFloatPrecision), cl::Hidden,
  131. cl::init(0));
  132. static cl::opt<unsigned> SwitchPeelThreshold(
  133. "switch-peel-threshold", cl::Hidden, cl::init(66),
  134. cl::desc("Set the case probability threshold for peeling the case from a "
  135. "switch statement. A value greater than 100 will void this "
  136. "optimization"));
  137. // Limit the width of DAG chains. This is important in general to prevent
  138. // DAG-based analysis from blowing up. For example, alias analysis and
  139. // load clustering may not complete in reasonable time. It is difficult to
  140. // recognize and avoid this situation within each individual analysis, and
  141. // future analyses are likely to have the same behavior. Limiting DAG width is
  142. // the safe approach and will be especially important with global DAGs.
  143. //
  144. // MaxParallelChains default is arbitrarily high to avoid affecting
  145. // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
  146. // sequence over this should have been converted to llvm.memcpy by the
  147. // frontend. It is easy to induce this behavior with .ll code such as:
  148. // %buffer = alloca [4096 x i8]
  149. // %data = load [4096 x i8]* %argPtr
  150. // store [4096 x i8] %data, [4096 x i8]* %buffer
  151. static const unsigned MaxParallelChains = 64;
  152. // Return the calling convention if the Value passed requires ABI mangling as it
  153. // is a parameter to a function or a return value from a function which is not
  154. // an intrinsic.
  155. static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
  156. if (auto *R = dyn_cast<ReturnInst>(V))
  157. return R->getParent()->getParent()->getCallingConv();
  158. if (auto *CI = dyn_cast<CallInst>(V)) {
  159. const bool IsInlineAsm = CI->isInlineAsm();
  160. const bool IsIndirectFunctionCall =
  161. !IsInlineAsm && !CI->getCalledFunction();
  162. // It is possible that the call instruction is an inline asm statement or an
  163. // indirect function call in which case the return value of
  164. // getCalledFunction() would be nullptr.
  165. const bool IsInstrinsicCall =
  166. !IsInlineAsm && !IsIndirectFunctionCall &&
  167. CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
  168. if (!IsInlineAsm && !IsInstrinsicCall)
  169. return CI->getCallingConv();
  170. }
  171. return None;
  172. }
  173. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  174. const SDValue *Parts, unsigned NumParts,
  175. MVT PartVT, EVT ValueVT, const Value *V,
  176. Optional<CallingConv::ID> CC);
  177. /// getCopyFromParts - Create a value that contains the specified legal parts
  178. /// combined into the value they represent. If the parts combine to a type
  179. /// larger than ValueVT then AssertOp can be used to specify whether the extra
  180. /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
  181. /// (ISD::AssertSext).
  182. static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
  183. const SDValue *Parts, unsigned NumParts,
  184. MVT PartVT, EVT ValueVT, const Value *V,
  185. Optional<CallingConv::ID> CC = None,
  186. Optional<ISD::NodeType> AssertOp = None) {
  187. if (ValueVT.isVector())
  188. return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
  189. CC);
  190. assert(NumParts > 0 && "No parts to assemble!");
  191. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  192. SDValue Val = Parts[0];
  193. if (NumParts > 1) {
  194. // Assemble the value from multiple parts.
  195. if (ValueVT.isInteger()) {
  196. unsigned PartBits = PartVT.getSizeInBits();
  197. unsigned ValueBits = ValueVT.getSizeInBits();
  198. // Assemble the power of 2 part.
  199. unsigned RoundParts = NumParts & (NumParts - 1) ?
  200. 1 << Log2_32(NumParts) : NumParts;
  201. unsigned RoundBits = PartBits * RoundParts;
  202. EVT RoundVT = RoundBits == ValueBits ?
  203. ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
  204. SDValue Lo, Hi;
  205. EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
  206. if (RoundParts > 2) {
  207. Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
  208. PartVT, HalfVT, V);
  209. Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
  210. RoundParts / 2, PartVT, HalfVT, V);
  211. } else {
  212. Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
  213. Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
  214. }
  215. if (DAG.getDataLayout().isBigEndian())
  216. std::swap(Lo, Hi);
  217. Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
  218. if (RoundParts < NumParts) {
  219. // Assemble the trailing non-power-of-2 part.
  220. unsigned OddParts = NumParts - RoundParts;
  221. EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
  222. Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
  223. OddVT, V, CC);
  224. // Combine the round and odd parts.
  225. Lo = Val;
  226. if (DAG.getDataLayout().isBigEndian())
  227. std::swap(Lo, Hi);
  228. EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  229. Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
  230. Hi =
  231. DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
  232. DAG.getConstant(Lo.getValueSizeInBits(), DL,
  233. TLI.getPointerTy(DAG.getDataLayout())));
  234. Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
  235. Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
  236. }
  237. } else if (PartVT.isFloatingPoint()) {
  238. // FP split into multiple FP parts (for ppcf128)
  239. assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
  240. "Unexpected split");
  241. SDValue Lo, Hi;
  242. Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
  243. Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
  244. if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
  245. std::swap(Lo, Hi);
  246. Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
  247. } else {
  248. // FP split into integer parts (soft fp)
  249. assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
  250. !PartVT.isVector() && "Unexpected split");
  251. EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  252. Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
  253. }
  254. }
  255. // There is now one part, held in Val. Correct it to match ValueVT.
  256. // PartEVT is the type of the register class that holds the value.
  257. // ValueVT is the type of the inline asm operation.
  258. EVT PartEVT = Val.getValueType();
  259. if (PartEVT == ValueVT)
  260. return Val;
  261. if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
  262. ValueVT.bitsLT(PartEVT)) {
  263. // For an FP value in an integer part, we need to truncate to the right
  264. // width first.
  265. PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  266. Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
  267. }
  268. // Handle types that have the same size.
  269. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
  270. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  271. // Handle types with different sizes.
  272. if (PartEVT.isInteger() && ValueVT.isInteger()) {
  273. if (ValueVT.bitsLT(PartEVT)) {
  274. // For a truncate, see if we have any information to
  275. // indicate whether the truncated bits will always be
  276. // zero or sign-extension.
  277. if (AssertOp.hasValue())
  278. Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
  279. DAG.getValueType(ValueVT));
  280. return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  281. }
  282. return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
  283. }
  284. if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  285. // FP_ROUND's are always exact here.
  286. if (ValueVT.bitsLT(Val.getValueType()))
  287. return DAG.getNode(
  288. ISD::FP_ROUND, DL, ValueVT, Val,
  289. DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
  290. return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
  291. }
  292. llvm_unreachable("Unknown mismatch!");
  293. }
  294. static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
  295. const Twine &ErrMsg) {
  296. const Instruction *I = dyn_cast_or_null<Instruction>(V);
  297. if (!V)
  298. return Ctx.emitError(ErrMsg);
  299. const char *AsmError = ", possible invalid constraint for vector type";
  300. if (const CallInst *CI = dyn_cast<CallInst>(I))
  301. if (isa<InlineAsm>(CI->getCalledValue()))
  302. return Ctx.emitError(I, ErrMsg + AsmError);
  303. return Ctx.emitError(I, ErrMsg);
  304. }
  305. /// getCopyFromPartsVector - Create a value that contains the specified legal
  306. /// parts combined into the value they represent. If the parts combine to a
  307. /// type larger than ValueVT then AssertOp can be used to specify whether the
  308. /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
  309. /// ValueVT (ISD::AssertSext).
  310. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  311. const SDValue *Parts, unsigned NumParts,
  312. MVT PartVT, EVT ValueVT, const Value *V,
  313. Optional<CallingConv::ID> CallConv) {
  314. assert(ValueVT.isVector() && "Not a vector value");
  315. assert(NumParts > 0 && "No parts to assemble!");
  316. const bool IsABIRegCopy = CallConv.hasValue();
  317. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  318. SDValue Val = Parts[0];
  319. // Handle a multi-element vector.
  320. if (NumParts > 1) {
  321. EVT IntermediateVT;
  322. MVT RegisterVT;
  323. unsigned NumIntermediates;
  324. unsigned NumRegs;
  325. if (IsABIRegCopy) {
  326. NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
  327. *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
  328. NumIntermediates, RegisterVT);
  329. } else {
  330. NumRegs =
  331. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  332. NumIntermediates, RegisterVT);
  333. }
  334. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  335. NumParts = NumRegs; // Silence a compiler warning.
  336. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  337. assert(RegisterVT.getSizeInBits() ==
  338. Parts[0].getSimpleValueType().getSizeInBits() &&
  339. "Part type sizes don't match!");
  340. // Assemble the parts into intermediate operands.
  341. SmallVector<SDValue, 8> Ops(NumIntermediates);
  342. if (NumIntermediates == NumParts) {
  343. // If the register was not expanded, truncate or copy the value,
  344. // as appropriate.
  345. for (unsigned i = 0; i != NumParts; ++i)
  346. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
  347. PartVT, IntermediateVT, V);
  348. } else if (NumParts > 0) {
  349. // If the intermediate type was expanded, build the intermediate
  350. // operands from the parts.
  351. assert(NumParts % NumIntermediates == 0 &&
  352. "Must expand into a divisible number of parts!");
  353. unsigned Factor = NumParts / NumIntermediates;
  354. for (unsigned i = 0; i != NumIntermediates; ++i)
  355. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
  356. PartVT, IntermediateVT, V);
  357. }
  358. // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
  359. // intermediate operands.
  360. EVT BuiltVectorTy =
  361. EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
  362. (IntermediateVT.isVector()
  363. ? IntermediateVT.getVectorNumElements() * NumParts
  364. : NumIntermediates));
  365. Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
  366. : ISD::BUILD_VECTOR,
  367. DL, BuiltVectorTy, Ops);
  368. }
  369. // There is now one part, held in Val. Correct it to match ValueVT.
  370. EVT PartEVT = Val.getValueType();
  371. if (PartEVT == ValueVT)
  372. return Val;
  373. if (PartEVT.isVector()) {
  374. // If the element type of the source/dest vectors are the same, but the
  375. // parts vector has more elements than the value vector, then we have a
  376. // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
  377. // elements we want.
  378. if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
  379. assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
  380. "Cannot narrow, it would be a lossy transformation");
  381. return DAG.getNode(
  382. ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
  383. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  384. }
  385. // Vector/Vector bitcast.
  386. if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
  387. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  388. assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
  389. "Cannot handle this kind of promotion");
  390. // Promoted vector extract
  391. return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
  392. }
  393. // Trivial bitcast if the types are the same size and the destination
  394. // vector type is legal.
  395. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
  396. TLI.isTypeLegal(ValueVT))
  397. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  398. if (ValueVT.getVectorNumElements() != 1) {
  399. // Certain ABIs require that vectors are passed as integers. For vectors
  400. // are the same size, this is an obvious bitcast.
  401. if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
  402. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  403. } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
  404. // Bitcast Val back the original type and extract the corresponding
  405. // vector we want.
  406. unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
  407. EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
  408. ValueVT.getVectorElementType(), Elts);
  409. Val = DAG.getBitcast(WiderVecType, Val);
  410. return DAG.getNode(
  411. ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
  412. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  413. }
  414. diagnosePossiblyInvalidConstraint(
  415. *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
  416. return DAG.getUNDEF(ValueVT);
  417. }
  418. // Handle cases such as i8 -> <1 x i1>
  419. EVT ValueSVT = ValueVT.getVectorElementType();
  420. if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
  421. Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
  422. : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
  423. return DAG.getBuildVector(ValueVT, DL, Val);
  424. }
  425. static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
  426. SDValue Val, SDValue *Parts, unsigned NumParts,
  427. MVT PartVT, const Value *V,
  428. Optional<CallingConv::ID> CallConv);
  429. /// getCopyToParts - Create a series of nodes that contain the specified value
  430. /// split into legal parts. If the parts contain more bits than Val, then, for
  431. /// integers, ExtendKind can be used to specify how to generate the extra bits.
  432. static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
  433. SDValue *Parts, unsigned NumParts, MVT PartVT,
  434. const Value *V,
  435. Optional<CallingConv::ID> CallConv = None,
  436. ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
  437. EVT ValueVT = Val.getValueType();
  438. // Handle the vector case separately.
  439. if (ValueVT.isVector())
  440. return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
  441. CallConv);
  442. unsigned PartBits = PartVT.getSizeInBits();
  443. unsigned OrigNumParts = NumParts;
  444. assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
  445. "Copying to an illegal type!");
  446. if (NumParts == 0)
  447. return;
  448. assert(!ValueVT.isVector() && "Vector case handled elsewhere");
  449. EVT PartEVT = PartVT;
  450. if (PartEVT == ValueVT) {
  451. assert(NumParts == 1 && "No-op copy with multiple parts!");
  452. Parts[0] = Val;
  453. return;
  454. }
  455. if (NumParts * PartBits > ValueVT.getSizeInBits()) {
  456. // If the parts cover more bits than the value has, promote the value.
  457. if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  458. assert(NumParts == 1 && "Do not know what to promote to!");
  459. Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
  460. } else {
  461. if (ValueVT.isFloatingPoint()) {
  462. // FP values need to be bitcast, then extended if they are being put
  463. // into a larger container.
  464. ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  465. Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  466. }
  467. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  468. ValueVT.isInteger() &&
  469. "Unknown mismatch!");
  470. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  471. Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
  472. if (PartVT == MVT::x86mmx)
  473. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  474. }
  475. } else if (PartBits == ValueVT.getSizeInBits()) {
  476. // Different types of the same size.
  477. assert(NumParts == 1 && PartEVT != ValueVT);
  478. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  479. } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
  480. // If the parts cover less bits than value has, truncate the value.
  481. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  482. ValueVT.isInteger() &&
  483. "Unknown mismatch!");
  484. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  485. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  486. if (PartVT == MVT::x86mmx)
  487. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  488. }
  489. // The value may have changed - recompute ValueVT.
  490. ValueVT = Val.getValueType();
  491. assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
  492. "Failed to tile the value with PartVT!");
  493. if (NumParts == 1) {
  494. if (PartEVT != ValueVT) {
  495. diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
  496. "scalar-to-vector conversion failed");
  497. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  498. }
  499. Parts[0] = Val;
  500. return;
  501. }
  502. // Expand the value into multiple parts.
  503. if (NumParts & (NumParts - 1)) {
  504. // The number of parts is not a power of 2. Split off and copy the tail.
  505. assert(PartVT.isInteger() && ValueVT.isInteger() &&
  506. "Do not know what to expand to!");
  507. unsigned RoundParts = 1 << Log2_32(NumParts);
  508. unsigned RoundBits = RoundParts * PartBits;
  509. unsigned OddParts = NumParts - RoundParts;
  510. SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
  511. DAG.getIntPtrConstant(RoundBits, DL));
  512. getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
  513. CallConv);
  514. if (DAG.getDataLayout().isBigEndian())
  515. // The odd parts were reversed by getCopyToParts - unreverse them.
  516. std::reverse(Parts + RoundParts, Parts + NumParts);
  517. NumParts = RoundParts;
  518. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  519. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  520. }
  521. // The number of parts is a power of 2. Repeatedly bisect the value using
  522. // EXTRACT_ELEMENT.
  523. Parts[0] = DAG.getNode(ISD::BITCAST, DL,
  524. EVT::getIntegerVT(*DAG.getContext(),
  525. ValueVT.getSizeInBits()),
  526. Val);
  527. for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
  528. for (unsigned i = 0; i < NumParts; i += StepSize) {
  529. unsigned ThisBits = StepSize * PartBits / 2;
  530. EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
  531. SDValue &Part0 = Parts[i];
  532. SDValue &Part1 = Parts[i+StepSize/2];
  533. Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  534. ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
  535. Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  536. ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
  537. if (ThisBits == PartBits && ThisVT != PartVT) {
  538. Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
  539. Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
  540. }
  541. }
  542. }
  543. if (DAG.getDataLayout().isBigEndian())
  544. std::reverse(Parts, Parts + OrigNumParts);
  545. }
  546. static SDValue widenVectorToPartType(SelectionDAG &DAG,
  547. SDValue Val, const SDLoc &DL, EVT PartVT) {
  548. if (!PartVT.isVector())
  549. return SDValue();
  550. EVT ValueVT = Val.getValueType();
  551. unsigned PartNumElts = PartVT.getVectorNumElements();
  552. unsigned ValueNumElts = ValueVT.getVectorNumElements();
  553. if (PartNumElts > ValueNumElts &&
  554. PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
  555. EVT ElementVT = PartVT.getVectorElementType();
  556. // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
  557. // undef elements.
  558. SmallVector<SDValue, 16> Ops;
  559. DAG.ExtractVectorElements(Val, Ops);
  560. SDValue EltUndef = DAG.getUNDEF(ElementVT);
  561. for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
  562. Ops.push_back(EltUndef);
  563. // FIXME: Use CONCAT for 2x -> 4x.
  564. return DAG.getBuildVector(PartVT, DL, Ops);
  565. }
  566. return SDValue();
  567. }
  568. /// getCopyToPartsVector - Create a series of nodes that contain the specified
  569. /// value split into legal parts.
  570. static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  571. SDValue Val, SDValue *Parts, unsigned NumParts,
  572. MVT PartVT, const Value *V,
  573. Optional<CallingConv::ID> CallConv) {
  574. EVT ValueVT = Val.getValueType();
  575. assert(ValueVT.isVector() && "Not a vector");
  576. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  577. const bool IsABIRegCopy = CallConv.hasValue();
  578. if (NumParts == 1) {
  579. EVT PartEVT = PartVT;
  580. if (PartEVT == ValueVT) {
  581. // Nothing to do.
  582. } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
  583. // Bitconvert vector->vector case.
  584. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  585. } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
  586. Val = Widened;
  587. } else if (PartVT.isVector() &&
  588. PartEVT.getVectorElementType().bitsGE(
  589. ValueVT.getVectorElementType()) &&
  590. PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
  591. // Promoted vector extract
  592. Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
  593. } else {
  594. if (ValueVT.getVectorNumElements() == 1) {
  595. Val = DAG.getNode(
  596. ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
  597. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  598. } else {
  599. assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
  600. "lossy conversion of vector to scalar type");
  601. EVT IntermediateType =
  602. EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  603. Val = DAG.getBitcast(IntermediateType, Val);
  604. Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
  605. }
  606. }
  607. assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
  608. Parts[0] = Val;
  609. return;
  610. }
  611. // Handle a multi-element vector.
  612. EVT IntermediateVT;
  613. MVT RegisterVT;
  614. unsigned NumIntermediates;
  615. unsigned NumRegs;
  616. if (IsABIRegCopy) {
  617. NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
  618. *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
  619. NumIntermediates, RegisterVT);
  620. } else {
  621. NumRegs =
  622. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  623. NumIntermediates, RegisterVT);
  624. }
  625. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  626. NumParts = NumRegs; // Silence a compiler warning.
  627. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  628. unsigned IntermediateNumElts = IntermediateVT.isVector() ?
  629. IntermediateVT.getVectorNumElements() : 1;
  630. // Convert the vector to the appropiate type if necessary.
  631. unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
  632. EVT BuiltVectorTy = EVT::getVectorVT(
  633. *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
  634. MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
  635. if (ValueVT != BuiltVectorTy) {
  636. if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
  637. Val = Widened;
  638. Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
  639. }
  640. // Split the vector into intermediate operands.
  641. SmallVector<SDValue, 8> Ops(NumIntermediates);
  642. for (unsigned i = 0; i != NumIntermediates; ++i) {
  643. if (IntermediateVT.isVector()) {
  644. Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
  645. DAG.getConstant(i * IntermediateNumElts, DL, IdxVT));
  646. } else {
  647. Ops[i] = DAG.getNode(
  648. ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
  649. DAG.getConstant(i, DL, IdxVT));
  650. }
  651. }
  652. // Split the intermediate operands into legal parts.
  653. if (NumParts == NumIntermediates) {
  654. // If the register was not expanded, promote or copy the value,
  655. // as appropriate.
  656. for (unsigned i = 0; i != NumParts; ++i)
  657. getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
  658. } else if (NumParts > 0) {
  659. // If the intermediate type was expanded, split each the value into
  660. // legal parts.
  661. assert(NumIntermediates != 0 && "division by zero");
  662. assert(NumParts % NumIntermediates == 0 &&
  663. "Must expand into a divisible number of parts!");
  664. unsigned Factor = NumParts / NumIntermediates;
  665. for (unsigned i = 0; i != NumIntermediates; ++i)
  666. getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
  667. CallConv);
  668. }
  669. }
  670. RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
  671. EVT valuevt, Optional<CallingConv::ID> CC)
  672. : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
  673. RegCount(1, regs.size()), CallConv(CC) {}
  674. RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
  675. const DataLayout &DL, unsigned Reg, Type *Ty,
  676. Optional<CallingConv::ID> CC) {
  677. ComputeValueVTs(TLI, DL, Ty, ValueVTs);
  678. CallConv = CC;
  679. for (EVT ValueVT : ValueVTs) {
  680. unsigned NumRegs =
  681. isABIMangled()
  682. ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
  683. : TLI.getNumRegisters(Context, ValueVT);
  684. MVT RegisterVT =
  685. isABIMangled()
  686. ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
  687. : TLI.getRegisterType(Context, ValueVT);
  688. for (unsigned i = 0; i != NumRegs; ++i)
  689. Regs.push_back(Reg + i);
  690. RegVTs.push_back(RegisterVT);
  691. RegCount.push_back(NumRegs);
  692. Reg += NumRegs;
  693. }
  694. }
  695. SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
  696. FunctionLoweringInfo &FuncInfo,
  697. const SDLoc &dl, SDValue &Chain,
  698. SDValue *Flag, const Value *V) const {
  699. // A Value with type {} or [0 x %t] needs no registers.
  700. if (ValueVTs.empty())
  701. return SDValue();
  702. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  703. // Assemble the legal parts into the final values.
  704. SmallVector<SDValue, 4> Values(ValueVTs.size());
  705. SmallVector<SDValue, 8> Parts;
  706. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  707. // Copy the legal parts from the registers.
  708. EVT ValueVT = ValueVTs[Value];
  709. unsigned NumRegs = RegCount[Value];
  710. MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
  711. *DAG.getContext(),
  712. CallConv.getValue(), RegVTs[Value])
  713. : RegVTs[Value];
  714. Parts.resize(NumRegs);
  715. for (unsigned i = 0; i != NumRegs; ++i) {
  716. SDValue P;
  717. if (!Flag) {
  718. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
  719. } else {
  720. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
  721. *Flag = P.getValue(2);
  722. }
  723. Chain = P.getValue(1);
  724. Parts[i] = P;
  725. // If the source register was virtual and if we know something about it,
  726. // add an assert node.
  727. if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
  728. !RegisterVT.isInteger() || RegisterVT.isVector())
  729. continue;
  730. const FunctionLoweringInfo::LiveOutInfo *LOI =
  731. FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
  732. if (!LOI)
  733. continue;
  734. unsigned RegSize = RegisterVT.getSizeInBits();
  735. unsigned NumSignBits = LOI->NumSignBits;
  736. unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
  737. if (NumZeroBits == RegSize) {
  738. // The current value is a zero.
  739. // Explicitly express that as it would be easier for
  740. // optimizations to kick in.
  741. Parts[i] = DAG.getConstant(0, dl, RegisterVT);
  742. continue;
  743. }
  744. // FIXME: We capture more information than the dag can represent. For
  745. // now, just use the tightest assertzext/assertsext possible.
  746. bool isSExt;
  747. EVT FromVT(MVT::Other);
  748. if (NumZeroBits) {
  749. FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
  750. isSExt = false;
  751. } else if (NumSignBits > 1) {
  752. FromVT =
  753. EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
  754. isSExt = true;
  755. } else {
  756. continue;
  757. }
  758. // Add an assertion node.
  759. assert(FromVT != MVT::Other);
  760. Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
  761. RegisterVT, P, DAG.getValueType(FromVT));
  762. }
  763. Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
  764. RegisterVT, ValueVT, V, CallConv);
  765. Part += NumRegs;
  766. Parts.clear();
  767. }
  768. return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
  769. }
  770. void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
  771. const SDLoc &dl, SDValue &Chain, SDValue *Flag,
  772. const Value *V,
  773. ISD::NodeType PreferredExtendType) const {
  774. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  775. ISD::NodeType ExtendKind = PreferredExtendType;
  776. // Get the list of the values's legal parts.
  777. unsigned NumRegs = Regs.size();
  778. SmallVector<SDValue, 8> Parts(NumRegs);
  779. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  780. unsigned NumParts = RegCount[Value];
  781. MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
  782. *DAG.getContext(),
  783. CallConv.getValue(), RegVTs[Value])
  784. : RegVTs[Value];
  785. if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
  786. ExtendKind = ISD::ZERO_EXTEND;
  787. getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
  788. NumParts, RegisterVT, V, CallConv, ExtendKind);
  789. Part += NumParts;
  790. }
  791. // Copy the parts into the registers.
  792. SmallVector<SDValue, 8> Chains(NumRegs);
  793. for (unsigned i = 0; i != NumRegs; ++i) {
  794. SDValue Part;
  795. if (!Flag) {
  796. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
  797. } else {
  798. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
  799. *Flag = Part.getValue(1);
  800. }
  801. Chains[i] = Part.getValue(0);
  802. }
  803. if (NumRegs == 1 || Flag)
  804. // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
  805. // flagged to it. That is the CopyToReg nodes and the user are considered
  806. // a single scheduling unit. If we create a TokenFactor and return it as
  807. // chain, then the TokenFactor is both a predecessor (operand) of the
  808. // user as well as a successor (the TF operands are flagged to the user).
  809. // c1, f1 = CopyToReg
  810. // c2, f2 = CopyToReg
  811. // c3 = TokenFactor c1, c2
  812. // ...
  813. // = op c3, ..., f2
  814. Chain = Chains[NumRegs-1];
  815. else
  816. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  817. }
  818. void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
  819. unsigned MatchingIdx, const SDLoc &dl,
  820. SelectionDAG &DAG,
  821. std::vector<SDValue> &Ops) const {
  822. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  823. unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
  824. if (HasMatching)
  825. Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
  826. else if (!Regs.empty() &&
  827. TargetRegisterInfo::isVirtualRegister(Regs.front())) {
  828. // Put the register class of the virtual registers in the flag word. That
  829. // way, later passes can recompute register class constraints for inline
  830. // assembly as well as normal instructions.
  831. // Don't do this for tied operands that can use the regclass information
  832. // from the def.
  833. const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
  834. const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
  835. Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
  836. }
  837. SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
  838. Ops.push_back(Res);
  839. if (Code == InlineAsm::Kind_Clobber) {
  840. // Clobbers should always have a 1:1 mapping with registers, and may
  841. // reference registers that have illegal (e.g. vector) types. Hence, we
  842. // shouldn't try to apply any sort of splitting logic to them.
  843. assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
  844. "No 1:1 mapping from clobbers to regs?");
  845. unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
  846. (void)SP;
  847. for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
  848. Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
  849. assert(
  850. (Regs[I] != SP ||
  851. DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
  852. "If we clobbered the stack pointer, MFI should know about it.");
  853. }
  854. return;
  855. }
  856. for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
  857. unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
  858. MVT RegisterVT = RegVTs[Value];
  859. for (unsigned i = 0; i != NumRegs; ++i) {
  860. assert(Reg < Regs.size() && "Mismatch in # registers expected");
  861. unsigned TheReg = Regs[Reg++];
  862. Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
  863. }
  864. }
  865. }
  866. SmallVector<std::pair<unsigned, unsigned>, 4>
  867. RegsForValue::getRegsAndSizes() const {
  868. SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
  869. unsigned I = 0;
  870. for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
  871. unsigned RegCount = std::get<0>(CountAndVT);
  872. MVT RegisterVT = std::get<1>(CountAndVT);
  873. unsigned RegisterSize = RegisterVT.getSizeInBits();
  874. for (unsigned E = I + RegCount; I != E; ++I)
  875. OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
  876. }
  877. return OutVec;
  878. }
  879. void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
  880. const TargetLibraryInfo *li) {
  881. AA = aa;
  882. GFI = gfi;
  883. LibInfo = li;
  884. DL = &DAG.getDataLayout();
  885. Context = DAG.getContext();
  886. LPadToCallSiteMap.clear();
  887. }
  888. void SelectionDAGBuilder::clear() {
  889. NodeMap.clear();
  890. UnusedArgNodeMap.clear();
  891. PendingLoads.clear();
  892. PendingExports.clear();
  893. CurInst = nullptr;
  894. HasTailCall = false;
  895. SDNodeOrder = LowestSDNodeOrder;
  896. StatepointLowering.clear();
  897. }
  898. void SelectionDAGBuilder::clearDanglingDebugInfo() {
  899. DanglingDebugInfoMap.clear();
  900. }
  901. SDValue SelectionDAGBuilder::getRoot() {
  902. if (PendingLoads.empty())
  903. return DAG.getRoot();
  904. if (PendingLoads.size() == 1) {
  905. SDValue Root = PendingLoads[0];
  906. DAG.setRoot(Root);
  907. PendingLoads.clear();
  908. return Root;
  909. }
  910. // Otherwise, we have to make a token factor node.
  911. SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  912. PendingLoads);
  913. PendingLoads.clear();
  914. DAG.setRoot(Root);
  915. return Root;
  916. }
  917. SDValue SelectionDAGBuilder::getControlRoot() {
  918. SDValue Root = DAG.getRoot();
  919. if (PendingExports.empty())
  920. return Root;
  921. // Turn all of the CopyToReg chains into one factored node.
  922. if (Root.getOpcode() != ISD::EntryToken) {
  923. unsigned i = 0, e = PendingExports.size();
  924. for (; i != e; ++i) {
  925. assert(PendingExports[i].getNode()->getNumOperands() > 1);
  926. if (PendingExports[i].getNode()->getOperand(0) == Root)
  927. break; // Don't add the root if we already indirectly depend on it.
  928. }
  929. if (i == e)
  930. PendingExports.push_back(Root);
  931. }
  932. Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  933. PendingExports);
  934. PendingExports.clear();
  935. DAG.setRoot(Root);
  936. return Root;
  937. }
  938. void SelectionDAGBuilder::visit(const Instruction &I) {
  939. // Set up outgoing PHI node register values before emitting the terminator.
  940. if (I.isTerminator()) {
  941. HandlePHINodesInSuccessorBlocks(I.getParent());
  942. }
  943. // Increase the SDNodeOrder if dealing with a non-debug instruction.
  944. if (!isa<DbgInfoIntrinsic>(I))
  945. ++SDNodeOrder;
  946. CurInst = &I;
  947. visit(I.getOpcode(), I);
  948. if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
  949. // Propagate the fast-math-flags of this IR instruction to the DAG node that
  950. // maps to this instruction.
  951. // TODO: We could handle all flags (nsw, etc) here.
  952. // TODO: If an IR instruction maps to >1 node, only the final node will have
  953. // flags set.
  954. if (SDNode *Node = getNodeForIRValue(&I)) {
  955. SDNodeFlags IncomingFlags;
  956. IncomingFlags.copyFMF(*FPMO);
  957. if (!Node->getFlags().isDefined())
  958. Node->setFlags(IncomingFlags);
  959. else
  960. Node->intersectFlagsWith(IncomingFlags);
  961. }
  962. }
  963. if (!I.isTerminator() && !HasTailCall &&
  964. !isStatepoint(&I)) // statepoints handle their exports internally
  965. CopyToExportRegsIfNeeded(&I);
  966. CurInst = nullptr;
  967. }
  968. void SelectionDAGBuilder::visitPHI(const PHINode &) {
  969. llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
  970. }
  971. void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
  972. // Note: this doesn't use InstVisitor, because it has to work with
  973. // ConstantExpr's in addition to instructions.
  974. switch (Opcode) {
  975. default: llvm_unreachable("Unknown instruction type encountered!");
  976. // Build the switch statement using the Instruction.def file.
  977. #define HANDLE_INST(NUM, OPCODE, CLASS) \
  978. case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
  979. #include "llvm/IR/Instruction.def"
  980. }
  981. }
  982. void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
  983. const DIExpression *Expr) {
  984. auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
  985. const DbgValueInst *DI = DDI.getDI();
  986. DIVariable *DanglingVariable = DI->getVariable();
  987. DIExpression *DanglingExpr = DI->getExpression();
  988. if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
  989. LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
  990. return true;
  991. }
  992. return false;
  993. };
  994. for (auto &DDIMI : DanglingDebugInfoMap) {
  995. DanglingDebugInfoVector &DDIV = DDIMI.second;
  996. DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
  997. }
  998. }
  999. // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
  1000. // generate the debug data structures now that we've seen its definition.
  1001. void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
  1002. SDValue Val) {
  1003. auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
  1004. if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
  1005. return;
  1006. DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
  1007. for (auto &DDI : DDIV) {
  1008. const DbgValueInst *DI = DDI.getDI();
  1009. assert(DI && "Ill-formed DanglingDebugInfo");
  1010. DebugLoc dl = DDI.getdl();
  1011. unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
  1012. unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
  1013. DILocalVariable *Variable = DI->getVariable();
  1014. DIExpression *Expr = DI->getExpression();
  1015. assert(Variable->isValidLocationForIntrinsic(dl) &&
  1016. "Expected inlined-at fields to agree");
  1017. SDDbgValue *SDV;
  1018. if (Val.getNode()) {
  1019. if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
  1020. LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
  1021. << DbgSDNodeOrder << "] for:\n " << *DI << "\n");
  1022. LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump());
  1023. // Increase the SDNodeOrder for the DbgValue here to make sure it is
  1024. // inserted after the definition of Val when emitting the instructions
  1025. // after ISel. An alternative could be to teach
  1026. // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
  1027. LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
  1028. << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
  1029. << ValSDNodeOrder << "\n");
  1030. SDV = getDbgValue(Val, Variable, Expr, dl,
  1031. std::max(DbgSDNodeOrder, ValSDNodeOrder));
  1032. DAG.AddDbgValue(SDV, Val.getNode(), false);
  1033. } else
  1034. LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
  1035. << "in EmitFuncArgumentDbgValue\n");
  1036. } else
  1037. LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
  1038. }
  1039. DDIV.clear();
  1040. }
  1041. /// getCopyFromRegs - If there was virtual register allocated for the value V
  1042. /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
  1043. SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
  1044. DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
  1045. SDValue Result;
  1046. if (It != FuncInfo.ValueMap.end()) {
  1047. unsigned InReg = It->second;
  1048. RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
  1049. DAG.getDataLayout(), InReg, Ty,
  1050. None); // This is not an ABI copy.
  1051. SDValue Chain = DAG.getEntryNode();
  1052. Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
  1053. V);
  1054. resolveDanglingDebugInfo(V, Result);
  1055. }
  1056. return Result;
  1057. }
  1058. /// getValue - Return an SDValue for the given Value.
  1059. SDValue SelectionDAGBuilder::getValue(const Value *V) {
  1060. // If we already have an SDValue for this value, use it. It's important
  1061. // to do this first, so that we don't create a CopyFromReg if we already
  1062. // have a regular SDValue.
  1063. SDValue &N = NodeMap[V];
  1064. if (N.getNode()) return N;
  1065. // If there's a virtual register allocated and initialized for this
  1066. // value, use it.
  1067. if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
  1068. return copyFromReg;
  1069. // Otherwise create a new SDValue and remember it.
  1070. SDValue Val = getValueImpl(V);
  1071. NodeMap[V] = Val;
  1072. resolveDanglingDebugInfo(V, Val);
  1073. return Val;
  1074. }
  1075. // Return true if SDValue exists for the given Value
  1076. bool SelectionDAGBuilder::findValue(const Value *V) const {
  1077. return (NodeMap.find(V) != NodeMap.end()) ||
  1078. (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
  1079. }
  1080. /// getNonRegisterValue - Return an SDValue for the given Value, but
  1081. /// don't look in FuncInfo.ValueMap for a virtual register.
  1082. SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
  1083. // If we already have an SDValue for this value, use it.
  1084. SDValue &N = NodeMap[V];
  1085. if (N.getNode()) {
  1086. if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
  1087. // Remove the debug location from the node as the node is about to be used
  1088. // in a location which may differ from the original debug location. This
  1089. // is relevant to Constant and ConstantFP nodes because they can appear
  1090. // as constant expressions inside PHI nodes.
  1091. N->setDebugLoc(DebugLoc());
  1092. }
  1093. return N;
  1094. }
  1095. // Otherwise create a new SDValue and remember it.
  1096. SDValue Val = getValueImpl(V);
  1097. NodeMap[V] = Val;
  1098. resolveDanglingDebugInfo(V, Val);
  1099. return Val;
  1100. }
  1101. /// getValueImpl - Helper function for getValue and getNonRegisterValue.
  1102. /// Create an SDValue for the given value.
  1103. SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
  1104. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1105. if (const Constant *C = dyn_cast<Constant>(V)) {
  1106. EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
  1107. if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
  1108. return DAG.getConstant(*CI, getCurSDLoc(), VT);
  1109. if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
  1110. return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
  1111. if (isa<ConstantPointerNull>(C)) {
  1112. unsigned AS = V->getType()->getPointerAddressSpace();
  1113. return DAG.getConstant(0, getCurSDLoc(),
  1114. TLI.getPointerTy(DAG.getDataLayout(), AS));
  1115. }
  1116. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
  1117. return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
  1118. if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
  1119. return DAG.getUNDEF(VT);
  1120. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  1121. visit(CE->getOpcode(), *CE);
  1122. SDValue N1 = NodeMap[V];
  1123. assert(N1.getNode() && "visit didn't populate the NodeMap!");
  1124. return N1;
  1125. }
  1126. if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
  1127. SmallVector<SDValue, 4> Constants;
  1128. for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
  1129. OI != OE; ++OI) {
  1130. SDNode *Val = getValue(*OI).getNode();
  1131. // If the operand is an empty aggregate, there are no values.
  1132. if (!Val) continue;
  1133. // Add each leaf value from the operand to the Constants list
  1134. // to form a flattened list of all the values.
  1135. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  1136. Constants.push_back(SDValue(Val, i));
  1137. }
  1138. return DAG.getMergeValues(Constants, getCurSDLoc());
  1139. }
  1140. if (const ConstantDataSequential *CDS =
  1141. dyn_cast<ConstantDataSequential>(C)) {
  1142. SmallVector<SDValue, 4> Ops;
  1143. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  1144. SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
  1145. // Add each leaf value from the operand to the Constants list
  1146. // to form a flattened list of all the values.
  1147. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  1148. Ops.push_back(SDValue(Val, i));
  1149. }
  1150. if (isa<ArrayType>(CDS->getType()))
  1151. return DAG.getMergeValues(Ops, getCurSDLoc());
  1152. return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
  1153. }
  1154. if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
  1155. assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
  1156. "Unknown struct or array constant!");
  1157. SmallVector<EVT, 4> ValueVTs;
  1158. ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
  1159. unsigned NumElts = ValueVTs.size();
  1160. if (NumElts == 0)
  1161. return SDValue(); // empty struct
  1162. SmallVector<SDValue, 4> Constants(NumElts);
  1163. for (unsigned i = 0; i != NumElts; ++i) {
  1164. EVT EltVT = ValueVTs[i];
  1165. if (isa<UndefValue>(C))
  1166. Constants[i] = DAG.getUNDEF(EltVT);
  1167. else if (EltVT.isFloatingPoint())
  1168. Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  1169. else
  1170. Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
  1171. }
  1172. return DAG.getMergeValues(Constants, getCurSDLoc());
  1173. }
  1174. if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
  1175. return DAG.getBlockAddress(BA, VT);
  1176. VectorType *VecTy = cast<VectorType>(V->getType());
  1177. unsigned NumElements = VecTy->getNumElements();
  1178. // Now that we know the number and type of the elements, get that number of
  1179. // elements into the Ops array based on what kind of constant it is.
  1180. SmallVector<SDValue, 16> Ops;
  1181. if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
  1182. for (unsigned i = 0; i != NumElements; ++i)
  1183. Ops.push_back(getValue(CV->getOperand(i)));
  1184. } else {
  1185. assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
  1186. EVT EltVT =
  1187. TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
  1188. SDValue Op;
  1189. if (EltVT.isFloatingPoint())
  1190. Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  1191. else
  1192. Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
  1193. Ops.assign(NumElements, Op);
  1194. }
  1195. // Create a BUILD_VECTOR node.
  1196. return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
  1197. }
  1198. // If this is a static alloca, generate it as the frameindex instead of
  1199. // computation.
  1200. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  1201. DenseMap<const AllocaInst*, int>::iterator SI =
  1202. FuncInfo.StaticAllocaMap.find(AI);
  1203. if (SI != FuncInfo.StaticAllocaMap.end())
  1204. return DAG.getFrameIndex(SI->second,
  1205. TLI.getFrameIndexTy(DAG.getDataLayout()));
  1206. }
  1207. // If this is an instruction which fast-isel has deferred, select it now.
  1208. if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
  1209. unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
  1210. RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
  1211. Inst->getType(), getABIRegCopyCC(V));
  1212. SDValue Chain = DAG.getEntryNode();
  1213. return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
  1214. }
  1215. llvm_unreachable("Can't get register for value!");
  1216. }
  1217. void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
  1218. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1219. bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
  1220. bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
  1221. bool IsSEH = isAsynchronousEHPersonality(Pers);
  1222. bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
  1223. MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
  1224. if (!IsSEH)
  1225. CatchPadMBB->setIsEHScopeEntry();
  1226. // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
  1227. if (IsMSVCCXX || IsCoreCLR)
  1228. CatchPadMBB->setIsEHFuncletEntry();
  1229. // Wasm does not need catchpads anymore
  1230. if (!IsWasmCXX)
  1231. DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
  1232. getControlRoot()));
  1233. }
  1234. void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
  1235. // Update machine-CFG edge.
  1236. MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
  1237. FuncInfo.MBB->addSuccessor(TargetMBB);
  1238. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1239. bool IsSEH = isAsynchronousEHPersonality(Pers);
  1240. if (IsSEH) {
  1241. // If this is not a fall-through branch or optimizations are switched off,
  1242. // emit the branch.
  1243. if (TargetMBB != NextBlock(FuncInfo.MBB) ||
  1244. TM.getOptLevel() == CodeGenOpt::None)
  1245. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  1246. getControlRoot(), DAG.getBasicBlock(TargetMBB)));
  1247. return;
  1248. }
  1249. // Figure out the funclet membership for the catchret's successor.
  1250. // This will be used by the FuncletLayout pass to determine how to order the
  1251. // BB's.
  1252. // A 'catchret' returns to the outer scope's color.
  1253. Value *ParentPad = I.getCatchSwitchParentPad();
  1254. const BasicBlock *SuccessorColor;
  1255. if (isa<ConstantTokenNone>(ParentPad))
  1256. SuccessorColor = &FuncInfo.Fn->getEntryBlock();
  1257. else
  1258. SuccessorColor = cast<Instruction>(ParentPad)->getParent();
  1259. assert(SuccessorColor && "No parent funclet for catchret!");
  1260. MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
  1261. assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
  1262. // Create the terminator node.
  1263. SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
  1264. getControlRoot(), DAG.getBasicBlock(TargetMBB),
  1265. DAG.getBasicBlock(SuccessorColorMBB));
  1266. DAG.setRoot(Ret);
  1267. }
  1268. void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
  1269. // Don't emit any special code for the cleanuppad instruction. It just marks
  1270. // the start of an EH scope/funclet.
  1271. FuncInfo.MBB->setIsEHScopeEntry();
  1272. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1273. if (Pers != EHPersonality::Wasm_CXX) {
  1274. FuncInfo.MBB->setIsEHFuncletEntry();
  1275. FuncInfo.MBB->setIsCleanupFuncletEntry();
  1276. }
  1277. }
  1278. /// When an invoke or a cleanupret unwinds to the next EH pad, there are
  1279. /// many places it could ultimately go. In the IR, we have a single unwind
  1280. /// destination, but in the machine CFG, we enumerate all the possible blocks.
  1281. /// This function skips over imaginary basic blocks that hold catchswitch
  1282. /// instructions, and finds all the "real" machine
  1283. /// basic block destinations. As those destinations may not be successors of
  1284. /// EHPadBB, here we also calculate the edge probability to those destinations.
  1285. /// The passed-in Prob is the edge probability to EHPadBB.
  1286. static void findUnwindDestinations(
  1287. FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
  1288. BranchProbability Prob,
  1289. SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
  1290. &UnwindDests) {
  1291. EHPersonality Personality =
  1292. classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1293. bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
  1294. bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
  1295. bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
  1296. bool IsSEH = isAsynchronousEHPersonality(Personality);
  1297. while (EHPadBB) {
  1298. const Instruction *Pad = EHPadBB->getFirstNonPHI();
  1299. BasicBlock *NewEHPadBB = nullptr;
  1300. if (isa<LandingPadInst>(Pad)) {
  1301. // Stop on landingpads. They are not funclets.
  1302. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1303. break;
  1304. } else if (isa<CleanupPadInst>(Pad)) {
  1305. // Stop on cleanup pads. Cleanups are always funclet entries for all known
  1306. // personalities.
  1307. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1308. UnwindDests.back().first->setIsEHScopeEntry();
  1309. if (!IsWasmCXX)
  1310. UnwindDests.back().first->setIsEHFuncletEntry();
  1311. break;
  1312. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
  1313. // Add the catchpad handlers to the possible destinations.
  1314. for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
  1315. UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
  1316. // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
  1317. if (IsMSVCCXX || IsCoreCLR)
  1318. UnwindDests.back().first->setIsEHFuncletEntry();
  1319. if (!IsSEH)
  1320. UnwindDests.back().first->setIsEHScopeEntry();
  1321. }
  1322. NewEHPadBB = CatchSwitch->getUnwindDest();
  1323. } else {
  1324. continue;
  1325. }
  1326. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1327. if (BPI && NewEHPadBB)
  1328. Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
  1329. EHPadBB = NewEHPadBB;
  1330. }
  1331. }
  1332. void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
  1333. // Update successor info.
  1334. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  1335. auto UnwindDest = I.getUnwindDest();
  1336. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1337. BranchProbability UnwindDestProb =
  1338. (BPI && UnwindDest)
  1339. ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
  1340. : BranchProbability::getZero();
  1341. findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
  1342. for (auto &UnwindDest : UnwindDests) {
  1343. UnwindDest.first->setIsEHPad();
  1344. addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
  1345. }
  1346. FuncInfo.MBB->normalizeSuccProbs();
  1347. // Create the terminator node.
  1348. SDValue Ret =
  1349. DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
  1350. DAG.setRoot(Ret);
  1351. }
  1352. void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
  1353. report_fatal_error("visitCatchSwitch not yet implemented!");
  1354. }
  1355. void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
  1356. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1357. auto &DL = DAG.getDataLayout();
  1358. SDValue Chain = getControlRoot();
  1359. SmallVector<ISD::OutputArg, 8> Outs;
  1360. SmallVector<SDValue, 8> OutVals;
  1361. // Calls to @llvm.experimental.deoptimize don't generate a return value, so
  1362. // lower
  1363. //
  1364. // %val = call <ty> @llvm.experimental.deoptimize()
  1365. // ret <ty> %val
  1366. //
  1367. // differently.
  1368. if (I.getParent()->getTerminatingDeoptimizeCall()) {
  1369. LowerDeoptimizingReturn();
  1370. return;
  1371. }
  1372. if (!FuncInfo.CanLowerReturn) {
  1373. unsigned DemoteReg = FuncInfo.DemoteRegister;
  1374. const Function *F = I.getParent()->getParent();
  1375. // Emit a store of the return value through the virtual register.
  1376. // Leave Outs empty so that LowerReturn won't try to load return
  1377. // registers the usual way.
  1378. SmallVector<EVT, 1> PtrValueVTs;
  1379. ComputeValueVTs(TLI, DL,
  1380. F->getReturnType()->getPointerTo(
  1381. DAG.getDataLayout().getAllocaAddrSpace()),
  1382. PtrValueVTs);
  1383. SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
  1384. DemoteReg, PtrValueVTs[0]);
  1385. SDValue RetOp = getValue(I.getOperand(0));
  1386. SmallVector<EVT, 4> ValueVTs;
  1387. SmallVector<uint64_t, 4> Offsets;
  1388. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets);
  1389. unsigned NumValues = ValueVTs.size();
  1390. SmallVector<SDValue, 4> Chains(NumValues);
  1391. for (unsigned i = 0; i != NumValues; ++i) {
  1392. // An aggregate return value cannot wrap around the address space, so
  1393. // offsets to its parts don't wrap either.
  1394. SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
  1395. Chains[i] = DAG.getStore(
  1396. Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i),
  1397. // FIXME: better loc info would be nice.
  1398. Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
  1399. }
  1400. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
  1401. MVT::Other, Chains);
  1402. } else if (I.getNumOperands() != 0) {
  1403. SmallVector<EVT, 4> ValueVTs;
  1404. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
  1405. unsigned NumValues = ValueVTs.size();
  1406. if (NumValues) {
  1407. SDValue RetOp = getValue(I.getOperand(0));
  1408. const Function *F = I.getParent()->getParent();
  1409. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  1410. if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
  1411. Attribute::SExt))
  1412. ExtendKind = ISD::SIGN_EXTEND;
  1413. else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
  1414. Attribute::ZExt))
  1415. ExtendKind = ISD::ZERO_EXTEND;
  1416. LLVMContext &Context = F->getContext();
  1417. bool RetInReg = F->getAttributes().hasAttribute(
  1418. AttributeList::ReturnIndex, Attribute::InReg);
  1419. for (unsigned j = 0; j != NumValues; ++j) {
  1420. EVT VT = ValueVTs[j];
  1421. if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
  1422. VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
  1423. CallingConv::ID CC = F->getCallingConv();
  1424. unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
  1425. MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
  1426. SmallVector<SDValue, 4> Parts(NumParts);
  1427. getCopyToParts(DAG, getCurSDLoc(),
  1428. SDValue(RetOp.getNode(), RetOp.getResNo() + j),
  1429. &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
  1430. // 'inreg' on function refers to return value
  1431. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1432. if (RetInReg)
  1433. Flags.setInReg();
  1434. // Propagate extension type if any
  1435. if (ExtendKind == ISD::SIGN_EXTEND)
  1436. Flags.setSExt();
  1437. else if (ExtendKind == ISD::ZERO_EXTEND)
  1438. Flags.setZExt();
  1439. for (unsigned i = 0; i < NumParts; ++i) {
  1440. Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
  1441. VT, /*isfixed=*/true, 0, 0));
  1442. OutVals.push_back(Parts[i]);
  1443. }
  1444. }
  1445. }
  1446. }
  1447. // Push in swifterror virtual register as the last element of Outs. This makes
  1448. // sure swifterror virtual register will be returned in the swifterror
  1449. // physical register.
  1450. const Function *F = I.getParent()->getParent();
  1451. if (TLI.supportSwiftError() &&
  1452. F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
  1453. assert(FuncInfo.SwiftErrorArg && "Need a swift error argument");
  1454. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1455. Flags.setSwiftError();
  1456. Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
  1457. EVT(TLI.getPointerTy(DL)) /*argvt*/,
  1458. true /*isfixed*/, 1 /*origidx*/,
  1459. 0 /*partOffs*/));
  1460. // Create SDNode for the swifterror virtual register.
  1461. OutVals.push_back(
  1462. DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt(
  1463. &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first,
  1464. EVT(TLI.getPointerTy(DL))));
  1465. }
  1466. bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
  1467. CallingConv::ID CallConv =
  1468. DAG.getMachineFunction().getFunction().getCallingConv();
  1469. Chain = DAG.getTargetLoweringInfo().LowerReturn(
  1470. Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
  1471. // Verify that the target's LowerReturn behaved as expected.
  1472. assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
  1473. "LowerReturn didn't return a valid chain!");
  1474. // Update the DAG with the new chain value resulting from return lowering.
  1475. DAG.setRoot(Chain);
  1476. }
  1477. /// CopyToExportRegsIfNeeded - If the given value has virtual registers
  1478. /// created for it, emit nodes to copy the value into the virtual
  1479. /// registers.
  1480. void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
  1481. // Skip empty types
  1482. if (V->getType()->isEmptyTy())
  1483. return;
  1484. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  1485. if (VMI != FuncInfo.ValueMap.end()) {
  1486. assert(!V->use_empty() && "Unused value assigned virtual registers!");
  1487. CopyValueToVirtualRegister(V, VMI->second);
  1488. }
  1489. }
  1490. /// ExportFromCurrentBlock - If this condition isn't known to be exported from
  1491. /// the current basic block, add it to ValueMap now so that we'll get a
  1492. /// CopyTo/FromReg.
  1493. void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
  1494. // No need to export constants.
  1495. if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
  1496. // Already exported?
  1497. if (FuncInfo.isExportedInst(V)) return;
  1498. unsigned Reg = FuncInfo.InitializeRegForValue(V);
  1499. CopyValueToVirtualRegister(V, Reg);
  1500. }
  1501. bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
  1502. const BasicBlock *FromBB) {
  1503. // The operands of the setcc have to be in this block. We don't know
  1504. // how to export them from some other block.
  1505. if (const Instruction *VI = dyn_cast<Instruction>(V)) {
  1506. // Can export from current BB.
  1507. if (VI->getParent() == FromBB)
  1508. return true;
  1509. // Is already exported, noop.
  1510. return FuncInfo.isExportedInst(V);
  1511. }
  1512. // If this is an argument, we can export it if the BB is the entry block or
  1513. // if it is already exported.
  1514. if (isa<Argument>(V)) {
  1515. if (FromBB == &FromBB->getParent()->getEntryBlock())
  1516. return true;
  1517. // Otherwise, can only export this if it is already exported.
  1518. return FuncInfo.isExportedInst(V);
  1519. }
  1520. // Otherwise, constants can always be exported.
  1521. return true;
  1522. }
  1523. /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
  1524. BranchProbability
  1525. SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
  1526. const MachineBasicBlock *Dst) const {
  1527. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1528. const BasicBlock *SrcBB = Src->getBasicBlock();
  1529. const BasicBlock *DstBB = Dst->getBasicBlock();
  1530. if (!BPI) {
  1531. // If BPI is not available, set the default probability as 1 / N, where N is
  1532. // the number of successors.
  1533. auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
  1534. return BranchProbability(1, SuccSize);
  1535. }
  1536. return BPI->getEdgeProbability(SrcBB, DstBB);
  1537. }
  1538. void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
  1539. MachineBasicBlock *Dst,
  1540. BranchProbability Prob) {
  1541. if (!FuncInfo.BPI)
  1542. Src->addSuccessorWithoutProb(Dst);
  1543. else {
  1544. if (Prob.isUnknown())
  1545. Prob = getEdgeProbability(Src, Dst);
  1546. Src->addSuccessor(Dst, Prob);
  1547. }
  1548. }
  1549. static bool InBlock(const Value *V, const BasicBlock *BB) {
  1550. if (const Instruction *I = dyn_cast<Instruction>(V))
  1551. return I->getParent() == BB;
  1552. return true;
  1553. }
  1554. /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
  1555. /// This function emits a branch and is used at the leaves of an OR or an
  1556. /// AND operator tree.
  1557. void
  1558. SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
  1559. MachineBasicBlock *TBB,
  1560. MachineBasicBlock *FBB,
  1561. MachineBasicBlock *CurBB,
  1562. MachineBasicBlock *SwitchBB,
  1563. BranchProbability TProb,
  1564. BranchProbability FProb,
  1565. bool InvertCond) {
  1566. const BasicBlock *BB = CurBB->getBasicBlock();
  1567. // If the leaf of the tree is a comparison, merge the condition into
  1568. // the caseblock.
  1569. if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
  1570. // The operands of the cmp have to be in this block. We don't know
  1571. // how to export them from some other block. If this is the first block
  1572. // of the sequence, no exporting is needed.
  1573. if (CurBB == SwitchBB ||
  1574. (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
  1575. isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
  1576. ISD::CondCode Condition;
  1577. if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
  1578. ICmpInst::Predicate Pred =
  1579. InvertCond ? IC->getInversePredicate() : IC->getPredicate();
  1580. Condition = getICmpCondCode(Pred);
  1581. } else {
  1582. const FCmpInst *FC = cast<FCmpInst>(Cond);
  1583. FCmpInst::Predicate Pred =
  1584. InvertCond ? FC->getInversePredicate() : FC->getPredicate();
  1585. Condition = getFCmpCondCode(Pred);
  1586. if (TM.Options.NoNaNsFPMath)
  1587. Condition = getFCmpCodeWithoutNaN(Condition);
  1588. }
  1589. CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
  1590. TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
  1591. SwitchCases.push_back(CB);
  1592. return;
  1593. }
  1594. }
  1595. // Create a CaseBlock record representing this branch.
  1596. ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
  1597. CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
  1598. nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
  1599. SwitchCases.push_back(CB);
  1600. }
  1601. /// FindMergedConditions - If Cond is an expression like
  1602. void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
  1603. MachineBasicBlock *TBB,
  1604. MachineBasicBlock *FBB,
  1605. MachineBasicBlock *CurBB,
  1606. MachineBasicBlock *SwitchBB,
  1607. Instruction::BinaryOps Opc,
  1608. BranchProbability TProb,
  1609. BranchProbability FProb,
  1610. bool InvertCond) {
  1611. // Skip over not part of the tree and remember to invert op and operands at
  1612. // next level.
  1613. if (BinaryOperator::isNot(Cond) && Cond->hasOneUse()) {
  1614. const Value *CondOp = BinaryOperator::getNotArgument(Cond);
  1615. if (InBlock(CondOp, CurBB->getBasicBlock())) {
  1616. FindMergedConditions(CondOp, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
  1617. !InvertCond);
  1618. return;
  1619. }
  1620. }
  1621. const Instruction *BOp = dyn_cast<Instruction>(Cond);
  1622. // Compute the effective opcode for Cond, taking into account whether it needs
  1623. // to be inverted, e.g.
  1624. // and (not (or A, B)), C
  1625. // gets lowered as
  1626. // and (and (not A, not B), C)
  1627. unsigned BOpc = 0;
  1628. if (BOp) {
  1629. BOpc = BOp->getOpcode();
  1630. if (InvertCond) {
  1631. if (BOpc == Instruction::And)
  1632. BOpc = Instruction::Or;
  1633. else if (BOpc == Instruction::Or)
  1634. BOpc = Instruction::And;
  1635. }
  1636. }
  1637. // If this node is not part of the or/and tree, emit it as a branch.
  1638. if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
  1639. BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
  1640. BOp->getParent() != CurBB->getBasicBlock() ||
  1641. !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
  1642. !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
  1643. EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
  1644. TProb, FProb, InvertCond);
  1645. return;
  1646. }
  1647. // Create TmpBB after CurBB.
  1648. MachineFunction::iterator BBI(CurBB);
  1649. MachineFunction &MF = DAG.getMachineFunction();
  1650. MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
  1651. CurBB->getParent()->insert(++BBI, TmpBB);
  1652. if (Opc == Instruction::Or) {
  1653. // Codegen X | Y as:
  1654. // BB1:
  1655. // jmp_if_X TBB
  1656. // jmp TmpBB
  1657. // TmpBB:
  1658. // jmp_if_Y TBB
  1659. // jmp FBB
  1660. //
  1661. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1662. // The requirement is that
  1663. // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
  1664. // = TrueProb for original BB.
  1665. // Assuming the original probabilities are A and B, one choice is to set
  1666. // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
  1667. // A/(1+B) and 2B/(1+B). This choice assumes that
  1668. // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
  1669. // Another choice is to assume TrueProb for BB1 equals to TrueProb for
  1670. // TmpBB, but the math is more complicated.
  1671. auto NewTrueProb = TProb / 2;
  1672. auto NewFalseProb = TProb / 2 + FProb;
  1673. // Emit the LHS condition.
  1674. FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
  1675. NewTrueProb, NewFalseProb, InvertCond);
  1676. // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
  1677. SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
  1678. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  1679. // Emit the RHS condition into TmpBB.
  1680. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
  1681. Probs[0], Probs[1], InvertCond);
  1682. } else {
  1683. assert(Opc == Instruction::And && "Unknown merge op!");
  1684. // Codegen X & Y as:
  1685. // BB1:
  1686. // jmp_if_X TmpBB
  1687. // jmp FBB
  1688. // TmpBB:
  1689. // jmp_if_Y TBB
  1690. // jmp FBB
  1691. //
  1692. // This requires creation of TmpBB after CurBB.
  1693. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1694. // The requirement is that
  1695. // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
  1696. // = FalseProb for original BB.
  1697. // Assuming the original probabilities are A and B, one choice is to set
  1698. // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
  1699. // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
  1700. // TrueProb for BB1 * FalseProb for TmpBB.
  1701. auto NewTrueProb = TProb + FProb / 2;
  1702. auto NewFalseProb = FProb / 2;
  1703. // Emit the LHS condition.
  1704. FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
  1705. NewTrueProb, NewFalseProb, InvertCond);
  1706. // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
  1707. SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
  1708. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  1709. // Emit the RHS condition into TmpBB.
  1710. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
  1711. Probs[0], Probs[1], InvertCond);
  1712. }
  1713. }
  1714. /// If the set of cases should be emitted as a series of branches, return true.
  1715. /// If we should emit this as a bunch of and/or'd together conditions, return
  1716. /// false.
  1717. bool
  1718. SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
  1719. if (Cases.size() != 2) return true;
  1720. // If this is two comparisons of the same values or'd or and'd together, they
  1721. // will get folded into a single comparison, so don't emit two blocks.
  1722. if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
  1723. Cases[0].CmpRHS == Cases[1].CmpRHS) ||
  1724. (Cases[0].CmpRHS == Cases[1].CmpLHS &&
  1725. Cases[0].CmpLHS == Cases[1].CmpRHS)) {
  1726. return false;
  1727. }
  1728. // Handle: (X != null) | (Y != null) --> (X|Y) != 0
  1729. // Handle: (X == null) & (Y == null) --> (X|Y) == 0
  1730. if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
  1731. Cases[0].CC == Cases[1].CC &&
  1732. isa<Constant>(Cases[0].CmpRHS) &&
  1733. cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
  1734. if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
  1735. return false;
  1736. if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
  1737. return false;
  1738. }
  1739. return true;
  1740. }
  1741. void SelectionDAGBuilder::visitBr(const BranchInst &I) {
  1742. MachineBasicBlock *BrMBB = FuncInfo.MBB;
  1743. // Update machine-CFG edges.
  1744. MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
  1745. if (I.isUnconditional()) {
  1746. // Update machine-CFG edges.
  1747. BrMBB->addSuccessor(Succ0MBB);
  1748. // If this is not a fall-through branch or optimizations are switched off,
  1749. // emit the branch.
  1750. if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
  1751. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  1752. MVT::Other, getControlRoot(),
  1753. DAG.getBasicBlock(Succ0MBB)));
  1754. return;
  1755. }
  1756. // If this condition is one of the special cases we handle, do special stuff
  1757. // now.
  1758. const Value *CondVal = I.getCondition();
  1759. MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
  1760. // If this is a series of conditions that are or'd or and'd together, emit
  1761. // this as a sequence of branches instead of setcc's with and/or operations.
  1762. // As long as jumps are not expensive, this should improve performance.
  1763. // For example, instead of something like:
  1764. // cmp A, B
  1765. // C = seteq
  1766. // cmp D, E
  1767. // F = setle
  1768. // or C, F
  1769. // jnz foo
  1770. // Emit:
  1771. // cmp A, B
  1772. // je foo
  1773. // cmp D, E
  1774. // jle foo
  1775. if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
  1776. Instruction::BinaryOps Opcode = BOp->getOpcode();
  1777. if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
  1778. !I.getMetadata(LLVMContext::MD_unpredictable) &&
  1779. (Opcode == Instruction::And || Opcode == Instruction::Or)) {
  1780. FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
  1781. Opcode,
  1782. getEdgeProbability(BrMBB, Succ0MBB),
  1783. getEdgeProbability(BrMBB, Succ1MBB),
  1784. /*InvertCond=*/false);
  1785. // If the compares in later blocks need to use values not currently
  1786. // exported from this block, export them now. This block should always
  1787. // be the first entry.
  1788. assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
  1789. // Allow some cases to be rejected.
  1790. if (ShouldEmitAsBranches(SwitchCases)) {
  1791. for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
  1792. ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
  1793. ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
  1794. }
  1795. // Emit the branch for this block.
  1796. visitSwitchCase(SwitchCases[0], BrMBB);
  1797. SwitchCases.erase(SwitchCases.begin());
  1798. return;
  1799. }
  1800. // Okay, we decided not to do this, remove any inserted MBB's and clear
  1801. // SwitchCases.
  1802. for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
  1803. FuncInfo.MF->erase(SwitchCases[i].ThisBB);
  1804. SwitchCases.clear();
  1805. }
  1806. }
  1807. // Create a CaseBlock record representing this branch.
  1808. CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
  1809. nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
  1810. // Use visitSwitchCase to actually insert the fast branch sequence for this
  1811. // cond branch.
  1812. visitSwitchCase(CB, BrMBB);
  1813. }
  1814. /// visitSwitchCase - Emits the necessary code to represent a single node in
  1815. /// the binary search tree resulting from lowering a switch instruction.
  1816. void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
  1817. MachineBasicBlock *SwitchBB) {
  1818. SDValue Cond;
  1819. SDValue CondLHS = getValue(CB.CmpLHS);
  1820. SDLoc dl = CB.DL;
  1821. // Build the setcc now.
  1822. if (!CB.CmpMHS) {
  1823. // Fold "(X == true)" to X and "(X == false)" to !X to
  1824. // handle common cases produced by branch lowering.
  1825. if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
  1826. CB.CC == ISD::SETEQ)
  1827. Cond = CondLHS;
  1828. else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
  1829. CB.CC == ISD::SETEQ) {
  1830. SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
  1831. Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
  1832. } else
  1833. Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
  1834. } else {
  1835. assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
  1836. const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
  1837. const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
  1838. SDValue CmpOp = getValue(CB.CmpMHS);
  1839. EVT VT = CmpOp.getValueType();
  1840. if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
  1841. Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
  1842. ISD::SETLE);
  1843. } else {
  1844. SDValue SUB = DAG.getNode(ISD::SUB, dl,
  1845. VT, CmpOp, DAG.getConstant(Low, dl, VT));
  1846. Cond = DAG.getSetCC(dl, MVT::i1, SUB,
  1847. DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
  1848. }
  1849. }
  1850. // Update successor info
  1851. addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
  1852. // TrueBB and FalseBB are always different unless the incoming IR is
  1853. // degenerate. This only happens when running llc on weird IR.
  1854. if (CB.TrueBB != CB.FalseBB)
  1855. addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
  1856. SwitchBB->normalizeSuccProbs();
  1857. // If the lhs block is the next block, invert the condition so that we can
  1858. // fall through to the lhs instead of the rhs block.
  1859. if (CB.TrueBB == NextBlock(SwitchBB)) {
  1860. std::swap(CB.TrueBB, CB.FalseBB);
  1861. SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
  1862. Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
  1863. }
  1864. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  1865. MVT::Other, getControlRoot(), Cond,
  1866. DAG.getBasicBlock(CB.TrueBB));
  1867. // Insert the false branch. Do this even if it's a fall through branch,
  1868. // this makes it easier to do DAG optimizations which require inverting
  1869. // the branch condition.
  1870. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  1871. DAG.getBasicBlock(CB.FalseBB));
  1872. DAG.setRoot(BrCond);
  1873. }
  1874. /// visitJumpTable - Emit JumpTable node in the current MBB
  1875. void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
  1876. // Emit the code for the jump table
  1877. assert(JT.Reg != -1U && "Should lower JT Header first!");
  1878. EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
  1879. SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
  1880. JT.Reg, PTy);
  1881. SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
  1882. SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
  1883. MVT::Other, Index.getValue(1),
  1884. Table, Index);
  1885. DAG.setRoot(BrJumpTable);
  1886. }
  1887. /// visitJumpTableHeader - This function emits necessary code to produce index
  1888. /// in the JumpTable from switch case.
  1889. void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
  1890. JumpTableHeader &JTH,
  1891. MachineBasicBlock *SwitchBB) {
  1892. SDLoc dl = getCurSDLoc();
  1893. // Subtract the lowest switch case value from the value being switched on and
  1894. // conditional branch to default mbb if the result is greater than the
  1895. // difference between smallest and largest cases.
  1896. SDValue SwitchOp = getValue(JTH.SValue);
  1897. EVT VT = SwitchOp.getValueType();
  1898. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
  1899. DAG.getConstant(JTH.First, dl, VT));
  1900. // The SDNode we just created, which holds the value being switched on minus
  1901. // the smallest case value, needs to be copied to a virtual register so it
  1902. // can be used as an index into the jump table in a subsequent basic block.
  1903. // This value may be smaller or larger than the target's pointer type, and
  1904. // therefore require extension or truncating.
  1905. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1906. SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
  1907. unsigned JumpTableReg =
  1908. FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
  1909. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
  1910. JumpTableReg, SwitchOp);
  1911. JT.Reg = JumpTableReg;
  1912. // Emit the range check for the jump table, and branch to the default block
  1913. // for the switch statement if the value being switched on exceeds the largest
  1914. // case in the switch.
  1915. SDValue CMP = DAG.getSetCC(
  1916. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  1917. Sub.getValueType()),
  1918. Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
  1919. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  1920. MVT::Other, CopyTo, CMP,
  1921. DAG.getBasicBlock(JT.Default));
  1922. // Avoid emitting unnecessary branches to the next block.
  1923. if (JT.MBB != NextBlock(SwitchBB))
  1924. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  1925. DAG.getBasicBlock(JT.MBB));
  1926. DAG.setRoot(BrCond);
  1927. }
  1928. /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
  1929. /// variable if there exists one.
  1930. static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
  1931. SDValue &Chain) {
  1932. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1933. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  1934. MachineFunction &MF = DAG.getMachineFunction();
  1935. Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
  1936. MachineSDNode *Node =
  1937. DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
  1938. if (Global) {
  1939. MachinePointerInfo MPInfo(Global);
  1940. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
  1941. MachineMemOperand::MODereferenceable;
  1942. MachineMemOperand *MemRef = MF.getMachineMemOperand(
  1943. MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
  1944. DAG.setNodeMemRefs(Node, {MemRef});
  1945. }
  1946. return SDValue(Node, 0);
  1947. }
  1948. /// Codegen a new tail for a stack protector check ParentMBB which has had its
  1949. /// tail spliced into a stack protector check success bb.
  1950. ///
  1951. /// For a high level explanation of how this fits into the stack protector
  1952. /// generation see the comment on the declaration of class
  1953. /// StackProtectorDescriptor.
  1954. void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
  1955. MachineBasicBlock *ParentBB) {
  1956. // First create the loads to the guard/stack slot for the comparison.
  1957. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1958. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  1959. MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
  1960. int FI = MFI.getStackProtectorIndex();
  1961. SDValue Guard;
  1962. SDLoc dl = getCurSDLoc();
  1963. SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
  1964. const Module &M = *ParentBB->getParent()->getFunction().getParent();
  1965. unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
  1966. // Generate code to load the content of the guard slot.
  1967. SDValue GuardVal = DAG.getLoad(
  1968. PtrTy, dl, DAG.getEntryNode(), StackSlotPtr,
  1969. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
  1970. MachineMemOperand::MOVolatile);
  1971. if (TLI.useStackGuardXorFP())
  1972. GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
  1973. // Retrieve guard check function, nullptr if instrumentation is inlined.
  1974. if (const Value *GuardCheck = TLI.getSSPStackGuardCheck(M)) {
  1975. // The target provides a guard check function to validate the guard value.
  1976. // Generate a call to that function with the content of the guard slot as
  1977. // argument.
  1978. auto *Fn = cast<Function>(GuardCheck);
  1979. FunctionType *FnTy = Fn->getFunctionType();
  1980. assert(FnTy->getNumParams() == 1 && "Invalid function signature");
  1981. TargetLowering::ArgListTy Args;
  1982. TargetLowering::ArgListEntry Entry;
  1983. Entry.Node = GuardVal;
  1984. Entry.Ty = FnTy->getParamType(0);
  1985. if (Fn->hasAttribute(1, Attribute::AttrKind::InReg))
  1986. Entry.IsInReg = true;
  1987. Args.push_back(Entry);
  1988. TargetLowering::CallLoweringInfo CLI(DAG);
  1989. CLI.setDebugLoc(getCurSDLoc())
  1990. .setChain(DAG.getEntryNode())
  1991. .setCallee(Fn->getCallingConv(), FnTy->getReturnType(),
  1992. getValue(GuardCheck), std::move(Args));
  1993. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  1994. DAG.setRoot(Result.second);
  1995. return;
  1996. }
  1997. // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
  1998. // Otherwise, emit a volatile load to retrieve the stack guard value.
  1999. SDValue Chain = DAG.getEntryNode();
  2000. if (TLI.useLoadStackGuardNode()) {
  2001. Guard = getLoadStackGuard(DAG, dl, Chain);
  2002. } else {
  2003. const Value *IRGuard = TLI.getSDagStackGuard(M);
  2004. SDValue GuardPtr = getValue(IRGuard);
  2005. Guard =
  2006. DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0),
  2007. Align, MachineMemOperand::MOVolatile);
  2008. }
  2009. // Perform the comparison via a subtract/getsetcc.
  2010. EVT VT = Guard.getValueType();
  2011. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
  2012. SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
  2013. *DAG.getContext(),
  2014. Sub.getValueType()),
  2015. Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
  2016. // If the sub is not 0, then we know the guard/stackslot do not equal, so
  2017. // branch to failure MBB.
  2018. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2019. MVT::Other, GuardVal.getOperand(0),
  2020. Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
  2021. // Otherwise branch to success MBB.
  2022. SDValue Br = DAG.getNode(ISD::BR, dl,
  2023. MVT::Other, BrCond,
  2024. DAG.getBasicBlock(SPD.getSuccessMBB()));
  2025. DAG.setRoot(Br);
  2026. }
  2027. /// Codegen the failure basic block for a stack protector check.
  2028. ///
  2029. /// A failure stack protector machine basic block consists simply of a call to
  2030. /// __stack_chk_fail().
  2031. ///
  2032. /// For a high level explanation of how this fits into the stack protector
  2033. /// generation see the comment on the declaration of class
  2034. /// StackProtectorDescriptor.
  2035. void
  2036. SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
  2037. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2038. SDValue Chain =
  2039. TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
  2040. None, false, getCurSDLoc(), false, false).second;
  2041. DAG.setRoot(Chain);
  2042. }
  2043. /// visitBitTestHeader - This function emits necessary code to produce value
  2044. /// suitable for "bit tests"
  2045. void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
  2046. MachineBasicBlock *SwitchBB) {
  2047. SDLoc dl = getCurSDLoc();
  2048. // Subtract the minimum value
  2049. SDValue SwitchOp = getValue(B.SValue);
  2050. EVT VT = SwitchOp.getValueType();
  2051. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
  2052. DAG.getConstant(B.First, dl, VT));
  2053. // Check range
  2054. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2055. SDValue RangeCmp = DAG.getSetCC(
  2056. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  2057. Sub.getValueType()),
  2058. Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
  2059. // Determine the type of the test operands.
  2060. bool UsePtrType = false;
  2061. if (!TLI.isTypeLegal(VT))
  2062. UsePtrType = true;
  2063. else {
  2064. for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
  2065. if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
  2066. // Switch table case range are encoded into series of masks.
  2067. // Just use pointer type, it's guaranteed to fit.
  2068. UsePtrType = true;
  2069. break;
  2070. }
  2071. }
  2072. if (UsePtrType) {
  2073. VT = TLI.getPointerTy(DAG.getDataLayout());
  2074. Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
  2075. }
  2076. B.RegVT = VT.getSimpleVT();
  2077. B.Reg = FuncInfo.CreateReg(B.RegVT);
  2078. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
  2079. MachineBasicBlock* MBB = B.Cases[0].ThisBB;
  2080. addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
  2081. addSuccessorWithProb(SwitchBB, MBB, B.Prob);
  2082. SwitchBB->normalizeSuccProbs();
  2083. SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
  2084. MVT::Other, CopyTo, RangeCmp,
  2085. DAG.getBasicBlock(B.Default));
  2086. // Avoid emitting unnecessary branches to the next block.
  2087. if (MBB != NextBlock(SwitchBB))
  2088. BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
  2089. DAG.getBasicBlock(MBB));
  2090. DAG.setRoot(BrRange);
  2091. }
  2092. /// visitBitTestCase - this function produces one "bit test"
  2093. void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
  2094. MachineBasicBlock* NextMBB,
  2095. BranchProbability BranchProbToNext,
  2096. unsigned Reg,
  2097. BitTestCase &B,
  2098. MachineBasicBlock *SwitchBB) {
  2099. SDLoc dl = getCurSDLoc();
  2100. MVT VT = BB.RegVT;
  2101. SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
  2102. SDValue Cmp;
  2103. unsigned PopCount = countPopulation(B.Mask);
  2104. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2105. if (PopCount == 1) {
  2106. // Testing for a single bit; just compare the shift count with what it
  2107. // would need to be to shift a 1 bit in that position.
  2108. Cmp = DAG.getSetCC(
  2109. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2110. ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
  2111. ISD::SETEQ);
  2112. } else if (PopCount == BB.Range) {
  2113. // There is only one zero bit in the range, test for it directly.
  2114. Cmp = DAG.getSetCC(
  2115. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2116. ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
  2117. ISD::SETNE);
  2118. } else {
  2119. // Make desired shift
  2120. SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
  2121. DAG.getConstant(1, dl, VT), ShiftOp);
  2122. // Emit bit tests and jumps
  2123. SDValue AndOp = DAG.getNode(ISD::AND, dl,
  2124. VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
  2125. Cmp = DAG.getSetCC(
  2126. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2127. AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
  2128. }
  2129. // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
  2130. addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
  2131. // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
  2132. addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
  2133. // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
  2134. // one as they are relative probabilities (and thus work more like weights),
  2135. // and hence we need to normalize them to let the sum of them become one.
  2136. SwitchBB->normalizeSuccProbs();
  2137. SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
  2138. MVT::Other, getControlRoot(),
  2139. Cmp, DAG.getBasicBlock(B.TargetBB));
  2140. // Avoid emitting unnecessary branches to the next block.
  2141. if (NextMBB != NextBlock(SwitchBB))
  2142. BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
  2143. DAG.getBasicBlock(NextMBB));
  2144. DAG.setRoot(BrAnd);
  2145. }
  2146. void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
  2147. MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
  2148. // Retrieve successors. Look through artificial IR level blocks like
  2149. // catchswitch for successors.
  2150. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
  2151. const BasicBlock *EHPadBB = I.getSuccessor(1);
  2152. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  2153. // have to do anything here to lower funclet bundles.
  2154. assert(!I.hasOperandBundlesOtherThan(
  2155. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  2156. "Cannot lower invokes with arbitrary operand bundles yet!");
  2157. const Value *Callee(I.getCalledValue());
  2158. const Function *Fn = dyn_cast<Function>(Callee);
  2159. if (isa<InlineAsm>(Callee))
  2160. visitInlineAsm(&I);
  2161. else if (Fn && Fn->isIntrinsic()) {
  2162. switch (Fn->getIntrinsicID()) {
  2163. default:
  2164. llvm_unreachable("Cannot invoke this intrinsic");
  2165. case Intrinsic::donothing:
  2166. // Ignore invokes to @llvm.donothing: jump directly to the next BB.
  2167. break;
  2168. case Intrinsic::experimental_patchpoint_void:
  2169. case Intrinsic::experimental_patchpoint_i64:
  2170. visitPatchpoint(&I, EHPadBB);
  2171. break;
  2172. case Intrinsic::experimental_gc_statepoint:
  2173. LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
  2174. break;
  2175. }
  2176. } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
  2177. // Currently we do not lower any intrinsic calls with deopt operand bundles.
  2178. // Eventually we will support lowering the @llvm.experimental.deoptimize
  2179. // intrinsic, and right now there are no plans to support other intrinsics
  2180. // with deopt state.
  2181. LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
  2182. } else {
  2183. LowerCallTo(&I, getValue(Callee), false, EHPadBB);
  2184. }
  2185. // If the value of the invoke is used outside of its defining block, make it
  2186. // available as a virtual register.
  2187. // We already took care of the exported value for the statepoint instruction
  2188. // during call to the LowerStatepoint.
  2189. if (!isStatepoint(I)) {
  2190. CopyToExportRegsIfNeeded(&I);
  2191. }
  2192. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  2193. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  2194. BranchProbability EHPadBBProb =
  2195. BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
  2196. : BranchProbability::getZero();
  2197. findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
  2198. // Update successor info.
  2199. addSuccessorWithProb(InvokeMBB, Return);
  2200. for (auto &UnwindDest : UnwindDests) {
  2201. UnwindDest.first->setIsEHPad();
  2202. addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
  2203. }
  2204. InvokeMBB->normalizeSuccProbs();
  2205. // Drop into normal successor.
  2206. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  2207. MVT::Other, getControlRoot(),
  2208. DAG.getBasicBlock(Return)));
  2209. }
  2210. void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
  2211. llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
  2212. }
  2213. void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
  2214. assert(FuncInfo.MBB->isEHPad() &&
  2215. "Call to landingpad not in landing pad!");
  2216. // If there aren't registers to copy the values into (e.g., during SjLj
  2217. // exceptions), then don't bother to create these DAG nodes.
  2218. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2219. const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
  2220. if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
  2221. TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
  2222. return;
  2223. // If landingpad's return type is token type, we don't create DAG nodes
  2224. // for its exception pointer and selector value. The extraction of exception
  2225. // pointer or selector value from token type landingpads is not currently
  2226. // supported.
  2227. if (LP.getType()->isTokenTy())
  2228. return;
  2229. SmallVector<EVT, 2> ValueVTs;
  2230. SDLoc dl = getCurSDLoc();
  2231. ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
  2232. assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
  2233. // Get the two live-in registers as SDValues. The physregs have already been
  2234. // copied into virtual registers.
  2235. SDValue Ops[2];
  2236. if (FuncInfo.ExceptionPointerVirtReg) {
  2237. Ops[0] = DAG.getZExtOrTrunc(
  2238. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2239. FuncInfo.ExceptionPointerVirtReg,
  2240. TLI.getPointerTy(DAG.getDataLayout())),
  2241. dl, ValueVTs[0]);
  2242. } else {
  2243. Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
  2244. }
  2245. Ops[1] = DAG.getZExtOrTrunc(
  2246. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2247. FuncInfo.ExceptionSelectorVirtReg,
  2248. TLI.getPointerTy(DAG.getDataLayout())),
  2249. dl, ValueVTs[1]);
  2250. // Merge into one.
  2251. SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
  2252. DAG.getVTList(ValueVTs), Ops);
  2253. setValue(&LP, Res);
  2254. }
  2255. void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
  2256. #ifndef NDEBUG
  2257. for (const CaseCluster &CC : Clusters)
  2258. assert(CC.Low == CC.High && "Input clusters must be single-case");
  2259. #endif
  2260. llvm::sort(Clusters, [](const CaseCluster &a, const CaseCluster &b) {
  2261. return a.Low->getValue().slt(b.Low->getValue());
  2262. });
  2263. // Merge adjacent clusters with the same destination.
  2264. const unsigned N = Clusters.size();
  2265. unsigned DstIndex = 0;
  2266. for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
  2267. CaseCluster &CC = Clusters[SrcIndex];
  2268. const ConstantInt *CaseVal = CC.Low;
  2269. MachineBasicBlock *Succ = CC.MBB;
  2270. if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
  2271. (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
  2272. // If this case has the same successor and is a neighbour, merge it into
  2273. // the previous cluster.
  2274. Clusters[DstIndex - 1].High = CaseVal;
  2275. Clusters[DstIndex - 1].Prob += CC.Prob;
  2276. } else {
  2277. std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
  2278. sizeof(Clusters[SrcIndex]));
  2279. }
  2280. }
  2281. Clusters.resize(DstIndex);
  2282. }
  2283. void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
  2284. MachineBasicBlock *Last) {
  2285. // Update JTCases.
  2286. for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
  2287. if (JTCases[i].first.HeaderBB == First)
  2288. JTCases[i].first.HeaderBB = Last;
  2289. // Update BitTestCases.
  2290. for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
  2291. if (BitTestCases[i].Parent == First)
  2292. BitTestCases[i].Parent = Last;
  2293. }
  2294. void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
  2295. MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
  2296. // Update machine-CFG edges with unique successors.
  2297. SmallSet<BasicBlock*, 32> Done;
  2298. for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
  2299. BasicBlock *BB = I.getSuccessor(i);
  2300. bool Inserted = Done.insert(BB).second;
  2301. if (!Inserted)
  2302. continue;
  2303. MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
  2304. addSuccessorWithProb(IndirectBrMBB, Succ);
  2305. }
  2306. IndirectBrMBB->normalizeSuccProbs();
  2307. DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
  2308. MVT::Other, getControlRoot(),
  2309. getValue(I.getAddress())));
  2310. }
  2311. void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
  2312. if (!DAG.getTarget().Options.TrapUnreachable)
  2313. return;
  2314. // We may be able to ignore unreachable behind a noreturn call.
  2315. if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
  2316. const BasicBlock &BB = *I.getParent();
  2317. if (&I != &BB.front()) {
  2318. BasicBlock::const_iterator PredI =
  2319. std::prev(BasicBlock::const_iterator(&I));
  2320. if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
  2321. if (Call->doesNotReturn())
  2322. return;
  2323. }
  2324. }
  2325. }
  2326. DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
  2327. }
  2328. void SelectionDAGBuilder::visitFSub(const User &I) {
  2329. // -0.0 - X --> fneg
  2330. Type *Ty = I.getType();
  2331. if (isa<Constant>(I.getOperand(0)) &&
  2332. I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
  2333. SDValue Op2 = getValue(I.getOperand(1));
  2334. setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
  2335. Op2.getValueType(), Op2));
  2336. return;
  2337. }
  2338. visitBinary(I, ISD::FSUB);
  2339. }
  2340. /// Checks if the given instruction performs a vector reduction, in which case
  2341. /// we have the freedom to alter the elements in the result as long as the
  2342. /// reduction of them stays unchanged.
  2343. static bool isVectorReductionOp(const User *I) {
  2344. const Instruction *Inst = dyn_cast<Instruction>(I);
  2345. if (!Inst || !Inst->getType()->isVectorTy())
  2346. return false;
  2347. auto OpCode = Inst->getOpcode();
  2348. switch (OpCode) {
  2349. case Instruction::Add:
  2350. case Instruction::Mul:
  2351. case Instruction::And:
  2352. case Instruction::Or:
  2353. case Instruction::Xor:
  2354. break;
  2355. case Instruction::FAdd:
  2356. case Instruction::FMul:
  2357. if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
  2358. if (FPOp->getFastMathFlags().isFast())
  2359. break;
  2360. LLVM_FALLTHROUGH;
  2361. default:
  2362. return false;
  2363. }
  2364. unsigned ElemNum = Inst->getType()->getVectorNumElements();
  2365. // Ensure the reduction size is a power of 2.
  2366. if (!isPowerOf2_32(ElemNum))
  2367. return false;
  2368. unsigned ElemNumToReduce = ElemNum;
  2369. // Do DFS search on the def-use chain from the given instruction. We only
  2370. // allow four kinds of operations during the search until we reach the
  2371. // instruction that extracts the first element from the vector:
  2372. //
  2373. // 1. The reduction operation of the same opcode as the given instruction.
  2374. //
  2375. // 2. PHI node.
  2376. //
  2377. // 3. ShuffleVector instruction together with a reduction operation that
  2378. // does a partial reduction.
  2379. //
  2380. // 4. ExtractElement that extracts the first element from the vector, and we
  2381. // stop searching the def-use chain here.
  2382. //
  2383. // 3 & 4 above perform a reduction on all elements of the vector. We push defs
  2384. // from 1-3 to the stack to continue the DFS. The given instruction is not
  2385. // a reduction operation if we meet any other instructions other than those
  2386. // listed above.
  2387. SmallVector<const User *, 16> UsersToVisit{Inst};
  2388. SmallPtrSet<const User *, 16> Visited;
  2389. bool ReduxExtracted = false;
  2390. while (!UsersToVisit.empty()) {
  2391. auto User = UsersToVisit.back();
  2392. UsersToVisit.pop_back();
  2393. if (!Visited.insert(User).second)
  2394. continue;
  2395. for (const auto &U : User->users()) {
  2396. auto Inst = dyn_cast<Instruction>(U);
  2397. if (!Inst)
  2398. return false;
  2399. if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
  2400. if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
  2401. if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
  2402. return false;
  2403. UsersToVisit.push_back(U);
  2404. } else if (const ShuffleVectorInst *ShufInst =
  2405. dyn_cast<ShuffleVectorInst>(U)) {
  2406. // Detect the following pattern: A ShuffleVector instruction together
  2407. // with a reduction that do partial reduction on the first and second
  2408. // ElemNumToReduce / 2 elements, and store the result in
  2409. // ElemNumToReduce / 2 elements in another vector.
  2410. unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
  2411. if (ResultElements < ElemNum)
  2412. return false;
  2413. if (ElemNumToReduce == 1)
  2414. return false;
  2415. if (!isa<UndefValue>(U->getOperand(1)))
  2416. return false;
  2417. for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
  2418. if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
  2419. return false;
  2420. for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
  2421. if (ShufInst->getMaskValue(i) != -1)
  2422. return false;
  2423. // There is only one user of this ShuffleVector instruction, which
  2424. // must be a reduction operation.
  2425. if (!U->hasOneUse())
  2426. return false;
  2427. auto U2 = dyn_cast<Instruction>(*U->user_begin());
  2428. if (!U2 || U2->getOpcode() != OpCode)
  2429. return false;
  2430. // Check operands of the reduction operation.
  2431. if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
  2432. (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
  2433. UsersToVisit.push_back(U2);
  2434. ElemNumToReduce /= 2;
  2435. } else
  2436. return false;
  2437. } else if (isa<ExtractElementInst>(U)) {
  2438. // At this moment we should have reduced all elements in the vector.
  2439. if (ElemNumToReduce != 1)
  2440. return false;
  2441. const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
  2442. if (!Val || !Val->isZero())
  2443. return false;
  2444. ReduxExtracted = true;
  2445. } else
  2446. return false;
  2447. }
  2448. }
  2449. return ReduxExtracted;
  2450. }
  2451. void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
  2452. SDNodeFlags Flags;
  2453. if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
  2454. Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
  2455. Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
  2456. }
  2457. if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
  2458. Flags.setExact(ExactOp->isExact());
  2459. }
  2460. if (isVectorReductionOp(&I)) {
  2461. Flags.setVectorReduction(true);
  2462. LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
  2463. }
  2464. SDValue Op1 = getValue(I.getOperand(0));
  2465. SDValue Op2 = getValue(I.getOperand(1));
  2466. SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
  2467. Op1, Op2, Flags);
  2468. setValue(&I, BinNodeValue);
  2469. }
  2470. void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
  2471. SDValue Op1 = getValue(I.getOperand(0));
  2472. SDValue Op2 = getValue(I.getOperand(1));
  2473. EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
  2474. Op1.getValueType(), DAG.getDataLayout());
  2475. // Coerce the shift amount to the right type if we can.
  2476. if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
  2477. unsigned ShiftSize = ShiftTy.getSizeInBits();
  2478. unsigned Op2Size = Op2.getValueSizeInBits();
  2479. SDLoc DL = getCurSDLoc();
  2480. // If the operand is smaller than the shift count type, promote it.
  2481. if (ShiftSize > Op2Size)
  2482. Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
  2483. // If the operand is larger than the shift count type but the shift
  2484. // count type has enough bits to represent any shift value, truncate
  2485. // it now. This is a common case and it exposes the truncate to
  2486. // optimization early.
  2487. else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
  2488. Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
  2489. // Otherwise we'll need to temporarily settle for some other convenient
  2490. // type. Type legalization will make adjustments once the shiftee is split.
  2491. else
  2492. Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
  2493. }
  2494. bool nuw = false;
  2495. bool nsw = false;
  2496. bool exact = false;
  2497. if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
  2498. if (const OverflowingBinaryOperator *OFBinOp =
  2499. dyn_cast<const OverflowingBinaryOperator>(&I)) {
  2500. nuw = OFBinOp->hasNoUnsignedWrap();
  2501. nsw = OFBinOp->hasNoSignedWrap();
  2502. }
  2503. if (const PossiblyExactOperator *ExactOp =
  2504. dyn_cast<const PossiblyExactOperator>(&I))
  2505. exact = ExactOp->isExact();
  2506. }
  2507. SDNodeFlags Flags;
  2508. Flags.setExact(exact);
  2509. Flags.setNoSignedWrap(nsw);
  2510. Flags.setNoUnsignedWrap(nuw);
  2511. SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
  2512. Flags);
  2513. setValue(&I, Res);
  2514. }
  2515. void SelectionDAGBuilder::visitSDiv(const User &I) {
  2516. SDValue Op1 = getValue(I.getOperand(0));
  2517. SDValue Op2 = getValue(I.getOperand(1));
  2518. SDNodeFlags Flags;
  2519. Flags.setExact(isa<PossiblyExactOperator>(&I) &&
  2520. cast<PossiblyExactOperator>(&I)->isExact());
  2521. setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
  2522. Op2, Flags));
  2523. }
  2524. void SelectionDAGBuilder::visitICmp(const User &I) {
  2525. ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
  2526. if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
  2527. predicate = IC->getPredicate();
  2528. else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
  2529. predicate = ICmpInst::Predicate(IC->getPredicate());
  2530. SDValue Op1 = getValue(I.getOperand(0));
  2531. SDValue Op2 = getValue(I.getOperand(1));
  2532. ISD::CondCode Opcode = getICmpCondCode(predicate);
  2533. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2534. I.getType());
  2535. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
  2536. }
  2537. void SelectionDAGBuilder::visitFCmp(const User &I) {
  2538. FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
  2539. if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
  2540. predicate = FC->getPredicate();
  2541. else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
  2542. predicate = FCmpInst::Predicate(FC->getPredicate());
  2543. SDValue Op1 = getValue(I.getOperand(0));
  2544. SDValue Op2 = getValue(I.getOperand(1));
  2545. ISD::CondCode Condition = getFCmpCondCode(predicate);
  2546. auto *FPMO = dyn_cast<FPMathOperator>(&I);
  2547. if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
  2548. Condition = getFCmpCodeWithoutNaN(Condition);
  2549. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2550. I.getType());
  2551. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
  2552. }
  2553. // Check if the condition of the select has one use or two users that are both
  2554. // selects with the same condition.
  2555. static bool hasOnlySelectUsers(const Value *Cond) {
  2556. return llvm::all_of(Cond->users(), [](const Value *V) {
  2557. return isa<SelectInst>(V);
  2558. });
  2559. }
  2560. void SelectionDAGBuilder::visitSelect(const User &I) {
  2561. SmallVector<EVT, 4> ValueVTs;
  2562. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
  2563. ValueVTs);
  2564. unsigned NumValues = ValueVTs.size();
  2565. if (NumValues == 0) return;
  2566. SmallVector<SDValue, 4> Values(NumValues);
  2567. SDValue Cond = getValue(I.getOperand(0));
  2568. SDValue LHSVal = getValue(I.getOperand(1));
  2569. SDValue RHSVal = getValue(I.getOperand(2));
  2570. auto BaseOps = {Cond};
  2571. ISD::NodeType OpCode = Cond.getValueType().isVector() ?
  2572. ISD::VSELECT : ISD::SELECT;
  2573. // Min/max matching is only viable if all output VTs are the same.
  2574. if (is_splat(ValueVTs)) {
  2575. EVT VT = ValueVTs[0];
  2576. LLVMContext &Ctx = *DAG.getContext();
  2577. auto &TLI = DAG.getTargetLoweringInfo();
  2578. // We care about the legality of the operation after it has been type
  2579. // legalized.
  2580. while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
  2581. VT != TLI.getTypeToTransformTo(Ctx, VT))
  2582. VT = TLI.getTypeToTransformTo(Ctx, VT);
  2583. // If the vselect is legal, assume we want to leave this as a vector setcc +
  2584. // vselect. Otherwise, if this is going to be scalarized, we want to see if
  2585. // min/max is legal on the scalar type.
  2586. bool UseScalarMinMax = VT.isVector() &&
  2587. !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
  2588. Value *LHS, *RHS;
  2589. auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
  2590. ISD::NodeType Opc = ISD::DELETED_NODE;
  2591. switch (SPR.Flavor) {
  2592. case SPF_UMAX: Opc = ISD::UMAX; break;
  2593. case SPF_UMIN: Opc = ISD::UMIN; break;
  2594. case SPF_SMAX: Opc = ISD::SMAX; break;
  2595. case SPF_SMIN: Opc = ISD::SMIN; break;
  2596. case SPF_FMINNUM:
  2597. switch (SPR.NaNBehavior) {
  2598. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2599. case SPNB_RETURNS_NAN: Opc = ISD::FMINNAN; break;
  2600. case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
  2601. case SPNB_RETURNS_ANY: {
  2602. if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
  2603. Opc = ISD::FMINNUM;
  2604. else if (TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT))
  2605. Opc = ISD::FMINNAN;
  2606. else if (UseScalarMinMax)
  2607. Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
  2608. ISD::FMINNUM : ISD::FMINNAN;
  2609. break;
  2610. }
  2611. }
  2612. break;
  2613. case SPF_FMAXNUM:
  2614. switch (SPR.NaNBehavior) {
  2615. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2616. case SPNB_RETURNS_NAN: Opc = ISD::FMAXNAN; break;
  2617. case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
  2618. case SPNB_RETURNS_ANY:
  2619. if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
  2620. Opc = ISD::FMAXNUM;
  2621. else if (TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT))
  2622. Opc = ISD::FMAXNAN;
  2623. else if (UseScalarMinMax)
  2624. Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
  2625. ISD::FMAXNUM : ISD::FMAXNAN;
  2626. break;
  2627. }
  2628. break;
  2629. default: break;
  2630. }
  2631. if (Opc != ISD::DELETED_NODE &&
  2632. (TLI.isOperationLegalOrCustom(Opc, VT) ||
  2633. (UseScalarMinMax &&
  2634. TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
  2635. // If the underlying comparison instruction is used by any other
  2636. // instruction, the consumed instructions won't be destroyed, so it is
  2637. // not profitable to convert to a min/max.
  2638. hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
  2639. OpCode = Opc;
  2640. LHSVal = getValue(LHS);
  2641. RHSVal = getValue(RHS);
  2642. BaseOps = {};
  2643. }
  2644. }
  2645. for (unsigned i = 0; i != NumValues; ++i) {
  2646. SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
  2647. Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
  2648. Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
  2649. Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
  2650. LHSVal.getNode()->getValueType(LHSVal.getResNo()+i),
  2651. Ops);
  2652. }
  2653. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2654. DAG.getVTList(ValueVTs), Values));
  2655. }
  2656. void SelectionDAGBuilder::visitTrunc(const User &I) {
  2657. // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
  2658. SDValue N = getValue(I.getOperand(0));
  2659. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2660. I.getType());
  2661. setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
  2662. }
  2663. void SelectionDAGBuilder::visitZExt(const User &I) {
  2664. // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2665. // ZExt also can't be a cast to bool for same reason. So, nothing much to do
  2666. SDValue N = getValue(I.getOperand(0));
  2667. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2668. I.getType());
  2669. setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
  2670. }
  2671. void SelectionDAGBuilder::visitSExt(const User &I) {
  2672. // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2673. // SExt also can't be a cast to bool for same reason. So, nothing much to do
  2674. SDValue N = getValue(I.getOperand(0));
  2675. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2676. I.getType());
  2677. setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
  2678. }
  2679. void SelectionDAGBuilder::visitFPTrunc(const User &I) {
  2680. // FPTrunc is never a no-op cast, no need to check
  2681. SDValue N = getValue(I.getOperand(0));
  2682. SDLoc dl = getCurSDLoc();
  2683. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2684. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  2685. setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
  2686. DAG.getTargetConstant(
  2687. 0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
  2688. }
  2689. void SelectionDAGBuilder::visitFPExt(const User &I) {
  2690. // FPExt is never a no-op cast, no need to check
  2691. SDValue N = getValue(I.getOperand(0));
  2692. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2693. I.getType());
  2694. setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
  2695. }
  2696. void SelectionDAGBuilder::visitFPToUI(const User &I) {
  2697. // FPToUI is never a no-op cast, no need to check
  2698. SDValue N = getValue(I.getOperand(0));
  2699. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2700. I.getType());
  2701. setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
  2702. }
  2703. void SelectionDAGBuilder::visitFPToSI(const User &I) {
  2704. // FPToSI is never a no-op cast, no need to check
  2705. SDValue N = getValue(I.getOperand(0));
  2706. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2707. I.getType());
  2708. setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
  2709. }
  2710. void SelectionDAGBuilder::visitUIToFP(const User &I) {
  2711. // UIToFP is never a no-op cast, no need to check
  2712. SDValue N = getValue(I.getOperand(0));
  2713. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2714. I.getType());
  2715. setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
  2716. }
  2717. void SelectionDAGBuilder::visitSIToFP(const User &I) {
  2718. // SIToFP is never a no-op cast, no need to check
  2719. SDValue N = getValue(I.getOperand(0));
  2720. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2721. I.getType());
  2722. setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
  2723. }
  2724. void SelectionDAGBuilder::visitPtrToInt(const User &I) {
  2725. // What to do depends on the size of the integer and the size of the pointer.
  2726. // We can either truncate, zero extend, or no-op, accordingly.
  2727. SDValue N = getValue(I.getOperand(0));
  2728. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2729. I.getType());
  2730. setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
  2731. }
  2732. void SelectionDAGBuilder::visitIntToPtr(const User &I) {
  2733. // What to do depends on the size of the integer and the size of the pointer.
  2734. // We can either truncate, zero extend, or no-op, accordingly.
  2735. SDValue N = getValue(I.getOperand(0));
  2736. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2737. I.getType());
  2738. setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
  2739. }
  2740. void SelectionDAGBuilder::visitBitCast(const User &I) {
  2741. SDValue N = getValue(I.getOperand(0));
  2742. SDLoc dl = getCurSDLoc();
  2743. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2744. I.getType());
  2745. // BitCast assures us that source and destination are the same size so this is
  2746. // either a BITCAST or a no-op.
  2747. if (DestVT != N.getValueType())
  2748. setValue(&I, DAG.getNode(ISD::BITCAST, dl,
  2749. DestVT, N)); // convert types.
  2750. // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
  2751. // might fold any kind of constant expression to an integer constant and that
  2752. // is not what we are looking for. Only recognize a bitcast of a genuine
  2753. // constant integer as an opaque constant.
  2754. else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
  2755. setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
  2756. /*isOpaque*/true));
  2757. else
  2758. setValue(&I, N); // noop cast.
  2759. }
  2760. void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
  2761. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2762. const Value *SV = I.getOperand(0);
  2763. SDValue N = getValue(SV);
  2764. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  2765. unsigned SrcAS = SV->getType()->getPointerAddressSpace();
  2766. unsigned DestAS = I.getType()->getPointerAddressSpace();
  2767. if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
  2768. N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
  2769. setValue(&I, N);
  2770. }
  2771. void SelectionDAGBuilder::visitInsertElement(const User &I) {
  2772. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2773. SDValue InVec = getValue(I.getOperand(0));
  2774. SDValue InVal = getValue(I.getOperand(1));
  2775. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
  2776. TLI.getVectorIdxTy(DAG.getDataLayout()));
  2777. setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
  2778. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  2779. InVec, InVal, InIdx));
  2780. }
  2781. void SelectionDAGBuilder::visitExtractElement(const User &I) {
  2782. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2783. SDValue InVec = getValue(I.getOperand(0));
  2784. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
  2785. TLI.getVectorIdxTy(DAG.getDataLayout()));
  2786. setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
  2787. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  2788. InVec, InIdx));
  2789. }
  2790. void SelectionDAGBuilder::visitShuffleVector(const User &I) {
  2791. SDValue Src1 = getValue(I.getOperand(0));
  2792. SDValue Src2 = getValue(I.getOperand(1));
  2793. SDLoc DL = getCurSDLoc();
  2794. SmallVector<int, 8> Mask;
  2795. ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
  2796. unsigned MaskNumElts = Mask.size();
  2797. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2798. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  2799. EVT SrcVT = Src1.getValueType();
  2800. unsigned SrcNumElts = SrcVT.getVectorNumElements();
  2801. if (SrcNumElts == MaskNumElts) {
  2802. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
  2803. return;
  2804. }
  2805. // Normalize the shuffle vector since mask and vector length don't match.
  2806. if (SrcNumElts < MaskNumElts) {
  2807. // Mask is longer than the source vectors. We can use concatenate vector to
  2808. // make the mask and vectors lengths match.
  2809. if (MaskNumElts % SrcNumElts == 0) {
  2810. // Mask length is a multiple of the source vector length.
  2811. // Check if the shuffle is some kind of concatenation of the input
  2812. // vectors.
  2813. unsigned NumConcat = MaskNumElts / SrcNumElts;
  2814. bool IsConcat = true;
  2815. SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
  2816. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2817. int Idx = Mask[i];
  2818. if (Idx < 0)
  2819. continue;
  2820. // Ensure the indices in each SrcVT sized piece are sequential and that
  2821. // the same source is used for the whole piece.
  2822. if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
  2823. (ConcatSrcs[i / SrcNumElts] >= 0 &&
  2824. ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
  2825. IsConcat = false;
  2826. break;
  2827. }
  2828. // Remember which source this index came from.
  2829. ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
  2830. }
  2831. // The shuffle is concatenating multiple vectors together. Just emit
  2832. // a CONCAT_VECTORS operation.
  2833. if (IsConcat) {
  2834. SmallVector<SDValue, 8> ConcatOps;
  2835. for (auto Src : ConcatSrcs) {
  2836. if (Src < 0)
  2837. ConcatOps.push_back(DAG.getUNDEF(SrcVT));
  2838. else if (Src == 0)
  2839. ConcatOps.push_back(Src1);
  2840. else
  2841. ConcatOps.push_back(Src2);
  2842. }
  2843. setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
  2844. return;
  2845. }
  2846. }
  2847. unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
  2848. unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
  2849. EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
  2850. PaddedMaskNumElts);
  2851. // Pad both vectors with undefs to make them the same length as the mask.
  2852. SDValue UndefVal = DAG.getUNDEF(SrcVT);
  2853. SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
  2854. SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
  2855. MOps1[0] = Src1;
  2856. MOps2[0] = Src2;
  2857. Src1 = Src1.isUndef()
  2858. ? DAG.getUNDEF(PaddedVT)
  2859. : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
  2860. Src2 = Src2.isUndef()
  2861. ? DAG.getUNDEF(PaddedVT)
  2862. : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
  2863. // Readjust mask for new input vector length.
  2864. SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
  2865. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2866. int Idx = Mask[i];
  2867. if (Idx >= (int)SrcNumElts)
  2868. Idx -= SrcNumElts - PaddedMaskNumElts;
  2869. MappedOps[i] = Idx;
  2870. }
  2871. SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
  2872. // If the concatenated vector was padded, extract a subvector with the
  2873. // correct number of elements.
  2874. if (MaskNumElts != PaddedMaskNumElts)
  2875. Result = DAG.getNode(
  2876. ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
  2877. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  2878. setValue(&I, Result);
  2879. return;
  2880. }
  2881. if (SrcNumElts > MaskNumElts) {
  2882. // Analyze the access pattern of the vector to see if we can extract
  2883. // two subvectors and do the shuffle.
  2884. int StartIdx[2] = { -1, -1 }; // StartIdx to extract from
  2885. bool CanExtract = true;
  2886. for (int Idx : Mask) {
  2887. unsigned Input = 0;
  2888. if (Idx < 0)
  2889. continue;
  2890. if (Idx >= (int)SrcNumElts) {
  2891. Input = 1;
  2892. Idx -= SrcNumElts;
  2893. }
  2894. // If all the indices come from the same MaskNumElts sized portion of
  2895. // the sources we can use extract. Also make sure the extract wouldn't
  2896. // extract past the end of the source.
  2897. int NewStartIdx = alignDown(Idx, MaskNumElts);
  2898. if (NewStartIdx + MaskNumElts > SrcNumElts ||
  2899. (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
  2900. CanExtract = false;
  2901. // Make sure we always update StartIdx as we use it to track if all
  2902. // elements are undef.
  2903. StartIdx[Input] = NewStartIdx;
  2904. }
  2905. if (StartIdx[0] < 0 && StartIdx[1] < 0) {
  2906. setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
  2907. return;
  2908. }
  2909. if (CanExtract) {
  2910. // Extract appropriate subvector and generate a vector shuffle
  2911. for (unsigned Input = 0; Input < 2; ++Input) {
  2912. SDValue &Src = Input == 0 ? Src1 : Src2;
  2913. if (StartIdx[Input] < 0)
  2914. Src = DAG.getUNDEF(VT);
  2915. else {
  2916. Src = DAG.getNode(
  2917. ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
  2918. DAG.getConstant(StartIdx[Input], DL,
  2919. TLI.getVectorIdxTy(DAG.getDataLayout())));
  2920. }
  2921. }
  2922. // Calculate new mask.
  2923. SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
  2924. for (int &Idx : MappedOps) {
  2925. if (Idx >= (int)SrcNumElts)
  2926. Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
  2927. else if (Idx >= 0)
  2928. Idx -= StartIdx[0];
  2929. }
  2930. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
  2931. return;
  2932. }
  2933. }
  2934. // We can't use either concat vectors or extract subvectors so fall back to
  2935. // replacing the shuffle with extract and build vector.
  2936. // to insert and build vector.
  2937. EVT EltVT = VT.getVectorElementType();
  2938. EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
  2939. SmallVector<SDValue,8> Ops;
  2940. for (int Idx : Mask) {
  2941. SDValue Res;
  2942. if (Idx < 0) {
  2943. Res = DAG.getUNDEF(EltVT);
  2944. } else {
  2945. SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
  2946. if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
  2947. Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
  2948. EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
  2949. }
  2950. Ops.push_back(Res);
  2951. }
  2952. setValue(&I, DAG.getBuildVector(VT, DL, Ops));
  2953. }
  2954. void SelectionDAGBuilder::visitInsertValue(const User &I) {
  2955. ArrayRef<unsigned> Indices;
  2956. if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
  2957. Indices = IV->getIndices();
  2958. else
  2959. Indices = cast<ConstantExpr>(&I)->getIndices();
  2960. const Value *Op0 = I.getOperand(0);
  2961. const Value *Op1 = I.getOperand(1);
  2962. Type *AggTy = I.getType();
  2963. Type *ValTy = Op1->getType();
  2964. bool IntoUndef = isa<UndefValue>(Op0);
  2965. bool FromUndef = isa<UndefValue>(Op1);
  2966. unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
  2967. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2968. SmallVector<EVT, 4> AggValueVTs;
  2969. ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
  2970. SmallVector<EVT, 4> ValValueVTs;
  2971. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  2972. unsigned NumAggValues = AggValueVTs.size();
  2973. unsigned NumValValues = ValValueVTs.size();
  2974. SmallVector<SDValue, 4> Values(NumAggValues);
  2975. // Ignore an insertvalue that produces an empty object
  2976. if (!NumAggValues) {
  2977. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  2978. return;
  2979. }
  2980. SDValue Agg = getValue(Op0);
  2981. unsigned i = 0;
  2982. // Copy the beginning value(s) from the original aggregate.
  2983. for (; i != LinearIndex; ++i)
  2984. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2985. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2986. // Copy values from the inserted value(s).
  2987. if (NumValValues) {
  2988. SDValue Val = getValue(Op1);
  2989. for (; i != LinearIndex + NumValValues; ++i)
  2990. Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2991. SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
  2992. }
  2993. // Copy remaining value(s) from the original aggregate.
  2994. for (; i != NumAggValues; ++i)
  2995. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2996. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2997. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2998. DAG.getVTList(AggValueVTs), Values));
  2999. }
  3000. void SelectionDAGBuilder::visitExtractValue(const User &I) {
  3001. ArrayRef<unsigned> Indices;
  3002. if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
  3003. Indices = EV->getIndices();
  3004. else
  3005. Indices = cast<ConstantExpr>(&I)->getIndices();
  3006. const Value *Op0 = I.getOperand(0);
  3007. Type *AggTy = Op0->getType();
  3008. Type *ValTy = I.getType();
  3009. bool OutOfUndef = isa<UndefValue>(Op0);
  3010. unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
  3011. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3012. SmallVector<EVT, 4> ValValueVTs;
  3013. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  3014. unsigned NumValValues = ValValueVTs.size();
  3015. // Ignore a extractvalue that produces an empty object
  3016. if (!NumValValues) {
  3017. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  3018. return;
  3019. }
  3020. SmallVector<SDValue, 4> Values(NumValValues);
  3021. SDValue Agg = getValue(Op0);
  3022. // Copy out the selected value(s).
  3023. for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
  3024. Values[i - LinearIndex] =
  3025. OutOfUndef ?
  3026. DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
  3027. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3028. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  3029. DAG.getVTList(ValValueVTs), Values));
  3030. }
  3031. void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
  3032. Value *Op0 = I.getOperand(0);
  3033. // Note that the pointer operand may be a vector of pointers. Take the scalar
  3034. // element which holds a pointer.
  3035. unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
  3036. SDValue N = getValue(Op0);
  3037. SDLoc dl = getCurSDLoc();
  3038. // Normalize Vector GEP - all scalar operands should be converted to the
  3039. // splat vector.
  3040. unsigned VectorWidth = I.getType()->isVectorTy() ?
  3041. cast<VectorType>(I.getType())->getVectorNumElements() : 0;
  3042. if (VectorWidth && !N.getValueType().isVector()) {
  3043. LLVMContext &Context = *DAG.getContext();
  3044. EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
  3045. N = DAG.getSplatBuildVector(VT, dl, N);
  3046. }
  3047. for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
  3048. GTI != E; ++GTI) {
  3049. const Value *Idx = GTI.getOperand();
  3050. if (StructType *StTy = GTI.getStructTypeOrNull()) {
  3051. unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
  3052. if (Field) {
  3053. // N = N + Offset
  3054. uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
  3055. // In an inbounds GEP with an offset that is nonnegative even when
  3056. // interpreted as signed, assume there is no unsigned overflow.
  3057. SDNodeFlags Flags;
  3058. if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
  3059. Flags.setNoUnsignedWrap(true);
  3060. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
  3061. DAG.getConstant(Offset, dl, N.getValueType()), Flags);
  3062. }
  3063. } else {
  3064. unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
  3065. MVT IdxTy = MVT::getIntegerVT(IdxSize);
  3066. APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
  3067. // If this is a scalar constant or a splat vector of constants,
  3068. // handle it quickly.
  3069. const auto *CI = dyn_cast<ConstantInt>(Idx);
  3070. if (!CI && isa<ConstantDataVector>(Idx) &&
  3071. cast<ConstantDataVector>(Idx)->getSplatValue())
  3072. CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
  3073. if (CI) {
  3074. if (CI->isZero())
  3075. continue;
  3076. APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
  3077. LLVMContext &Context = *DAG.getContext();
  3078. SDValue OffsVal = VectorWidth ?
  3079. DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
  3080. DAG.getConstant(Offs, dl, IdxTy);
  3081. // In an inbouds GEP with an offset that is nonnegative even when
  3082. // interpreted as signed, assume there is no unsigned overflow.
  3083. SDNodeFlags Flags;
  3084. if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
  3085. Flags.setNoUnsignedWrap(true);
  3086. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
  3087. continue;
  3088. }
  3089. // N = N + Idx * ElementSize;
  3090. SDValue IdxN = getValue(Idx);
  3091. if (!IdxN.getValueType().isVector() && VectorWidth) {
  3092. EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
  3093. IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
  3094. }
  3095. // If the index is smaller or larger than intptr_t, truncate or extend
  3096. // it.
  3097. IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
  3098. // If this is a multiply by a power of two, turn it into a shl
  3099. // immediately. This is a very common case.
  3100. if (ElementSize != 1) {
  3101. if (ElementSize.isPowerOf2()) {
  3102. unsigned Amt = ElementSize.logBase2();
  3103. IdxN = DAG.getNode(ISD::SHL, dl,
  3104. N.getValueType(), IdxN,
  3105. DAG.getConstant(Amt, dl, IdxN.getValueType()));
  3106. } else {
  3107. SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
  3108. IdxN = DAG.getNode(ISD::MUL, dl,
  3109. N.getValueType(), IdxN, Scale);
  3110. }
  3111. }
  3112. N = DAG.getNode(ISD::ADD, dl,
  3113. N.getValueType(), N, IdxN);
  3114. }
  3115. }
  3116. setValue(&I, N);
  3117. }
  3118. void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
  3119. // If this is a fixed sized alloca in the entry block of the function,
  3120. // allocate it statically on the stack.
  3121. if (FuncInfo.StaticAllocaMap.count(&I))
  3122. return; // getValue will auto-populate this.
  3123. SDLoc dl = getCurSDLoc();
  3124. Type *Ty = I.getAllocatedType();
  3125. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3126. auto &DL = DAG.getDataLayout();
  3127. uint64_t TySize = DL.getTypeAllocSize(Ty);
  3128. unsigned Align =
  3129. std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
  3130. SDValue AllocSize = getValue(I.getArraySize());
  3131. EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
  3132. if (AllocSize.getValueType() != IntPtr)
  3133. AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
  3134. AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
  3135. AllocSize,
  3136. DAG.getConstant(TySize, dl, IntPtr));
  3137. // Handle alignment. If the requested alignment is less than or equal to
  3138. // the stack alignment, ignore it. If the size is greater than or equal to
  3139. // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
  3140. unsigned StackAlign =
  3141. DAG.getSubtarget().getFrameLowering()->getStackAlignment();
  3142. if (Align <= StackAlign)
  3143. Align = 0;
  3144. // Round the size of the allocation up to the stack alignment size
  3145. // by add SA-1 to the size. This doesn't overflow because we're computing
  3146. // an address inside an alloca.
  3147. SDNodeFlags Flags;
  3148. Flags.setNoUnsignedWrap(true);
  3149. AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
  3150. DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
  3151. // Mask out the low bits for alignment purposes.
  3152. AllocSize =
  3153. DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
  3154. DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
  3155. SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
  3156. SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
  3157. SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
  3158. setValue(&I, DSA);
  3159. DAG.setRoot(DSA.getValue(1));
  3160. assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
  3161. }
  3162. void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
  3163. if (I.isAtomic())
  3164. return visitAtomicLoad(I);
  3165. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3166. const Value *SV = I.getOperand(0);
  3167. if (TLI.supportSwiftError()) {
  3168. // Swifterror values can come from either a function parameter with
  3169. // swifterror attribute or an alloca with swifterror attribute.
  3170. if (const Argument *Arg = dyn_cast<Argument>(SV)) {
  3171. if (Arg->hasSwiftErrorAttr())
  3172. return visitLoadFromSwiftError(I);
  3173. }
  3174. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
  3175. if (Alloca->isSwiftError())
  3176. return visitLoadFromSwiftError(I);
  3177. }
  3178. }
  3179. SDValue Ptr = getValue(SV);
  3180. Type *Ty = I.getType();
  3181. bool isVolatile = I.isVolatile();
  3182. bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
  3183. bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
  3184. bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout());
  3185. unsigned Alignment = I.getAlignment();
  3186. AAMDNodes AAInfo;
  3187. I.getAAMetadata(AAInfo);
  3188. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3189. SmallVector<EVT, 4> ValueVTs;
  3190. SmallVector<uint64_t, 4> Offsets;
  3191. ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets);
  3192. unsigned NumValues = ValueVTs.size();
  3193. if (NumValues == 0)
  3194. return;
  3195. SDValue Root;
  3196. bool ConstantMemory = false;
  3197. if (isVolatile || NumValues > MaxParallelChains)
  3198. // Serialize volatile loads with other side effects.
  3199. Root = getRoot();
  3200. else if (AA && AA->pointsToConstantMemory(MemoryLocation(
  3201. SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) {
  3202. // Do not serialize (non-volatile) loads of constant memory with anything.
  3203. Root = DAG.getEntryNode();
  3204. ConstantMemory = true;
  3205. } else {
  3206. // Do not serialize non-volatile loads against each other.
  3207. Root = DAG.getRoot();
  3208. }
  3209. SDLoc dl = getCurSDLoc();
  3210. if (isVolatile)
  3211. Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
  3212. // An aggregate load cannot wrap around the address space, so offsets to its
  3213. // parts don't wrap either.
  3214. SDNodeFlags Flags;
  3215. Flags.setNoUnsignedWrap(true);
  3216. SmallVector<SDValue, 4> Values(NumValues);
  3217. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3218. EVT PtrVT = Ptr.getValueType();
  3219. unsigned ChainI = 0;
  3220. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3221. // Serializing loads here may result in excessive register pressure, and
  3222. // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
  3223. // could recover a bit by hoisting nodes upward in the chain by recognizing
  3224. // they are side-effect free or do not alias. The optimizer should really
  3225. // avoid this case by converting large object/array copies to llvm.memcpy
  3226. // (MaxParallelChains should always remain as failsafe).
  3227. if (ChainI == MaxParallelChains) {
  3228. assert(PendingLoads.empty() && "PendingLoads must be serialized first");
  3229. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3230. makeArrayRef(Chains.data(), ChainI));
  3231. Root = Chain;
  3232. ChainI = 0;
  3233. }
  3234. SDValue A = DAG.getNode(ISD::ADD, dl,
  3235. PtrVT, Ptr,
  3236. DAG.getConstant(Offsets[i], dl, PtrVT),
  3237. Flags);
  3238. auto MMOFlags = MachineMemOperand::MONone;
  3239. if (isVolatile)
  3240. MMOFlags |= MachineMemOperand::MOVolatile;
  3241. if (isNonTemporal)
  3242. MMOFlags |= MachineMemOperand::MONonTemporal;
  3243. if (isInvariant)
  3244. MMOFlags |= MachineMemOperand::MOInvariant;
  3245. if (isDereferenceable)
  3246. MMOFlags |= MachineMemOperand::MODereferenceable;
  3247. MMOFlags |= TLI.getMMOFlags(I);
  3248. SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A,
  3249. MachinePointerInfo(SV, Offsets[i]), Alignment,
  3250. MMOFlags, AAInfo, Ranges);
  3251. Values[i] = L;
  3252. Chains[ChainI] = L.getValue(1);
  3253. }
  3254. if (!ConstantMemory) {
  3255. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3256. makeArrayRef(Chains.data(), ChainI));
  3257. if (isVolatile)
  3258. DAG.setRoot(Chain);
  3259. else
  3260. PendingLoads.push_back(Chain);
  3261. }
  3262. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
  3263. DAG.getVTList(ValueVTs), Values));
  3264. }
  3265. void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
  3266. assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
  3267. "call visitStoreToSwiftError when backend supports swifterror");
  3268. SmallVector<EVT, 4> ValueVTs;
  3269. SmallVector<uint64_t, 4> Offsets;
  3270. const Value *SrcV = I.getOperand(0);
  3271. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3272. SrcV->getType(), ValueVTs, &Offsets);
  3273. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3274. "expect a single EVT for swifterror");
  3275. SDValue Src = getValue(SrcV);
  3276. // Create a virtual register, then update the virtual register.
  3277. unsigned VReg; bool CreatedVReg;
  3278. std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I);
  3279. // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
  3280. // Chain can be getRoot or getControlRoot.
  3281. SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
  3282. SDValue(Src.getNode(), Src.getResNo()));
  3283. DAG.setRoot(CopyNode);
  3284. if (CreatedVReg)
  3285. FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg);
  3286. }
  3287. void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
  3288. assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
  3289. "call visitLoadFromSwiftError when backend supports swifterror");
  3290. assert(!I.isVolatile() &&
  3291. I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&
  3292. I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&
  3293. "Support volatile, non temporal, invariant for load_from_swift_error");
  3294. const Value *SV = I.getOperand(0);
  3295. Type *Ty = I.getType();
  3296. AAMDNodes AAInfo;
  3297. I.getAAMetadata(AAInfo);
  3298. assert((!AA || !AA->pointsToConstantMemory(MemoryLocation(
  3299. SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) &&
  3300. "load_from_swift_error should not be constant memory");
  3301. SmallVector<EVT, 4> ValueVTs;
  3302. SmallVector<uint64_t, 4> Offsets;
  3303. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
  3304. ValueVTs, &Offsets);
  3305. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3306. "expect a single EVT for swifterror");
  3307. // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
  3308. SDValue L = DAG.getCopyFromReg(
  3309. getRoot(), getCurSDLoc(),
  3310. FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first,
  3311. ValueVTs[0]);
  3312. setValue(&I, L);
  3313. }
  3314. void SelectionDAGBuilder::visitStore(const StoreInst &I) {
  3315. if (I.isAtomic())
  3316. return visitAtomicStore(I);
  3317. const Value *SrcV = I.getOperand(0);
  3318. const Value *PtrV = I.getOperand(1);
  3319. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3320. if (TLI.supportSwiftError()) {
  3321. // Swifterror values can come from either a function parameter with
  3322. // swifterror attribute or an alloca with swifterror attribute.
  3323. if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
  3324. if (Arg->hasSwiftErrorAttr())
  3325. return visitStoreToSwiftError(I);
  3326. }
  3327. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
  3328. if (Alloca->isSwiftError())
  3329. return visitStoreToSwiftError(I);
  3330. }
  3331. }
  3332. SmallVector<EVT, 4> ValueVTs;
  3333. SmallVector<uint64_t, 4> Offsets;
  3334. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3335. SrcV->getType(), ValueVTs, &Offsets);
  3336. unsigned NumValues = ValueVTs.size();
  3337. if (NumValues == 0)
  3338. return;
  3339. // Get the lowered operands. Note that we do this after
  3340. // checking if NumResults is zero, because with zero results
  3341. // the operands won't have values in the map.
  3342. SDValue Src = getValue(SrcV);
  3343. SDValue Ptr = getValue(PtrV);
  3344. SDValue Root = getRoot();
  3345. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3346. SDLoc dl = getCurSDLoc();
  3347. EVT PtrVT = Ptr.getValueType();
  3348. unsigned Alignment = I.getAlignment();
  3349. AAMDNodes AAInfo;
  3350. I.getAAMetadata(AAInfo);
  3351. auto MMOFlags = MachineMemOperand::MONone;
  3352. if (I.isVolatile())
  3353. MMOFlags |= MachineMemOperand::MOVolatile;
  3354. if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
  3355. MMOFlags |= MachineMemOperand::MONonTemporal;
  3356. MMOFlags |= TLI.getMMOFlags(I);
  3357. // An aggregate load cannot wrap around the address space, so offsets to its
  3358. // parts don't wrap either.
  3359. SDNodeFlags Flags;
  3360. Flags.setNoUnsignedWrap(true);
  3361. unsigned ChainI = 0;
  3362. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3363. // See visitLoad comments.
  3364. if (ChainI == MaxParallelChains) {
  3365. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3366. makeArrayRef(Chains.data(), ChainI));
  3367. Root = Chain;
  3368. ChainI = 0;
  3369. }
  3370. SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
  3371. DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
  3372. SDValue St = DAG.getStore(
  3373. Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add,
  3374. MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo);
  3375. Chains[ChainI] = St;
  3376. }
  3377. SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3378. makeArrayRef(Chains.data(), ChainI));
  3379. DAG.setRoot(StoreNode);
  3380. }
  3381. void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
  3382. bool IsCompressing) {
  3383. SDLoc sdl = getCurSDLoc();
  3384. auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3385. unsigned& Alignment) {
  3386. // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
  3387. Src0 = I.getArgOperand(0);
  3388. Ptr = I.getArgOperand(1);
  3389. Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
  3390. Mask = I.getArgOperand(3);
  3391. };
  3392. auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3393. unsigned& Alignment) {
  3394. // llvm.masked.compressstore.*(Src0, Ptr, Mask)
  3395. Src0 = I.getArgOperand(0);
  3396. Ptr = I.getArgOperand(1);
  3397. Mask = I.getArgOperand(2);
  3398. Alignment = 0;
  3399. };
  3400. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3401. unsigned Alignment;
  3402. if (IsCompressing)
  3403. getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3404. else
  3405. getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3406. SDValue Ptr = getValue(PtrOperand);
  3407. SDValue Src0 = getValue(Src0Operand);
  3408. SDValue Mask = getValue(MaskOperand);
  3409. EVT VT = Src0.getValueType();
  3410. if (!Alignment)
  3411. Alignment = DAG.getEVTAlignment(VT);
  3412. AAMDNodes AAInfo;
  3413. I.getAAMetadata(AAInfo);
  3414. MachineMemOperand *MMO =
  3415. DAG.getMachineFunction().
  3416. getMachineMemOperand(MachinePointerInfo(PtrOperand),
  3417. MachineMemOperand::MOStore, VT.getStoreSize(),
  3418. Alignment, AAInfo);
  3419. SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
  3420. MMO, false /* Truncating */,
  3421. IsCompressing);
  3422. DAG.setRoot(StoreNode);
  3423. setValue(&I, StoreNode);
  3424. }
  3425. // Get a uniform base for the Gather/Scatter intrinsic.
  3426. // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
  3427. // We try to represent it as a base pointer + vector of indices.
  3428. // Usually, the vector of pointers comes from a 'getelementptr' instruction.
  3429. // The first operand of the GEP may be a single pointer or a vector of pointers
  3430. // Example:
  3431. // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
  3432. // or
  3433. // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
  3434. // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
  3435. //
  3436. // When the first GEP operand is a single pointer - it is the uniform base we
  3437. // are looking for. If first operand of the GEP is a splat vector - we
  3438. // extract the splat value and use it as a uniform base.
  3439. // In all other cases the function returns 'false'.
  3440. static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index,
  3441. SDValue &Scale, SelectionDAGBuilder* SDB) {
  3442. SelectionDAG& DAG = SDB->DAG;
  3443. LLVMContext &Context = *DAG.getContext();
  3444. assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
  3445. const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
  3446. if (!GEP)
  3447. return false;
  3448. const Value *GEPPtr = GEP->getPointerOperand();
  3449. if (!GEPPtr->getType()->isVectorTy())
  3450. Ptr = GEPPtr;
  3451. else if (!(Ptr = getSplatValue(GEPPtr)))
  3452. return false;
  3453. unsigned FinalIndex = GEP->getNumOperands() - 1;
  3454. Value *IndexVal = GEP->getOperand(FinalIndex);
  3455. // Ensure all the other indices are 0.
  3456. for (unsigned i = 1; i < FinalIndex; ++i) {
  3457. auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i));
  3458. if (!C || !C->isZero())
  3459. return false;
  3460. }
  3461. // The operands of the GEP may be defined in another basic block.
  3462. // In this case we'll not find nodes for the operands.
  3463. if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
  3464. return false;
  3465. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3466. const DataLayout &DL = DAG.getDataLayout();
  3467. Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
  3468. SDB->getCurSDLoc(), TLI.getPointerTy(DL));
  3469. Base = SDB->getValue(Ptr);
  3470. Index = SDB->getValue(IndexVal);
  3471. if (!Index.getValueType().isVector()) {
  3472. unsigned GEPWidth = GEP->getType()->getVectorNumElements();
  3473. EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
  3474. Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
  3475. }
  3476. return true;
  3477. }
  3478. void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
  3479. SDLoc sdl = getCurSDLoc();
  3480. // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
  3481. const Value *Ptr = I.getArgOperand(1);
  3482. SDValue Src0 = getValue(I.getArgOperand(0));
  3483. SDValue Mask = getValue(I.getArgOperand(3));
  3484. EVT VT = Src0.getValueType();
  3485. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
  3486. if (!Alignment)
  3487. Alignment = DAG.getEVTAlignment(VT);
  3488. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3489. AAMDNodes AAInfo;
  3490. I.getAAMetadata(AAInfo);
  3491. SDValue Base;
  3492. SDValue Index;
  3493. SDValue Scale;
  3494. const Value *BasePtr = Ptr;
  3495. bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
  3496. const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
  3497. MachineMemOperand *MMO = DAG.getMachineFunction().
  3498. getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
  3499. MachineMemOperand::MOStore, VT.getStoreSize(),
  3500. Alignment, AAInfo);
  3501. if (!UniformBase) {
  3502. Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3503. Index = getValue(Ptr);
  3504. Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3505. }
  3506. SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
  3507. SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
  3508. Ops, MMO);
  3509. DAG.setRoot(Scatter);
  3510. setValue(&I, Scatter);
  3511. }
  3512. void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
  3513. SDLoc sdl = getCurSDLoc();
  3514. auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3515. unsigned& Alignment) {
  3516. // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
  3517. Ptr = I.getArgOperand(0);
  3518. Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  3519. Mask = I.getArgOperand(2);
  3520. Src0 = I.getArgOperand(3);
  3521. };
  3522. auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3523. unsigned& Alignment) {
  3524. // @llvm.masked.expandload.*(Ptr, Mask, Src0)
  3525. Ptr = I.getArgOperand(0);
  3526. Alignment = 0;
  3527. Mask = I.getArgOperand(1);
  3528. Src0 = I.getArgOperand(2);
  3529. };
  3530. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3531. unsigned Alignment;
  3532. if (IsExpanding)
  3533. getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3534. else
  3535. getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3536. SDValue Ptr = getValue(PtrOperand);
  3537. SDValue Src0 = getValue(Src0Operand);
  3538. SDValue Mask = getValue(MaskOperand);
  3539. EVT VT = Src0.getValueType();
  3540. if (!Alignment)
  3541. Alignment = DAG.getEVTAlignment(VT);
  3542. AAMDNodes AAInfo;
  3543. I.getAAMetadata(AAInfo);
  3544. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3545. // Do not serialize masked loads of constant memory with anything.
  3546. bool AddToChain = !AA || !AA->pointsToConstantMemory(MemoryLocation(
  3547. PtrOperand, DAG.getDataLayout().getTypeStoreSize(I.getType()), AAInfo));
  3548. SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
  3549. MachineMemOperand *MMO =
  3550. DAG.getMachineFunction().
  3551. getMachineMemOperand(MachinePointerInfo(PtrOperand),
  3552. MachineMemOperand::MOLoad, VT.getStoreSize(),
  3553. Alignment, AAInfo, Ranges);
  3554. SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
  3555. ISD::NON_EXTLOAD, IsExpanding);
  3556. if (AddToChain)
  3557. PendingLoads.push_back(Load.getValue(1));
  3558. setValue(&I, Load);
  3559. }
  3560. void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
  3561. SDLoc sdl = getCurSDLoc();
  3562. // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
  3563. const Value *Ptr = I.getArgOperand(0);
  3564. SDValue Src0 = getValue(I.getArgOperand(3));
  3565. SDValue Mask = getValue(I.getArgOperand(2));
  3566. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3567. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3568. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
  3569. if (!Alignment)
  3570. Alignment = DAG.getEVTAlignment(VT);
  3571. AAMDNodes AAInfo;
  3572. I.getAAMetadata(AAInfo);
  3573. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3574. SDValue Root = DAG.getRoot();
  3575. SDValue Base;
  3576. SDValue Index;
  3577. SDValue Scale;
  3578. const Value *BasePtr = Ptr;
  3579. bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
  3580. bool ConstantMemory = false;
  3581. if (UniformBase &&
  3582. AA && AA->pointsToConstantMemory(MemoryLocation(
  3583. BasePtr, DAG.getDataLayout().getTypeStoreSize(I.getType()),
  3584. AAInfo))) {
  3585. // Do not serialize (non-volatile) loads of constant memory with anything.
  3586. Root = DAG.getEntryNode();
  3587. ConstantMemory = true;
  3588. }
  3589. MachineMemOperand *MMO =
  3590. DAG.getMachineFunction().
  3591. getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
  3592. MachineMemOperand::MOLoad, VT.getStoreSize(),
  3593. Alignment, AAInfo, Ranges);
  3594. if (!UniformBase) {
  3595. Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3596. Index = getValue(Ptr);
  3597. Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3598. }
  3599. SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
  3600. SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
  3601. Ops, MMO);
  3602. SDValue OutChain = Gather.getValue(1);
  3603. if (!ConstantMemory)
  3604. PendingLoads.push_back(OutChain);
  3605. setValue(&I, Gather);
  3606. }
  3607. void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
  3608. SDLoc dl = getCurSDLoc();
  3609. AtomicOrdering SuccessOrder = I.getSuccessOrdering();
  3610. AtomicOrdering FailureOrder = I.getFailureOrdering();
  3611. SyncScope::ID SSID = I.getSyncScopeID();
  3612. SDValue InChain = getRoot();
  3613. MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
  3614. SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
  3615. SDValue L = DAG.getAtomicCmpSwap(
  3616. ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
  3617. getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
  3618. getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
  3619. /*Alignment=*/ 0, SuccessOrder, FailureOrder, SSID);
  3620. SDValue OutChain = L.getValue(2);
  3621. setValue(&I, L);
  3622. DAG.setRoot(OutChain);
  3623. }
  3624. void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
  3625. SDLoc dl = getCurSDLoc();
  3626. ISD::NodeType NT;
  3627. switch (I.getOperation()) {
  3628. default: llvm_unreachable("Unknown atomicrmw operation");
  3629. case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
  3630. case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
  3631. case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
  3632. case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
  3633. case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
  3634. case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
  3635. case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
  3636. case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
  3637. case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
  3638. case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
  3639. case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
  3640. }
  3641. AtomicOrdering Order = I.getOrdering();
  3642. SyncScope::ID SSID = I.getSyncScopeID();
  3643. SDValue InChain = getRoot();
  3644. SDValue L =
  3645. DAG.getAtomic(NT, dl,
  3646. getValue(I.getValOperand()).getSimpleValueType(),
  3647. InChain,
  3648. getValue(I.getPointerOperand()),
  3649. getValue(I.getValOperand()),
  3650. I.getPointerOperand(),
  3651. /* Alignment=*/ 0, Order, SSID);
  3652. SDValue OutChain = L.getValue(1);
  3653. setValue(&I, L);
  3654. DAG.setRoot(OutChain);
  3655. }
  3656. void SelectionDAGBuilder::visitFence(const FenceInst &I) {
  3657. SDLoc dl = getCurSDLoc();
  3658. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3659. SDValue Ops[3];
  3660. Ops[0] = getRoot();
  3661. Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
  3662. TLI.getFenceOperandTy(DAG.getDataLayout()));
  3663. Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
  3664. TLI.getFenceOperandTy(DAG.getDataLayout()));
  3665. DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
  3666. }
  3667. void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
  3668. SDLoc dl = getCurSDLoc();
  3669. AtomicOrdering Order = I.getOrdering();
  3670. SyncScope::ID SSID = I.getSyncScopeID();
  3671. SDValue InChain = getRoot();
  3672. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3673. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3674. if (!TLI.supportsUnalignedAtomics() &&
  3675. I.getAlignment() < VT.getStoreSize())
  3676. report_fatal_error("Cannot generate unaligned atomic load");
  3677. MachineMemOperand *MMO =
  3678. DAG.getMachineFunction().
  3679. getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
  3680. MachineMemOperand::MOVolatile |
  3681. MachineMemOperand::MOLoad,
  3682. VT.getStoreSize(),
  3683. I.getAlignment() ? I.getAlignment() :
  3684. DAG.getEVTAlignment(VT),
  3685. AAMDNodes(), nullptr, SSID, Order);
  3686. InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
  3687. SDValue L =
  3688. DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
  3689. getValue(I.getPointerOperand()), MMO);
  3690. SDValue OutChain = L.getValue(1);
  3691. setValue(&I, L);
  3692. DAG.setRoot(OutChain);
  3693. }
  3694. void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
  3695. SDLoc dl = getCurSDLoc();
  3696. AtomicOrdering Order = I.getOrdering();
  3697. SyncScope::ID SSID = I.getSyncScopeID();
  3698. SDValue InChain = getRoot();
  3699. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3700. EVT VT =
  3701. TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
  3702. if (I.getAlignment() < VT.getStoreSize())
  3703. report_fatal_error("Cannot generate unaligned atomic store");
  3704. SDValue OutChain =
  3705. DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
  3706. InChain,
  3707. getValue(I.getPointerOperand()),
  3708. getValue(I.getValueOperand()),
  3709. I.getPointerOperand(), I.getAlignment(),
  3710. Order, SSID);
  3711. DAG.setRoot(OutChain);
  3712. }
  3713. /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
  3714. /// node.
  3715. void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
  3716. unsigned Intrinsic) {
  3717. // Ignore the callsite's attributes. A specific call site may be marked with
  3718. // readnone, but the lowering code will expect the chain based on the
  3719. // definition.
  3720. const Function *F = I.getCalledFunction();
  3721. bool HasChain = !F->doesNotAccessMemory();
  3722. bool OnlyLoad = HasChain && F->onlyReadsMemory();
  3723. // Build the operand list.
  3724. SmallVector<SDValue, 8> Ops;
  3725. if (HasChain) { // If this intrinsic has side-effects, chainify it.
  3726. if (OnlyLoad) {
  3727. // We don't need to serialize loads against other loads.
  3728. Ops.push_back(DAG.getRoot());
  3729. } else {
  3730. Ops.push_back(getRoot());
  3731. }
  3732. }
  3733. // Info is set by getTgtMemInstrinsic
  3734. TargetLowering::IntrinsicInfo Info;
  3735. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3736. bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
  3737. DAG.getMachineFunction(),
  3738. Intrinsic);
  3739. // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
  3740. if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
  3741. Info.opc == ISD::INTRINSIC_W_CHAIN)
  3742. Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
  3743. TLI.getPointerTy(DAG.getDataLayout())));
  3744. // Add all operands of the call to the operand list.
  3745. for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
  3746. SDValue Op = getValue(I.getArgOperand(i));
  3747. Ops.push_back(Op);
  3748. }
  3749. SmallVector<EVT, 4> ValueVTs;
  3750. ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
  3751. if (HasChain)
  3752. ValueVTs.push_back(MVT::Other);
  3753. SDVTList VTs = DAG.getVTList(ValueVTs);
  3754. // Create the node.
  3755. SDValue Result;
  3756. if (IsTgtIntrinsic) {
  3757. // This is target intrinsic that touches memory
  3758. Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs,
  3759. Ops, Info.memVT,
  3760. MachinePointerInfo(Info.ptrVal, Info.offset), Info.align,
  3761. Info.flags, Info.size);
  3762. } else if (!HasChain) {
  3763. Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
  3764. } else if (!I.getType()->isVoidTy()) {
  3765. Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
  3766. } else {
  3767. Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
  3768. }
  3769. if (HasChain) {
  3770. SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
  3771. if (OnlyLoad)
  3772. PendingLoads.push_back(Chain);
  3773. else
  3774. DAG.setRoot(Chain);
  3775. }
  3776. if (!I.getType()->isVoidTy()) {
  3777. if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
  3778. EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
  3779. Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
  3780. } else
  3781. Result = lowerRangeToAssertZExt(DAG, I, Result);
  3782. setValue(&I, Result);
  3783. }
  3784. }
  3785. /// GetSignificand - Get the significand and build it into a floating-point
  3786. /// number with exponent of 1:
  3787. ///
  3788. /// Op = (Op & 0x007fffff) | 0x3f800000;
  3789. ///
  3790. /// where Op is the hexadecimal representation of floating point value.
  3791. static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
  3792. SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  3793. DAG.getConstant(0x007fffff, dl, MVT::i32));
  3794. SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
  3795. DAG.getConstant(0x3f800000, dl, MVT::i32));
  3796. return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
  3797. }
  3798. /// GetExponent - Get the exponent:
  3799. ///
  3800. /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
  3801. ///
  3802. /// where Op is the hexadecimal representation of floating point value.
  3803. static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
  3804. const TargetLowering &TLI, const SDLoc &dl) {
  3805. SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  3806. DAG.getConstant(0x7f800000, dl, MVT::i32));
  3807. SDValue t1 = DAG.getNode(
  3808. ISD::SRL, dl, MVT::i32, t0,
  3809. DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
  3810. SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
  3811. DAG.getConstant(127, dl, MVT::i32));
  3812. return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
  3813. }
  3814. /// getF32Constant - Get 32-bit floating point constant.
  3815. static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
  3816. const SDLoc &dl) {
  3817. return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
  3818. MVT::f32);
  3819. }
  3820. static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
  3821. SelectionDAG &DAG) {
  3822. // TODO: What fast-math-flags should be set on the floating-point nodes?
  3823. // IntegerPartOfX = ((int32_t)(t0);
  3824. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
  3825. // FractionalPartOfX = t0 - (float)IntegerPartOfX;
  3826. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  3827. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
  3828. // IntegerPartOfX <<= 23;
  3829. IntegerPartOfX = DAG.getNode(
  3830. ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  3831. DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
  3832. DAG.getDataLayout())));
  3833. SDValue TwoToFractionalPartOfX;
  3834. if (LimitFloatPrecision <= 6) {
  3835. // For floating-point precision of 6:
  3836. //
  3837. // TwoToFractionalPartOfX =
  3838. // 0.997535578f +
  3839. // (0.735607626f + 0.252464424f * x) * x;
  3840. //
  3841. // error 0.0144103317, which is 6 bits
  3842. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3843. getF32Constant(DAG, 0x3e814304, dl));
  3844. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3845. getF32Constant(DAG, 0x3f3c50c8, dl));
  3846. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3847. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3848. getF32Constant(DAG, 0x3f7f5e7e, dl));
  3849. } else if (LimitFloatPrecision <= 12) {
  3850. // For floating-point precision of 12:
  3851. //
  3852. // TwoToFractionalPartOfX =
  3853. // 0.999892986f +
  3854. // (0.696457318f +
  3855. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  3856. //
  3857. // error 0.000107046256, which is 13 to 14 bits
  3858. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3859. getF32Constant(DAG, 0x3da235e3, dl));
  3860. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3861. getF32Constant(DAG, 0x3e65b8f3, dl));
  3862. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3863. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3864. getF32Constant(DAG, 0x3f324b07, dl));
  3865. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3866. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3867. getF32Constant(DAG, 0x3f7ff8fd, dl));
  3868. } else { // LimitFloatPrecision <= 18
  3869. // For floating-point precision of 18:
  3870. //
  3871. // TwoToFractionalPartOfX =
  3872. // 0.999999982f +
  3873. // (0.693148872f +
  3874. // (0.240227044f +
  3875. // (0.554906021e-1f +
  3876. // (0.961591928e-2f +
  3877. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  3878. // error 2.47208000*10^(-7), which is better than 18 bits
  3879. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3880. getF32Constant(DAG, 0x3924b03e, dl));
  3881. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3882. getF32Constant(DAG, 0x3ab24b87, dl));
  3883. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3884. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3885. getF32Constant(DAG, 0x3c1d8c17, dl));
  3886. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3887. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3888. getF32Constant(DAG, 0x3d634a1d, dl));
  3889. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3890. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3891. getF32Constant(DAG, 0x3e75fe14, dl));
  3892. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3893. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  3894. getF32Constant(DAG, 0x3f317234, dl));
  3895. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  3896. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  3897. getF32Constant(DAG, 0x3f800000, dl));
  3898. }
  3899. // Add the exponent into the result in integer domain.
  3900. SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
  3901. return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
  3902. DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
  3903. }
  3904. /// expandExp - Lower an exp intrinsic. Handles the special sequences for
  3905. /// limited-precision mode.
  3906. static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  3907. const TargetLowering &TLI) {
  3908. if (Op.getValueType() == MVT::f32 &&
  3909. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3910. // Put the exponent in the right bit position for later addition to the
  3911. // final result:
  3912. //
  3913. // #define LOG2OFe 1.4426950f
  3914. // t0 = Op * LOG2OFe
  3915. // TODO: What fast-math-flags should be set here?
  3916. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
  3917. getF32Constant(DAG, 0x3fb8aa3b, dl));
  3918. return getLimitedPrecisionExp2(t0, dl, DAG);
  3919. }
  3920. // No special expansion.
  3921. return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
  3922. }
  3923. /// expandLog - Lower a log intrinsic. Handles the special sequences for
  3924. /// limited-precision mode.
  3925. static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  3926. const TargetLowering &TLI) {
  3927. // TODO: What fast-math-flags should be set on the floating-point nodes?
  3928. if (Op.getValueType() == MVT::f32 &&
  3929. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3930. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  3931. // Scale the exponent by log(2) [0.69314718f].
  3932. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  3933. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  3934. getF32Constant(DAG, 0x3f317218, dl));
  3935. // Get the significand and build it into a floating-point number with
  3936. // exponent of 1.
  3937. SDValue X = GetSignificand(DAG, Op1, dl);
  3938. SDValue LogOfMantissa;
  3939. if (LimitFloatPrecision <= 6) {
  3940. // For floating-point precision of 6:
  3941. //
  3942. // LogofMantissa =
  3943. // -1.1609546f +
  3944. // (1.4034025f - 0.23903021f * x) * x;
  3945. //
  3946. // error 0.0034276066, which is better than 8 bits
  3947. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3948. getF32Constant(DAG, 0xbe74c456, dl));
  3949. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3950. getF32Constant(DAG, 0x3fb3a2b1, dl));
  3951. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3952. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3953. getF32Constant(DAG, 0x3f949a29, dl));
  3954. } else if (LimitFloatPrecision <= 12) {
  3955. // For floating-point precision of 12:
  3956. //
  3957. // LogOfMantissa =
  3958. // -1.7417939f +
  3959. // (2.8212026f +
  3960. // (-1.4699568f +
  3961. // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
  3962. //
  3963. // error 0.000061011436, which is 14 bits
  3964. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3965. getF32Constant(DAG, 0xbd67b6d6, dl));
  3966. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3967. getF32Constant(DAG, 0x3ee4f4b8, dl));
  3968. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3969. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3970. getF32Constant(DAG, 0x3fbc278b, dl));
  3971. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3972. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3973. getF32Constant(DAG, 0x40348e95, dl));
  3974. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3975. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3976. getF32Constant(DAG, 0x3fdef31a, dl));
  3977. } else { // LimitFloatPrecision <= 18
  3978. // For floating-point precision of 18:
  3979. //
  3980. // LogOfMantissa =
  3981. // -2.1072184f +
  3982. // (4.2372794f +
  3983. // (-3.7029485f +
  3984. // (2.2781945f +
  3985. // (-0.87823314f +
  3986. // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
  3987. //
  3988. // error 0.0000023660568, which is better than 18 bits
  3989. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3990. getF32Constant(DAG, 0xbc91e5ac, dl));
  3991. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3992. getF32Constant(DAG, 0x3e4350aa, dl));
  3993. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3994. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3995. getF32Constant(DAG, 0x3f60d3e3, dl));
  3996. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3997. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3998. getF32Constant(DAG, 0x4011cdf0, dl));
  3999. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4000. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4001. getF32Constant(DAG, 0x406cfd1c, dl));
  4002. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4003. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4004. getF32Constant(DAG, 0x408797cb, dl));
  4005. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4006. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  4007. getF32Constant(DAG, 0x4006dcab, dl));
  4008. }
  4009. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
  4010. }
  4011. // No special expansion.
  4012. return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
  4013. }
  4014. /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
  4015. /// limited-precision mode.
  4016. static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4017. const TargetLowering &TLI) {
  4018. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4019. if (Op.getValueType() == MVT::f32 &&
  4020. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4021. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4022. // Get the exponent.
  4023. SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
  4024. // Get the significand and build it into a floating-point number with
  4025. // exponent of 1.
  4026. SDValue X = GetSignificand(DAG, Op1, dl);
  4027. // Different possible minimax approximations of significand in
  4028. // floating-point for various degrees of accuracy over [1,2].
  4029. SDValue Log2ofMantissa;
  4030. if (LimitFloatPrecision <= 6) {
  4031. // For floating-point precision of 6:
  4032. //
  4033. // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
  4034. //
  4035. // error 0.0049451742, which is more than 7 bits
  4036. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4037. getF32Constant(DAG, 0xbeb08fe0, dl));
  4038. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4039. getF32Constant(DAG, 0x40019463, dl));
  4040. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4041. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4042. getF32Constant(DAG, 0x3fd6633d, dl));
  4043. } else if (LimitFloatPrecision <= 12) {
  4044. // For floating-point precision of 12:
  4045. //
  4046. // Log2ofMantissa =
  4047. // -2.51285454f +
  4048. // (4.07009056f +
  4049. // (-2.12067489f +
  4050. // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
  4051. //
  4052. // error 0.0000876136000, which is better than 13 bits
  4053. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4054. getF32Constant(DAG, 0xbda7262e, dl));
  4055. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4056. getF32Constant(DAG, 0x3f25280b, dl));
  4057. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4058. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4059. getF32Constant(DAG, 0x4007b923, dl));
  4060. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4061. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4062. getF32Constant(DAG, 0x40823e2f, dl));
  4063. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4064. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4065. getF32Constant(DAG, 0x4020d29c, dl));
  4066. } else { // LimitFloatPrecision <= 18
  4067. // For floating-point precision of 18:
  4068. //
  4069. // Log2ofMantissa =
  4070. // -3.0400495f +
  4071. // (6.1129976f +
  4072. // (-5.3420409f +
  4073. // (3.2865683f +
  4074. // (-1.2669343f +
  4075. // (0.27515199f -
  4076. // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
  4077. //
  4078. // error 0.0000018516, which is better than 18 bits
  4079. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4080. getF32Constant(DAG, 0xbcd2769e, dl));
  4081. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4082. getF32Constant(DAG, 0x3e8ce0b9, dl));
  4083. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4084. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4085. getF32Constant(DAG, 0x3fa22ae7, dl));
  4086. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4087. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4088. getF32Constant(DAG, 0x40525723, dl));
  4089. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4090. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4091. getF32Constant(DAG, 0x40aaf200, dl));
  4092. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4093. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4094. getF32Constant(DAG, 0x40c39dad, dl));
  4095. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4096. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  4097. getF32Constant(DAG, 0x4042902c, dl));
  4098. }
  4099. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
  4100. }
  4101. // No special expansion.
  4102. return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
  4103. }
  4104. /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
  4105. /// limited-precision mode.
  4106. static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4107. const TargetLowering &TLI) {
  4108. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4109. if (Op.getValueType() == MVT::f32 &&
  4110. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4111. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4112. // Scale the exponent by log10(2) [0.30102999f].
  4113. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  4114. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  4115. getF32Constant(DAG, 0x3e9a209a, dl));
  4116. // Get the significand and build it into a floating-point number with
  4117. // exponent of 1.
  4118. SDValue X = GetSignificand(DAG, Op1, dl);
  4119. SDValue Log10ofMantissa;
  4120. if (LimitFloatPrecision <= 6) {
  4121. // For floating-point precision of 6:
  4122. //
  4123. // Log10ofMantissa =
  4124. // -0.50419619f +
  4125. // (0.60948995f - 0.10380950f * x) * x;
  4126. //
  4127. // error 0.0014886165, which is 6 bits
  4128. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4129. getF32Constant(DAG, 0xbdd49a13, dl));
  4130. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4131. getF32Constant(DAG, 0x3f1c0789, dl));
  4132. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4133. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4134. getF32Constant(DAG, 0x3f011300, dl));
  4135. } else if (LimitFloatPrecision <= 12) {
  4136. // For floating-point precision of 12:
  4137. //
  4138. // Log10ofMantissa =
  4139. // -0.64831180f +
  4140. // (0.91751397f +
  4141. // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
  4142. //
  4143. // error 0.00019228036, which is better than 12 bits
  4144. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4145. getF32Constant(DAG, 0x3d431f31, dl));
  4146. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  4147. getF32Constant(DAG, 0x3ea21fb2, dl));
  4148. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4149. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4150. getF32Constant(DAG, 0x3f6ae232, dl));
  4151. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4152. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  4153. getF32Constant(DAG, 0x3f25f7c3, dl));
  4154. } else { // LimitFloatPrecision <= 18
  4155. // For floating-point precision of 18:
  4156. //
  4157. // Log10ofMantissa =
  4158. // -0.84299375f +
  4159. // (1.5327582f +
  4160. // (-1.0688956f +
  4161. // (0.49102474f +
  4162. // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
  4163. //
  4164. // error 0.0000037995730, which is better than 18 bits
  4165. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4166. getF32Constant(DAG, 0x3c5d51ce, dl));
  4167. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  4168. getF32Constant(DAG, 0x3e00685a, dl));
  4169. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4170. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4171. getF32Constant(DAG, 0x3efb6798, dl));
  4172. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4173. SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  4174. getF32Constant(DAG, 0x3f88d192, dl));
  4175. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4176. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4177. getF32Constant(DAG, 0x3fc4316c, dl));
  4178. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4179. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
  4180. getF32Constant(DAG, 0x3f57ce70, dl));
  4181. }
  4182. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
  4183. }
  4184. // No special expansion.
  4185. return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
  4186. }
  4187. /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
  4188. /// limited-precision mode.
  4189. static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4190. const TargetLowering &TLI) {
  4191. if (Op.getValueType() == MVT::f32 &&
  4192. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
  4193. return getLimitedPrecisionExp2(Op, dl, DAG);
  4194. // No special expansion.
  4195. return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
  4196. }
  4197. /// visitPow - Lower a pow intrinsic. Handles the special sequences for
  4198. /// limited-precision mode with x == 10.0f.
  4199. static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
  4200. SelectionDAG &DAG, const TargetLowering &TLI) {
  4201. bool IsExp10 = false;
  4202. if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
  4203. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4204. if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
  4205. APFloat Ten(10.0f);
  4206. IsExp10 = LHSC->isExactlyValue(Ten);
  4207. }
  4208. }
  4209. // TODO: What fast-math-flags should be set on the FMUL node?
  4210. if (IsExp10) {
  4211. // Put the exponent in the right bit position for later addition to the
  4212. // final result:
  4213. //
  4214. // #define LOG2OF10 3.3219281f
  4215. // t0 = Op * LOG2OF10;
  4216. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
  4217. getF32Constant(DAG, 0x40549a78, dl));
  4218. return getLimitedPrecisionExp2(t0, dl, DAG);
  4219. }
  4220. // No special expansion.
  4221. return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
  4222. }
  4223. /// ExpandPowI - Expand a llvm.powi intrinsic.
  4224. static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
  4225. SelectionDAG &DAG) {
  4226. // If RHS is a constant, we can expand this out to a multiplication tree,
  4227. // otherwise we end up lowering to a call to __powidf2 (for example). When
  4228. // optimizing for size, we only want to do this if the expansion would produce
  4229. // a small number of multiplies, otherwise we do the full expansion.
  4230. if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
  4231. // Get the exponent as a positive value.
  4232. unsigned Val = RHSC->getSExtValue();
  4233. if ((int)Val < 0) Val = -Val;
  4234. // powi(x, 0) -> 1.0
  4235. if (Val == 0)
  4236. return DAG.getConstantFP(1.0, DL, LHS.getValueType());
  4237. const Function &F = DAG.getMachineFunction().getFunction();
  4238. if (!F.optForSize() ||
  4239. // If optimizing for size, don't insert too many multiplies.
  4240. // This inserts up to 5 multiplies.
  4241. countPopulation(Val) + Log2_32(Val) < 7) {
  4242. // We use the simple binary decomposition method to generate the multiply
  4243. // sequence. There are more optimal ways to do this (for example,
  4244. // powi(x,15) generates one more multiply than it should), but this has
  4245. // the benefit of being both really simple and much better than a libcall.
  4246. SDValue Res; // Logically starts equal to 1.0
  4247. SDValue CurSquare = LHS;
  4248. // TODO: Intrinsics should have fast-math-flags that propagate to these
  4249. // nodes.
  4250. while (Val) {
  4251. if (Val & 1) {
  4252. if (Res.getNode())
  4253. Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
  4254. else
  4255. Res = CurSquare; // 1.0*CurSquare.
  4256. }
  4257. CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
  4258. CurSquare, CurSquare);
  4259. Val >>= 1;
  4260. }
  4261. // If the original was negative, invert the result, producing 1/(x*x*x).
  4262. if (RHSC->getSExtValue() < 0)
  4263. Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
  4264. DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
  4265. return Res;
  4266. }
  4267. }
  4268. // Otherwise, expand to a libcall.
  4269. return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
  4270. }
  4271. // getUnderlyingArgReg - Find underlying register used for a truncated or
  4272. // bitcasted argument.
  4273. static unsigned getUnderlyingArgReg(const SDValue &N) {
  4274. switch (N.getOpcode()) {
  4275. case ISD::CopyFromReg:
  4276. return cast<RegisterSDNode>(N.getOperand(1))->getReg();
  4277. case ISD::BITCAST:
  4278. case ISD::AssertZext:
  4279. case ISD::AssertSext:
  4280. case ISD::TRUNCATE:
  4281. return getUnderlyingArgReg(N.getOperand(0));
  4282. default:
  4283. return 0;
  4284. }
  4285. }
  4286. /// If the DbgValueInst is a dbg_value of a function argument, create the
  4287. /// corresponding DBG_VALUE machine instruction for it now. At the end of
  4288. /// instruction selection, they will be inserted to the entry BB.
  4289. bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
  4290. const Value *V, DILocalVariable *Variable, DIExpression *Expr,
  4291. DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
  4292. const Argument *Arg = dyn_cast<Argument>(V);
  4293. if (!Arg)
  4294. return false;
  4295. MachineFunction &MF = DAG.getMachineFunction();
  4296. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  4297. bool IsIndirect = false;
  4298. Optional<MachineOperand> Op;
  4299. // Some arguments' frame index is recorded during argument lowering.
  4300. int FI = FuncInfo.getArgumentFrameIndex(Arg);
  4301. if (FI != std::numeric_limits<int>::max())
  4302. Op = MachineOperand::CreateFI(FI);
  4303. if (!Op && N.getNode()) {
  4304. unsigned Reg = getUnderlyingArgReg(N);
  4305. if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
  4306. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  4307. unsigned PR = RegInfo.getLiveInPhysReg(Reg);
  4308. if (PR)
  4309. Reg = PR;
  4310. }
  4311. if (Reg) {
  4312. Op = MachineOperand::CreateReg(Reg, false);
  4313. IsIndirect = IsDbgDeclare;
  4314. }
  4315. }
  4316. if (!Op && N.getNode())
  4317. // Check if frame index is available.
  4318. if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
  4319. if (FrameIndexSDNode *FINode =
  4320. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  4321. Op = MachineOperand::CreateFI(FINode->getIndex());
  4322. if (!Op) {
  4323. // Check if ValueMap has reg number.
  4324. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  4325. if (VMI != FuncInfo.ValueMap.end()) {
  4326. const auto &TLI = DAG.getTargetLoweringInfo();
  4327. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
  4328. V->getType(), getABIRegCopyCC(V));
  4329. if (RFV.occupiesMultipleRegs()) {
  4330. unsigned Offset = 0;
  4331. for (auto RegAndSize : RFV.getRegsAndSizes()) {
  4332. Op = MachineOperand::CreateReg(RegAndSize.first, false);
  4333. auto FragmentExpr = DIExpression::createFragmentExpression(
  4334. Expr, Offset, RegAndSize.second);
  4335. if (!FragmentExpr)
  4336. continue;
  4337. FuncInfo.ArgDbgValues.push_back(
  4338. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
  4339. Op->getReg(), Variable, *FragmentExpr));
  4340. Offset += RegAndSize.second;
  4341. }
  4342. return true;
  4343. }
  4344. Op = MachineOperand::CreateReg(VMI->second, false);
  4345. IsIndirect = IsDbgDeclare;
  4346. }
  4347. }
  4348. if (!Op)
  4349. return false;
  4350. assert(Variable->isValidLocationForIntrinsic(DL) &&
  4351. "Expected inlined-at fields to agree");
  4352. IsIndirect = (Op->isReg()) ? IsIndirect : true;
  4353. FuncInfo.ArgDbgValues.push_back(
  4354. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
  4355. *Op, Variable, Expr));
  4356. return true;
  4357. }
  4358. /// Return the appropriate SDDbgValue based on N.
  4359. SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
  4360. DILocalVariable *Variable,
  4361. DIExpression *Expr,
  4362. const DebugLoc &dl,
  4363. unsigned DbgSDNodeOrder) {
  4364. if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
  4365. // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
  4366. // stack slot locations.
  4367. //
  4368. // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
  4369. // debug values here after optimization:
  4370. //
  4371. // dbg.value(i32* %px, !"int *px", !DIExpression()), and
  4372. // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
  4373. //
  4374. // Both describe the direct values of their associated variables.
  4375. return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
  4376. /*IsIndirect*/ false, dl, DbgSDNodeOrder);
  4377. }
  4378. return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
  4379. /*IsIndirect*/ false, dl, DbgSDNodeOrder);
  4380. }
  4381. // VisualStudio defines setjmp as _setjmp
  4382. #if defined(_MSC_VER) && defined(setjmp) && \
  4383. !defined(setjmp_undefined_for_msvc)
  4384. # pragma push_macro("setjmp")
  4385. # undef setjmp
  4386. # define setjmp_undefined_for_msvc
  4387. #endif
  4388. /// Lower the call to the specified intrinsic function. If we want to emit this
  4389. /// as a call to a named external function, return the name. Otherwise, lower it
  4390. /// and return null.
  4391. const char *
  4392. SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
  4393. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4394. SDLoc sdl = getCurSDLoc();
  4395. DebugLoc dl = getCurDebugLoc();
  4396. SDValue Res;
  4397. switch (Intrinsic) {
  4398. default:
  4399. // By default, turn this into a target intrinsic node.
  4400. visitTargetIntrinsic(I, Intrinsic);
  4401. return nullptr;
  4402. case Intrinsic::vastart: visitVAStart(I); return nullptr;
  4403. case Intrinsic::vaend: visitVAEnd(I); return nullptr;
  4404. case Intrinsic::vacopy: visitVACopy(I); return nullptr;
  4405. case Intrinsic::returnaddress:
  4406. setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
  4407. TLI.getPointerTy(DAG.getDataLayout()),
  4408. getValue(I.getArgOperand(0))));
  4409. return nullptr;
  4410. case Intrinsic::addressofreturnaddress:
  4411. setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
  4412. TLI.getPointerTy(DAG.getDataLayout())));
  4413. return nullptr;
  4414. case Intrinsic::frameaddress:
  4415. setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
  4416. TLI.getPointerTy(DAG.getDataLayout()),
  4417. getValue(I.getArgOperand(0))));
  4418. return nullptr;
  4419. case Intrinsic::read_register: {
  4420. Value *Reg = I.getArgOperand(0);
  4421. SDValue Chain = getRoot();
  4422. SDValue RegName =
  4423. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  4424. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4425. Res = DAG.getNode(ISD::READ_REGISTER, sdl,
  4426. DAG.getVTList(VT, MVT::Other), Chain, RegName);
  4427. setValue(&I, Res);
  4428. DAG.setRoot(Res.getValue(1));
  4429. return nullptr;
  4430. }
  4431. case Intrinsic::write_register: {
  4432. Value *Reg = I.getArgOperand(0);
  4433. Value *RegValue = I.getArgOperand(1);
  4434. SDValue Chain = getRoot();
  4435. SDValue RegName =
  4436. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  4437. DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
  4438. RegName, getValue(RegValue)));
  4439. return nullptr;
  4440. }
  4441. case Intrinsic::setjmp:
  4442. return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
  4443. case Intrinsic::longjmp:
  4444. return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
  4445. case Intrinsic::memcpy: {
  4446. const auto &MCI = cast<MemCpyInst>(I);
  4447. SDValue Op1 = getValue(I.getArgOperand(0));
  4448. SDValue Op2 = getValue(I.getArgOperand(1));
  4449. SDValue Op3 = getValue(I.getArgOperand(2));
  4450. // @llvm.memcpy defines 0 and 1 to both mean no alignment.
  4451. unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
  4452. unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
  4453. unsigned Align = MinAlign(DstAlign, SrcAlign);
  4454. bool isVol = MCI.isVolatile();
  4455. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4456. // FIXME: Support passing different dest/src alignments to the memcpy DAG
  4457. // node.
  4458. SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4459. false, isTC,
  4460. MachinePointerInfo(I.getArgOperand(0)),
  4461. MachinePointerInfo(I.getArgOperand(1)));
  4462. updateDAGForMaybeTailCall(MC);
  4463. return nullptr;
  4464. }
  4465. case Intrinsic::memset: {
  4466. const auto &MSI = cast<MemSetInst>(I);
  4467. SDValue Op1 = getValue(I.getArgOperand(0));
  4468. SDValue Op2 = getValue(I.getArgOperand(1));
  4469. SDValue Op3 = getValue(I.getArgOperand(2));
  4470. // @llvm.memset defines 0 and 1 to both mean no alignment.
  4471. unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
  4472. bool isVol = MSI.isVolatile();
  4473. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4474. SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4475. isTC, MachinePointerInfo(I.getArgOperand(0)));
  4476. updateDAGForMaybeTailCall(MS);
  4477. return nullptr;
  4478. }
  4479. case Intrinsic::memmove: {
  4480. const auto &MMI = cast<MemMoveInst>(I);
  4481. SDValue Op1 = getValue(I.getArgOperand(0));
  4482. SDValue Op2 = getValue(I.getArgOperand(1));
  4483. SDValue Op3 = getValue(I.getArgOperand(2));
  4484. // @llvm.memmove defines 0 and 1 to both mean no alignment.
  4485. unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
  4486. unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
  4487. unsigned Align = MinAlign(DstAlign, SrcAlign);
  4488. bool isVol = MMI.isVolatile();
  4489. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4490. // FIXME: Support passing different dest/src alignments to the memmove DAG
  4491. // node.
  4492. SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4493. isTC, MachinePointerInfo(I.getArgOperand(0)),
  4494. MachinePointerInfo(I.getArgOperand(1)));
  4495. updateDAGForMaybeTailCall(MM);
  4496. return nullptr;
  4497. }
  4498. case Intrinsic::memcpy_element_unordered_atomic: {
  4499. const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
  4500. SDValue Dst = getValue(MI.getRawDest());
  4501. SDValue Src = getValue(MI.getRawSource());
  4502. SDValue Length = getValue(MI.getLength());
  4503. unsigned DstAlign = MI.getDestAlignment();
  4504. unsigned SrcAlign = MI.getSourceAlignment();
  4505. Type *LengthTy = MI.getLength()->getType();
  4506. unsigned ElemSz = MI.getElementSizeInBytes();
  4507. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4508. SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
  4509. SrcAlign, Length, LengthTy, ElemSz, isTC,
  4510. MachinePointerInfo(MI.getRawDest()),
  4511. MachinePointerInfo(MI.getRawSource()));
  4512. updateDAGForMaybeTailCall(MC);
  4513. return nullptr;
  4514. }
  4515. case Intrinsic::memmove_element_unordered_atomic: {
  4516. auto &MI = cast<AtomicMemMoveInst>(I);
  4517. SDValue Dst = getValue(MI.getRawDest());
  4518. SDValue Src = getValue(MI.getRawSource());
  4519. SDValue Length = getValue(MI.getLength());
  4520. unsigned DstAlign = MI.getDestAlignment();
  4521. unsigned SrcAlign = MI.getSourceAlignment();
  4522. Type *LengthTy = MI.getLength()->getType();
  4523. unsigned ElemSz = MI.getElementSizeInBytes();
  4524. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4525. SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
  4526. SrcAlign, Length, LengthTy, ElemSz, isTC,
  4527. MachinePointerInfo(MI.getRawDest()),
  4528. MachinePointerInfo(MI.getRawSource()));
  4529. updateDAGForMaybeTailCall(MC);
  4530. return nullptr;
  4531. }
  4532. case Intrinsic::memset_element_unordered_atomic: {
  4533. auto &MI = cast<AtomicMemSetInst>(I);
  4534. SDValue Dst = getValue(MI.getRawDest());
  4535. SDValue Val = getValue(MI.getValue());
  4536. SDValue Length = getValue(MI.getLength());
  4537. unsigned DstAlign = MI.getDestAlignment();
  4538. Type *LengthTy = MI.getLength()->getType();
  4539. unsigned ElemSz = MI.getElementSizeInBytes();
  4540. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4541. SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
  4542. LengthTy, ElemSz, isTC,
  4543. MachinePointerInfo(MI.getRawDest()));
  4544. updateDAGForMaybeTailCall(MC);
  4545. return nullptr;
  4546. }
  4547. case Intrinsic::dbg_addr:
  4548. case Intrinsic::dbg_declare: {
  4549. const auto &DI = cast<DbgVariableIntrinsic>(I);
  4550. DILocalVariable *Variable = DI.getVariable();
  4551. DIExpression *Expression = DI.getExpression();
  4552. dropDanglingDebugInfo(Variable, Expression);
  4553. assert(Variable && "Missing variable");
  4554. // Check if address has undef value.
  4555. const Value *Address = DI.getVariableLocation();
  4556. if (!Address || isa<UndefValue>(Address) ||
  4557. (Address->use_empty() && !isa<Argument>(Address))) {
  4558. LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  4559. return nullptr;
  4560. }
  4561. bool isParameter = Variable->isParameter() || isa<Argument>(Address);
  4562. // Check if this variable can be described by a frame index, typically
  4563. // either as a static alloca or a byval parameter.
  4564. int FI = std::numeric_limits<int>::max();
  4565. if (const auto *AI =
  4566. dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
  4567. if (AI->isStaticAlloca()) {
  4568. auto I = FuncInfo.StaticAllocaMap.find(AI);
  4569. if (I != FuncInfo.StaticAllocaMap.end())
  4570. FI = I->second;
  4571. }
  4572. } else if (const auto *Arg = dyn_cast<Argument>(
  4573. Address->stripInBoundsConstantOffsets())) {
  4574. FI = FuncInfo.getArgumentFrameIndex(Arg);
  4575. }
  4576. // llvm.dbg.addr is control dependent and always generates indirect
  4577. // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
  4578. // the MachineFunction variable table.
  4579. if (FI != std::numeric_limits<int>::max()) {
  4580. if (Intrinsic == Intrinsic::dbg_addr) {
  4581. SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
  4582. Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
  4583. DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
  4584. }
  4585. return nullptr;
  4586. }
  4587. SDValue &N = NodeMap[Address];
  4588. if (!N.getNode() && isa<Argument>(Address))
  4589. // Check unused arguments map.
  4590. N = UnusedArgNodeMap[Address];
  4591. SDDbgValue *SDV;
  4592. if (N.getNode()) {
  4593. if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
  4594. Address = BCI->getOperand(0);
  4595. // Parameters are handled specially.
  4596. auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
  4597. if (isParameter && FINode) {
  4598. // Byval parameter. We have a frame index at this point.
  4599. SDV =
  4600. DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
  4601. /*IsIndirect*/ true, dl, SDNodeOrder);
  4602. } else if (isa<Argument>(Address)) {
  4603. // Address is an argument, so try to emit its dbg value using
  4604. // virtual register info from the FuncInfo.ValueMap.
  4605. EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
  4606. return nullptr;
  4607. } else {
  4608. SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
  4609. true, dl, SDNodeOrder);
  4610. }
  4611. DAG.AddDbgValue(SDV, N.getNode(), isParameter);
  4612. } else {
  4613. // If Address is an argument then try to emit its dbg value using
  4614. // virtual register info from the FuncInfo.ValueMap.
  4615. if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
  4616. N)) {
  4617. LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  4618. }
  4619. }
  4620. return nullptr;
  4621. }
  4622. case Intrinsic::dbg_label: {
  4623. const DbgLabelInst &DI = cast<DbgLabelInst>(I);
  4624. DILabel *Label = DI.getLabel();
  4625. assert(Label && "Missing label");
  4626. SDDbgLabel *SDV;
  4627. SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
  4628. DAG.AddDbgLabel(SDV);
  4629. return nullptr;
  4630. }
  4631. case Intrinsic::dbg_value: {
  4632. const DbgValueInst &DI = cast<DbgValueInst>(I);
  4633. assert(DI.getVariable() && "Missing variable");
  4634. DILocalVariable *Variable = DI.getVariable();
  4635. DIExpression *Expression = DI.getExpression();
  4636. dropDanglingDebugInfo(Variable, Expression);
  4637. const Value *V = DI.getValue();
  4638. if (!V)
  4639. return nullptr;
  4640. SDDbgValue *SDV;
  4641. if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
  4642. SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder);
  4643. DAG.AddDbgValue(SDV, nullptr, false);
  4644. return nullptr;
  4645. }
  4646. // Do not use getValue() in here; we don't want to generate code at
  4647. // this point if it hasn't been done yet.
  4648. SDValue N = NodeMap[V];
  4649. if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
  4650. N = UnusedArgNodeMap[V];
  4651. if (N.getNode()) {
  4652. if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N))
  4653. return nullptr;
  4654. SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder);
  4655. DAG.AddDbgValue(SDV, N.getNode(), false);
  4656. return nullptr;
  4657. }
  4658. // PHI nodes have already been selected, so we should know which VReg that
  4659. // is assigns to already.
  4660. if (isa<PHINode>(V)) {
  4661. auto VMI = FuncInfo.ValueMap.find(V);
  4662. if (VMI != FuncInfo.ValueMap.end()) {
  4663. unsigned Reg = VMI->second;
  4664. // The PHI node may be split up into several MI PHI nodes (in
  4665. // FunctionLoweringInfo::set).
  4666. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
  4667. V->getType(), None);
  4668. if (RFV.occupiesMultipleRegs()) {
  4669. unsigned Offset = 0;
  4670. unsigned BitsToDescribe = 0;
  4671. if (auto VarSize = Variable->getSizeInBits())
  4672. BitsToDescribe = *VarSize;
  4673. if (auto Fragment = Expression->getFragmentInfo())
  4674. BitsToDescribe = Fragment->SizeInBits;
  4675. for (auto RegAndSize : RFV.getRegsAndSizes()) {
  4676. unsigned RegisterSize = RegAndSize.second;
  4677. // Bail out if all bits are described already.
  4678. if (Offset >= BitsToDescribe)
  4679. break;
  4680. unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
  4681. ? BitsToDescribe - Offset
  4682. : RegisterSize;
  4683. auto FragmentExpr = DIExpression::createFragmentExpression(
  4684. Expression, Offset, FragmentSize);
  4685. if (!FragmentExpr)
  4686. continue;
  4687. SDV = DAG.getVRegDbgValue(Variable, *FragmentExpr, RegAndSize.first,
  4688. false, dl, SDNodeOrder);
  4689. DAG.AddDbgValue(SDV, nullptr, false);
  4690. Offset += RegisterSize;
  4691. }
  4692. } else {
  4693. SDV = DAG.getVRegDbgValue(Variable, Expression, Reg, false, dl,
  4694. SDNodeOrder);
  4695. DAG.AddDbgValue(SDV, nullptr, false);
  4696. }
  4697. return nullptr;
  4698. }
  4699. }
  4700. // TODO: When we get here we will either drop the dbg.value completely, or
  4701. // we try to move it forward by letting it dangle for awhile. So we should
  4702. // probably add an extra DbgValue to the DAG here, with a reference to
  4703. // "noreg", to indicate that we have lost the debug location for the
  4704. // variable.
  4705. if (!V->use_empty() ) {
  4706. // Do not call getValue(V) yet, as we don't want to generate code.
  4707. // Remember it for later.
  4708. DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
  4709. return nullptr;
  4710. }
  4711. LLVM_DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n");
  4712. LLVM_DEBUG(dbgs() << " Last seen at:\n " << *V << "\n");
  4713. return nullptr;
  4714. }
  4715. case Intrinsic::eh_typeid_for: {
  4716. // Find the type id for the given typeinfo.
  4717. GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
  4718. unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
  4719. Res = DAG.getConstant(TypeID, sdl, MVT::i32);
  4720. setValue(&I, Res);
  4721. return nullptr;
  4722. }
  4723. case Intrinsic::eh_return_i32:
  4724. case Intrinsic::eh_return_i64:
  4725. DAG.getMachineFunction().setCallsEHReturn(true);
  4726. DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
  4727. MVT::Other,
  4728. getControlRoot(),
  4729. getValue(I.getArgOperand(0)),
  4730. getValue(I.getArgOperand(1))));
  4731. return nullptr;
  4732. case Intrinsic::eh_unwind_init:
  4733. DAG.getMachineFunction().setCallsUnwindInit(true);
  4734. return nullptr;
  4735. case Intrinsic::eh_dwarf_cfa:
  4736. setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
  4737. TLI.getPointerTy(DAG.getDataLayout()),
  4738. getValue(I.getArgOperand(0))));
  4739. return nullptr;
  4740. case Intrinsic::eh_sjlj_callsite: {
  4741. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  4742. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
  4743. assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
  4744. assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
  4745. MMI.setCurrentCallSite(CI->getZExtValue());
  4746. return nullptr;
  4747. }
  4748. case Intrinsic::eh_sjlj_functioncontext: {
  4749. // Get and store the index of the function context.
  4750. MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
  4751. AllocaInst *FnCtx =
  4752. cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
  4753. int FI = FuncInfo.StaticAllocaMap[FnCtx];
  4754. MFI.setFunctionContextIndex(FI);
  4755. return nullptr;
  4756. }
  4757. case Intrinsic::eh_sjlj_setjmp: {
  4758. SDValue Ops[2];
  4759. Ops[0] = getRoot();
  4760. Ops[1] = getValue(I.getArgOperand(0));
  4761. SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
  4762. DAG.getVTList(MVT::i32, MVT::Other), Ops);
  4763. setValue(&I, Op.getValue(0));
  4764. DAG.setRoot(Op.getValue(1));
  4765. return nullptr;
  4766. }
  4767. case Intrinsic::eh_sjlj_longjmp:
  4768. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
  4769. getRoot(), getValue(I.getArgOperand(0))));
  4770. return nullptr;
  4771. case Intrinsic::eh_sjlj_setup_dispatch:
  4772. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
  4773. getRoot()));
  4774. return nullptr;
  4775. case Intrinsic::masked_gather:
  4776. visitMaskedGather(I);
  4777. return nullptr;
  4778. case Intrinsic::masked_load:
  4779. visitMaskedLoad(I);
  4780. return nullptr;
  4781. case Intrinsic::masked_scatter:
  4782. visitMaskedScatter(I);
  4783. return nullptr;
  4784. case Intrinsic::masked_store:
  4785. visitMaskedStore(I);
  4786. return nullptr;
  4787. case Intrinsic::masked_expandload:
  4788. visitMaskedLoad(I, true /* IsExpanding */);
  4789. return nullptr;
  4790. case Intrinsic::masked_compressstore:
  4791. visitMaskedStore(I, true /* IsCompressing */);
  4792. return nullptr;
  4793. case Intrinsic::x86_mmx_pslli_w:
  4794. case Intrinsic::x86_mmx_pslli_d:
  4795. case Intrinsic::x86_mmx_pslli_q:
  4796. case Intrinsic::x86_mmx_psrli_w:
  4797. case Intrinsic::x86_mmx_psrli_d:
  4798. case Intrinsic::x86_mmx_psrli_q:
  4799. case Intrinsic::x86_mmx_psrai_w:
  4800. case Intrinsic::x86_mmx_psrai_d: {
  4801. SDValue ShAmt = getValue(I.getArgOperand(1));
  4802. if (isa<ConstantSDNode>(ShAmt)) {
  4803. visitTargetIntrinsic(I, Intrinsic);
  4804. return nullptr;
  4805. }
  4806. unsigned NewIntrinsic = 0;
  4807. EVT ShAmtVT = MVT::v2i32;
  4808. switch (Intrinsic) {
  4809. case Intrinsic::x86_mmx_pslli_w:
  4810. NewIntrinsic = Intrinsic::x86_mmx_psll_w;
  4811. break;
  4812. case Intrinsic::x86_mmx_pslli_d:
  4813. NewIntrinsic = Intrinsic::x86_mmx_psll_d;
  4814. break;
  4815. case Intrinsic::x86_mmx_pslli_q:
  4816. NewIntrinsic = Intrinsic::x86_mmx_psll_q;
  4817. break;
  4818. case Intrinsic::x86_mmx_psrli_w:
  4819. NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
  4820. break;
  4821. case Intrinsic::x86_mmx_psrli_d:
  4822. NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
  4823. break;
  4824. case Intrinsic::x86_mmx_psrli_q:
  4825. NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
  4826. break;
  4827. case Intrinsic::x86_mmx_psrai_w:
  4828. NewIntrinsic = Intrinsic::x86_mmx_psra_w;
  4829. break;
  4830. case Intrinsic::x86_mmx_psrai_d:
  4831. NewIntrinsic = Intrinsic::x86_mmx_psra_d;
  4832. break;
  4833. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  4834. }
  4835. // The vector shift intrinsics with scalars uses 32b shift amounts but
  4836. // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
  4837. // to be zero.
  4838. // We must do this early because v2i32 is not a legal type.
  4839. SDValue ShOps[2];
  4840. ShOps[0] = ShAmt;
  4841. ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
  4842. ShAmt = DAG.getBuildVector(ShAmtVT, sdl, ShOps);
  4843. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4844. ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
  4845. Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
  4846. DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
  4847. getValue(I.getArgOperand(0)), ShAmt);
  4848. setValue(&I, Res);
  4849. return nullptr;
  4850. }
  4851. case Intrinsic::powi:
  4852. setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
  4853. getValue(I.getArgOperand(1)), DAG));
  4854. return nullptr;
  4855. case Intrinsic::log:
  4856. setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  4857. return nullptr;
  4858. case Intrinsic::log2:
  4859. setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  4860. return nullptr;
  4861. case Intrinsic::log10:
  4862. setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  4863. return nullptr;
  4864. case Intrinsic::exp:
  4865. setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  4866. return nullptr;
  4867. case Intrinsic::exp2:
  4868. setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  4869. return nullptr;
  4870. case Intrinsic::pow:
  4871. setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
  4872. getValue(I.getArgOperand(1)), DAG, TLI));
  4873. return nullptr;
  4874. case Intrinsic::sqrt:
  4875. case Intrinsic::fabs:
  4876. case Intrinsic::sin:
  4877. case Intrinsic::cos:
  4878. case Intrinsic::floor:
  4879. case Intrinsic::ceil:
  4880. case Intrinsic::trunc:
  4881. case Intrinsic::rint:
  4882. case Intrinsic::nearbyint:
  4883. case Intrinsic::round:
  4884. case Intrinsic::canonicalize: {
  4885. unsigned Opcode;
  4886. switch (Intrinsic) {
  4887. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  4888. case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
  4889. case Intrinsic::fabs: Opcode = ISD::FABS; break;
  4890. case Intrinsic::sin: Opcode = ISD::FSIN; break;
  4891. case Intrinsic::cos: Opcode = ISD::FCOS; break;
  4892. case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
  4893. case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
  4894. case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
  4895. case Intrinsic::rint: Opcode = ISD::FRINT; break;
  4896. case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
  4897. case Intrinsic::round: Opcode = ISD::FROUND; break;
  4898. case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
  4899. }
  4900. setValue(&I, DAG.getNode(Opcode, sdl,
  4901. getValue(I.getArgOperand(0)).getValueType(),
  4902. getValue(I.getArgOperand(0))));
  4903. return nullptr;
  4904. }
  4905. case Intrinsic::minnum: {
  4906. auto VT = getValue(I.getArgOperand(0)).getValueType();
  4907. unsigned Opc =
  4908. I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT)
  4909. ? ISD::FMINNAN
  4910. : ISD::FMINNUM;
  4911. setValue(&I, DAG.getNode(Opc, sdl, VT,
  4912. getValue(I.getArgOperand(0)),
  4913. getValue(I.getArgOperand(1))));
  4914. return nullptr;
  4915. }
  4916. case Intrinsic::maxnum: {
  4917. auto VT = getValue(I.getArgOperand(0)).getValueType();
  4918. unsigned Opc =
  4919. I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT)
  4920. ? ISD::FMAXNAN
  4921. : ISD::FMAXNUM;
  4922. setValue(&I, DAG.getNode(Opc, sdl, VT,
  4923. getValue(I.getArgOperand(0)),
  4924. getValue(I.getArgOperand(1))));
  4925. return nullptr;
  4926. }
  4927. case Intrinsic::minimum:
  4928. setValue(&I, DAG.getNode(ISD::FMINNAN, sdl,
  4929. getValue(I.getArgOperand(0)).getValueType(),
  4930. getValue(I.getArgOperand(0)),
  4931. getValue(I.getArgOperand(1))));
  4932. return nullptr;
  4933. case Intrinsic::maximum:
  4934. setValue(&I, DAG.getNode(ISD::FMAXNAN, sdl,
  4935. getValue(I.getArgOperand(0)).getValueType(),
  4936. getValue(I.getArgOperand(0)),
  4937. getValue(I.getArgOperand(1))));
  4938. return nullptr;
  4939. case Intrinsic::copysign:
  4940. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
  4941. getValue(I.getArgOperand(0)).getValueType(),
  4942. getValue(I.getArgOperand(0)),
  4943. getValue(I.getArgOperand(1))));
  4944. return nullptr;
  4945. case Intrinsic::fma:
  4946. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  4947. getValue(I.getArgOperand(0)).getValueType(),
  4948. getValue(I.getArgOperand(0)),
  4949. getValue(I.getArgOperand(1)),
  4950. getValue(I.getArgOperand(2))));
  4951. return nullptr;
  4952. case Intrinsic::experimental_constrained_fadd:
  4953. case Intrinsic::experimental_constrained_fsub:
  4954. case Intrinsic::experimental_constrained_fmul:
  4955. case Intrinsic::experimental_constrained_fdiv:
  4956. case Intrinsic::experimental_constrained_frem:
  4957. case Intrinsic::experimental_constrained_fma:
  4958. case Intrinsic::experimental_constrained_sqrt:
  4959. case Intrinsic::experimental_constrained_pow:
  4960. case Intrinsic::experimental_constrained_powi:
  4961. case Intrinsic::experimental_constrained_sin:
  4962. case Intrinsic::experimental_constrained_cos:
  4963. case Intrinsic::experimental_constrained_exp:
  4964. case Intrinsic::experimental_constrained_exp2:
  4965. case Intrinsic::experimental_constrained_log:
  4966. case Intrinsic::experimental_constrained_log10:
  4967. case Intrinsic::experimental_constrained_log2:
  4968. case Intrinsic::experimental_constrained_rint:
  4969. case Intrinsic::experimental_constrained_nearbyint:
  4970. visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
  4971. return nullptr;
  4972. case Intrinsic::fmuladd: {
  4973. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4974. if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
  4975. TLI.isFMAFasterThanFMulAndFAdd(VT)) {
  4976. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  4977. getValue(I.getArgOperand(0)).getValueType(),
  4978. getValue(I.getArgOperand(0)),
  4979. getValue(I.getArgOperand(1)),
  4980. getValue(I.getArgOperand(2))));
  4981. } else {
  4982. // TODO: Intrinsic calls should have fast-math-flags.
  4983. SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
  4984. getValue(I.getArgOperand(0)).getValueType(),
  4985. getValue(I.getArgOperand(0)),
  4986. getValue(I.getArgOperand(1)));
  4987. SDValue Add = DAG.getNode(ISD::FADD, sdl,
  4988. getValue(I.getArgOperand(0)).getValueType(),
  4989. Mul,
  4990. getValue(I.getArgOperand(2)));
  4991. setValue(&I, Add);
  4992. }
  4993. return nullptr;
  4994. }
  4995. case Intrinsic::convert_to_fp16:
  4996. setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
  4997. DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
  4998. getValue(I.getArgOperand(0)),
  4999. DAG.getTargetConstant(0, sdl,
  5000. MVT::i32))));
  5001. return nullptr;
  5002. case Intrinsic::convert_from_fp16:
  5003. setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
  5004. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  5005. DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
  5006. getValue(I.getArgOperand(0)))));
  5007. return nullptr;
  5008. case Intrinsic::pcmarker: {
  5009. SDValue Tmp = getValue(I.getArgOperand(0));
  5010. DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
  5011. return nullptr;
  5012. }
  5013. case Intrinsic::readcyclecounter: {
  5014. SDValue Op = getRoot();
  5015. Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
  5016. DAG.getVTList(MVT::i64, MVT::Other), Op);
  5017. setValue(&I, Res);
  5018. DAG.setRoot(Res.getValue(1));
  5019. return nullptr;
  5020. }
  5021. case Intrinsic::bitreverse:
  5022. setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
  5023. getValue(I.getArgOperand(0)).getValueType(),
  5024. getValue(I.getArgOperand(0))));
  5025. return nullptr;
  5026. case Intrinsic::bswap:
  5027. setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
  5028. getValue(I.getArgOperand(0)).getValueType(),
  5029. getValue(I.getArgOperand(0))));
  5030. return nullptr;
  5031. case Intrinsic::cttz: {
  5032. SDValue Arg = getValue(I.getArgOperand(0));
  5033. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  5034. EVT Ty = Arg.getValueType();
  5035. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
  5036. sdl, Ty, Arg));
  5037. return nullptr;
  5038. }
  5039. case Intrinsic::ctlz: {
  5040. SDValue Arg = getValue(I.getArgOperand(0));
  5041. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  5042. EVT Ty = Arg.getValueType();
  5043. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
  5044. sdl, Ty, Arg));
  5045. return nullptr;
  5046. }
  5047. case Intrinsic::ctpop: {
  5048. SDValue Arg = getValue(I.getArgOperand(0));
  5049. EVT Ty = Arg.getValueType();
  5050. setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
  5051. return nullptr;
  5052. }
  5053. case Intrinsic::fshl:
  5054. case Intrinsic::fshr: {
  5055. bool IsFSHL = Intrinsic == Intrinsic::fshl;
  5056. SDValue X = getValue(I.getArgOperand(0));
  5057. SDValue Y = getValue(I.getArgOperand(1));
  5058. SDValue Z = getValue(I.getArgOperand(2));
  5059. EVT VT = X.getValueType();
  5060. SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
  5061. SDValue Zero = DAG.getConstant(0, sdl, VT);
  5062. SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
  5063. // When X == Y, this is rotate. If the data type has a power-of-2 size, we
  5064. // avoid the select that is necessary in the general case to filter out
  5065. // the 0-shift possibility that leads to UB.
  5066. if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
  5067. // TODO: This should also be done if the operation is custom, but we have
  5068. // to make sure targets are handling the modulo shift amount as expected.
  5069. auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
  5070. if (TLI.isOperationLegal(RotateOpcode, VT)) {
  5071. setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
  5072. return nullptr;
  5073. }
  5074. // Some targets only rotate one way. Try the opposite direction.
  5075. RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
  5076. if (TLI.isOperationLegal(RotateOpcode, VT)) {
  5077. // Negate the shift amount because it is safe to ignore the high bits.
  5078. SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
  5079. setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
  5080. return nullptr;
  5081. }
  5082. // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
  5083. // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
  5084. SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
  5085. SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
  5086. SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
  5087. SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
  5088. setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
  5089. return nullptr;
  5090. }
  5091. // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
  5092. // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
  5093. SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
  5094. SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
  5095. SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
  5096. SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
  5097. // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
  5098. // and that is undefined. We must compare and select to avoid UB.
  5099. EVT CCVT = MVT::i1;
  5100. if (VT.isVector())
  5101. CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
  5102. // For fshl, 0-shift returns the 1st arg (X).
  5103. // For fshr, 0-shift returns the 2nd arg (Y).
  5104. SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
  5105. setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
  5106. return nullptr;
  5107. }
  5108. case Intrinsic::stacksave: {
  5109. SDValue Op = getRoot();
  5110. Res = DAG.getNode(
  5111. ISD::STACKSAVE, sdl,
  5112. DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
  5113. setValue(&I, Res);
  5114. DAG.setRoot(Res.getValue(1));
  5115. return nullptr;
  5116. }
  5117. case Intrinsic::stackrestore:
  5118. Res = getValue(I.getArgOperand(0));
  5119. DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
  5120. return nullptr;
  5121. case Intrinsic::get_dynamic_area_offset: {
  5122. SDValue Op = getRoot();
  5123. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5124. EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5125. // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
  5126. // target.
  5127. if (PtrTy != ResTy)
  5128. report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
  5129. " intrinsic!");
  5130. Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
  5131. Op);
  5132. DAG.setRoot(Op);
  5133. setValue(&I, Res);
  5134. return nullptr;
  5135. }
  5136. case Intrinsic::stackguard: {
  5137. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5138. MachineFunction &MF = DAG.getMachineFunction();
  5139. const Module &M = *MF.getFunction().getParent();
  5140. SDValue Chain = getRoot();
  5141. if (TLI.useLoadStackGuardNode()) {
  5142. Res = getLoadStackGuard(DAG, sdl, Chain);
  5143. } else {
  5144. const Value *Global = TLI.getSDagStackGuard(M);
  5145. unsigned Align = DL->getPrefTypeAlignment(Global->getType());
  5146. Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
  5147. MachinePointerInfo(Global, 0), Align,
  5148. MachineMemOperand::MOVolatile);
  5149. }
  5150. if (TLI.useStackGuardXorFP())
  5151. Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
  5152. DAG.setRoot(Chain);
  5153. setValue(&I, Res);
  5154. return nullptr;
  5155. }
  5156. case Intrinsic::stackprotector: {
  5157. // Emit code into the DAG to store the stack guard onto the stack.
  5158. MachineFunction &MF = DAG.getMachineFunction();
  5159. MachineFrameInfo &MFI = MF.getFrameInfo();
  5160. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5161. SDValue Src, Chain = getRoot();
  5162. if (TLI.useLoadStackGuardNode())
  5163. Src = getLoadStackGuard(DAG, sdl, Chain);
  5164. else
  5165. Src = getValue(I.getArgOperand(0)); // The guard's value.
  5166. AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
  5167. int FI = FuncInfo.StaticAllocaMap[Slot];
  5168. MFI.setStackProtectorIndex(FI);
  5169. SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
  5170. // Store the stack protector onto the stack.
  5171. Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
  5172. DAG.getMachineFunction(), FI),
  5173. /* Alignment = */ 0, MachineMemOperand::MOVolatile);
  5174. setValue(&I, Res);
  5175. DAG.setRoot(Res);
  5176. return nullptr;
  5177. }
  5178. case Intrinsic::objectsize: {
  5179. // If we don't know by now, we're never going to know.
  5180. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
  5181. assert(CI && "Non-constant type in __builtin_object_size?");
  5182. SDValue Arg = getValue(I.getCalledValue());
  5183. EVT Ty = Arg.getValueType();
  5184. if (CI->isZero())
  5185. Res = DAG.getConstant(-1ULL, sdl, Ty);
  5186. else
  5187. Res = DAG.getConstant(0, sdl, Ty);
  5188. setValue(&I, Res);
  5189. return nullptr;
  5190. }
  5191. case Intrinsic::annotation:
  5192. case Intrinsic::ptr_annotation:
  5193. case Intrinsic::launder_invariant_group:
  5194. case Intrinsic::strip_invariant_group:
  5195. // Drop the intrinsic, but forward the value
  5196. setValue(&I, getValue(I.getOperand(0)));
  5197. return nullptr;
  5198. case Intrinsic::assume:
  5199. case Intrinsic::var_annotation:
  5200. case Intrinsic::sideeffect:
  5201. // Discard annotate attributes, assumptions, and artificial side-effects.
  5202. return nullptr;
  5203. case Intrinsic::codeview_annotation: {
  5204. // Emit a label associated with this metadata.
  5205. MachineFunction &MF = DAG.getMachineFunction();
  5206. MCSymbol *Label =
  5207. MF.getMMI().getContext().createTempSymbol("annotation", true);
  5208. Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
  5209. MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
  5210. Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
  5211. DAG.setRoot(Res);
  5212. return nullptr;
  5213. }
  5214. case Intrinsic::init_trampoline: {
  5215. const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
  5216. SDValue Ops[6];
  5217. Ops[0] = getRoot();
  5218. Ops[1] = getValue(I.getArgOperand(0));
  5219. Ops[2] = getValue(I.getArgOperand(1));
  5220. Ops[3] = getValue(I.getArgOperand(2));
  5221. Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
  5222. Ops[5] = DAG.getSrcValue(F);
  5223. Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
  5224. DAG.setRoot(Res);
  5225. return nullptr;
  5226. }
  5227. case Intrinsic::adjust_trampoline:
  5228. setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
  5229. TLI.getPointerTy(DAG.getDataLayout()),
  5230. getValue(I.getArgOperand(0))));
  5231. return nullptr;
  5232. case Intrinsic::gcroot: {
  5233. assert(DAG.getMachineFunction().getFunction().hasGC() &&
  5234. "only valid in functions with gc specified, enforced by Verifier");
  5235. assert(GFI && "implied by previous");
  5236. const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
  5237. const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
  5238. FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
  5239. GFI->addStackRoot(FI->getIndex(), TypeMap);
  5240. return nullptr;
  5241. }
  5242. case Intrinsic::gcread:
  5243. case Intrinsic::gcwrite:
  5244. llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
  5245. case Intrinsic::flt_rounds:
  5246. setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
  5247. return nullptr;
  5248. case Intrinsic::expect:
  5249. // Just replace __builtin_expect(exp, c) with EXP.
  5250. setValue(&I, getValue(I.getArgOperand(0)));
  5251. return nullptr;
  5252. case Intrinsic::debugtrap:
  5253. case Intrinsic::trap: {
  5254. StringRef TrapFuncName =
  5255. I.getAttributes()
  5256. .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
  5257. .getValueAsString();
  5258. if (TrapFuncName.empty()) {
  5259. ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
  5260. ISD::TRAP : ISD::DEBUGTRAP;
  5261. DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
  5262. return nullptr;
  5263. }
  5264. TargetLowering::ArgListTy Args;
  5265. TargetLowering::CallLoweringInfo CLI(DAG);
  5266. CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
  5267. CallingConv::C, I.getType(),
  5268. DAG.getExternalSymbol(TrapFuncName.data(),
  5269. TLI.getPointerTy(DAG.getDataLayout())),
  5270. std::move(Args));
  5271. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  5272. DAG.setRoot(Result.second);
  5273. return nullptr;
  5274. }
  5275. case Intrinsic::uadd_with_overflow:
  5276. case Intrinsic::sadd_with_overflow:
  5277. case Intrinsic::usub_with_overflow:
  5278. case Intrinsic::ssub_with_overflow:
  5279. case Intrinsic::umul_with_overflow:
  5280. case Intrinsic::smul_with_overflow: {
  5281. ISD::NodeType Op;
  5282. switch (Intrinsic) {
  5283. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5284. case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
  5285. case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
  5286. case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
  5287. case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
  5288. case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
  5289. case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
  5290. }
  5291. SDValue Op1 = getValue(I.getArgOperand(0));
  5292. SDValue Op2 = getValue(I.getArgOperand(1));
  5293. SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
  5294. setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
  5295. return nullptr;
  5296. }
  5297. case Intrinsic::prefetch: {
  5298. SDValue Ops[5];
  5299. unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  5300. auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
  5301. Ops[0] = DAG.getRoot();
  5302. Ops[1] = getValue(I.getArgOperand(0));
  5303. Ops[2] = getValue(I.getArgOperand(1));
  5304. Ops[3] = getValue(I.getArgOperand(2));
  5305. Ops[4] = getValue(I.getArgOperand(3));
  5306. SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
  5307. DAG.getVTList(MVT::Other), Ops,
  5308. EVT::getIntegerVT(*Context, 8),
  5309. MachinePointerInfo(I.getArgOperand(0)),
  5310. 0, /* align */
  5311. Flags);
  5312. // Chain the prefetch in parallell with any pending loads, to stay out of
  5313. // the way of later optimizations.
  5314. PendingLoads.push_back(Result);
  5315. Result = getRoot();
  5316. DAG.setRoot(Result);
  5317. return nullptr;
  5318. }
  5319. case Intrinsic::lifetime_start:
  5320. case Intrinsic::lifetime_end: {
  5321. bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
  5322. // Stack coloring is not enabled in O0, discard region information.
  5323. if (TM.getOptLevel() == CodeGenOpt::None)
  5324. return nullptr;
  5325. SmallVector<Value *, 4> Allocas;
  5326. GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL);
  5327. for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
  5328. E = Allocas.end(); Object != E; ++Object) {
  5329. AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
  5330. // Could not find an Alloca.
  5331. if (!LifetimeObject)
  5332. continue;
  5333. // First check that the Alloca is static, otherwise it won't have a
  5334. // valid frame index.
  5335. auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
  5336. if (SI == FuncInfo.StaticAllocaMap.end())
  5337. return nullptr;
  5338. int FI = SI->second;
  5339. SDValue Ops[2];
  5340. Ops[0] = getRoot();
  5341. Ops[1] =
  5342. DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true);
  5343. unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
  5344. Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
  5345. DAG.setRoot(Res);
  5346. }
  5347. return nullptr;
  5348. }
  5349. case Intrinsic::invariant_start:
  5350. // Discard region information.
  5351. setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
  5352. return nullptr;
  5353. case Intrinsic::invariant_end:
  5354. // Discard region information.
  5355. return nullptr;
  5356. case Intrinsic::clear_cache:
  5357. return TLI.getClearCacheBuiltinName();
  5358. case Intrinsic::donothing:
  5359. // ignore
  5360. return nullptr;
  5361. case Intrinsic::experimental_stackmap:
  5362. visitStackmap(I);
  5363. return nullptr;
  5364. case Intrinsic::experimental_patchpoint_void:
  5365. case Intrinsic::experimental_patchpoint_i64:
  5366. visitPatchpoint(&I);
  5367. return nullptr;
  5368. case Intrinsic::experimental_gc_statepoint:
  5369. LowerStatepoint(ImmutableStatepoint(&I));
  5370. return nullptr;
  5371. case Intrinsic::experimental_gc_result:
  5372. visitGCResult(cast<GCResultInst>(I));
  5373. return nullptr;
  5374. case Intrinsic::experimental_gc_relocate:
  5375. visitGCRelocate(cast<GCRelocateInst>(I));
  5376. return nullptr;
  5377. case Intrinsic::instrprof_increment:
  5378. llvm_unreachable("instrprof failed to lower an increment");
  5379. case Intrinsic::instrprof_value_profile:
  5380. llvm_unreachable("instrprof failed to lower a value profiling call");
  5381. case Intrinsic::localescape: {
  5382. MachineFunction &MF = DAG.getMachineFunction();
  5383. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  5384. // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
  5385. // is the same on all targets.
  5386. for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
  5387. Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
  5388. if (isa<ConstantPointerNull>(Arg))
  5389. continue; // Skip null pointers. They represent a hole in index space.
  5390. AllocaInst *Slot = cast<AllocaInst>(Arg);
  5391. assert(FuncInfo.StaticAllocaMap.count(Slot) &&
  5392. "can only escape static allocas");
  5393. int FI = FuncInfo.StaticAllocaMap[Slot];
  5394. MCSymbol *FrameAllocSym =
  5395. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  5396. GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
  5397. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
  5398. TII->get(TargetOpcode::LOCAL_ESCAPE))
  5399. .addSym(FrameAllocSym)
  5400. .addFrameIndex(FI);
  5401. }
  5402. return nullptr;
  5403. }
  5404. case Intrinsic::localrecover: {
  5405. // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
  5406. MachineFunction &MF = DAG.getMachineFunction();
  5407. MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
  5408. // Get the symbol that defines the frame offset.
  5409. auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
  5410. auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
  5411. unsigned IdxVal =
  5412. unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
  5413. MCSymbol *FrameAllocSym =
  5414. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  5415. GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
  5416. // Create a MCSymbol for the label to avoid any target lowering
  5417. // that would make this PC relative.
  5418. SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
  5419. SDValue OffsetVal =
  5420. DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
  5421. // Add the offset to the FP.
  5422. Value *FP = I.getArgOperand(1);
  5423. SDValue FPVal = getValue(FP);
  5424. SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
  5425. setValue(&I, Add);
  5426. return nullptr;
  5427. }
  5428. case Intrinsic::eh_exceptionpointer:
  5429. case Intrinsic::eh_exceptioncode: {
  5430. // Get the exception pointer vreg, copy from it, and resize it to fit.
  5431. const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
  5432. MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
  5433. const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
  5434. unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
  5435. SDValue N =
  5436. DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
  5437. if (Intrinsic == Intrinsic::eh_exceptioncode)
  5438. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
  5439. setValue(&I, N);
  5440. return nullptr;
  5441. }
  5442. case Intrinsic::xray_customevent: {
  5443. // Here we want to make sure that the intrinsic behaves as if it has a
  5444. // specific calling convention, and only for x86_64.
  5445. // FIXME: Support other platforms later.
  5446. const auto &Triple = DAG.getTarget().getTargetTriple();
  5447. if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
  5448. return nullptr;
  5449. SDLoc DL = getCurSDLoc();
  5450. SmallVector<SDValue, 8> Ops;
  5451. // We want to say that we always want the arguments in registers.
  5452. SDValue LogEntryVal = getValue(I.getArgOperand(0));
  5453. SDValue StrSizeVal = getValue(I.getArgOperand(1));
  5454. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  5455. SDValue Chain = getRoot();
  5456. Ops.push_back(LogEntryVal);
  5457. Ops.push_back(StrSizeVal);
  5458. Ops.push_back(Chain);
  5459. // We need to enforce the calling convention for the callsite, so that
  5460. // argument ordering is enforced correctly, and that register allocation can
  5461. // see that some registers may be assumed clobbered and have to preserve
  5462. // them across calls to the intrinsic.
  5463. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
  5464. DL, NodeTys, Ops);
  5465. SDValue patchableNode = SDValue(MN, 0);
  5466. DAG.setRoot(patchableNode);
  5467. setValue(&I, patchableNode);
  5468. return nullptr;
  5469. }
  5470. case Intrinsic::xray_typedevent: {
  5471. // Here we want to make sure that the intrinsic behaves as if it has a
  5472. // specific calling convention, and only for x86_64.
  5473. // FIXME: Support other platforms later.
  5474. const auto &Triple = DAG.getTarget().getTargetTriple();
  5475. if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
  5476. return nullptr;
  5477. SDLoc DL = getCurSDLoc();
  5478. SmallVector<SDValue, 8> Ops;
  5479. // We want to say that we always want the arguments in registers.
  5480. // It's unclear to me how manipulating the selection DAG here forces callers
  5481. // to provide arguments in registers instead of on the stack.
  5482. SDValue LogTypeId = getValue(I.getArgOperand(0));
  5483. SDValue LogEntryVal = getValue(I.getArgOperand(1));
  5484. SDValue StrSizeVal = getValue(I.getArgOperand(2));
  5485. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  5486. SDValue Chain = getRoot();
  5487. Ops.push_back(LogTypeId);
  5488. Ops.push_back(LogEntryVal);
  5489. Ops.push_back(StrSizeVal);
  5490. Ops.push_back(Chain);
  5491. // We need to enforce the calling convention for the callsite, so that
  5492. // argument ordering is enforced correctly, and that register allocation can
  5493. // see that some registers may be assumed clobbered and have to preserve
  5494. // them across calls to the intrinsic.
  5495. MachineSDNode *MN = DAG.getMachineNode(
  5496. TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
  5497. SDValue patchableNode = SDValue(MN, 0);
  5498. DAG.setRoot(patchableNode);
  5499. setValue(&I, patchableNode);
  5500. return nullptr;
  5501. }
  5502. case Intrinsic::experimental_deoptimize:
  5503. LowerDeoptimizeCall(&I);
  5504. return nullptr;
  5505. case Intrinsic::experimental_vector_reduce_fadd:
  5506. case Intrinsic::experimental_vector_reduce_fmul:
  5507. case Intrinsic::experimental_vector_reduce_add:
  5508. case Intrinsic::experimental_vector_reduce_mul:
  5509. case Intrinsic::experimental_vector_reduce_and:
  5510. case Intrinsic::experimental_vector_reduce_or:
  5511. case Intrinsic::experimental_vector_reduce_xor:
  5512. case Intrinsic::experimental_vector_reduce_smax:
  5513. case Intrinsic::experimental_vector_reduce_smin:
  5514. case Intrinsic::experimental_vector_reduce_umax:
  5515. case Intrinsic::experimental_vector_reduce_umin:
  5516. case Intrinsic::experimental_vector_reduce_fmax:
  5517. case Intrinsic::experimental_vector_reduce_fmin:
  5518. visitVectorReduce(I, Intrinsic);
  5519. return nullptr;
  5520. case Intrinsic::icall_branch_funnel: {
  5521. SmallVector<SDValue, 16> Ops;
  5522. Ops.push_back(DAG.getRoot());
  5523. Ops.push_back(getValue(I.getArgOperand(0)));
  5524. int64_t Offset;
  5525. auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
  5526. I.getArgOperand(1), Offset, DAG.getDataLayout()));
  5527. if (!Base)
  5528. report_fatal_error(
  5529. "llvm.icall.branch.funnel operand must be a GlobalValue");
  5530. Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
  5531. struct BranchFunnelTarget {
  5532. int64_t Offset;
  5533. SDValue Target;
  5534. };
  5535. SmallVector<BranchFunnelTarget, 8> Targets;
  5536. for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
  5537. auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
  5538. I.getArgOperand(Op), Offset, DAG.getDataLayout()));
  5539. if (ElemBase != Base)
  5540. report_fatal_error("all llvm.icall.branch.funnel operands must refer "
  5541. "to the same GlobalValue");
  5542. SDValue Val = getValue(I.getArgOperand(Op + 1));
  5543. auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
  5544. if (!GA)
  5545. report_fatal_error(
  5546. "llvm.icall.branch.funnel operand must be a GlobalValue");
  5547. Targets.push_back({Offset, DAG.getTargetGlobalAddress(
  5548. GA->getGlobal(), getCurSDLoc(),
  5549. Val.getValueType(), GA->getOffset())});
  5550. }
  5551. llvm::sort(Targets,
  5552. [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
  5553. return T1.Offset < T2.Offset;
  5554. });
  5555. for (auto &T : Targets) {
  5556. Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
  5557. Ops.push_back(T.Target);
  5558. }
  5559. SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
  5560. getCurSDLoc(), MVT::Other, Ops),
  5561. 0);
  5562. DAG.setRoot(N);
  5563. setValue(&I, N);
  5564. HasTailCall = true;
  5565. return nullptr;
  5566. }
  5567. case Intrinsic::wasm_landingpad_index: {
  5568. // TODO store landing pad index in a map, which will be used when generating
  5569. // LSDA information
  5570. return nullptr;
  5571. }
  5572. }
  5573. }
  5574. void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
  5575. const ConstrainedFPIntrinsic &FPI) {
  5576. SDLoc sdl = getCurSDLoc();
  5577. unsigned Opcode;
  5578. switch (FPI.getIntrinsicID()) {
  5579. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5580. case Intrinsic::experimental_constrained_fadd:
  5581. Opcode = ISD::STRICT_FADD;
  5582. break;
  5583. case Intrinsic::experimental_constrained_fsub:
  5584. Opcode = ISD::STRICT_FSUB;
  5585. break;
  5586. case Intrinsic::experimental_constrained_fmul:
  5587. Opcode = ISD::STRICT_FMUL;
  5588. break;
  5589. case Intrinsic::experimental_constrained_fdiv:
  5590. Opcode = ISD::STRICT_FDIV;
  5591. break;
  5592. case Intrinsic::experimental_constrained_frem:
  5593. Opcode = ISD::STRICT_FREM;
  5594. break;
  5595. case Intrinsic::experimental_constrained_fma:
  5596. Opcode = ISD::STRICT_FMA;
  5597. break;
  5598. case Intrinsic::experimental_constrained_sqrt:
  5599. Opcode = ISD::STRICT_FSQRT;
  5600. break;
  5601. case Intrinsic::experimental_constrained_pow:
  5602. Opcode = ISD::STRICT_FPOW;
  5603. break;
  5604. case Intrinsic::experimental_constrained_powi:
  5605. Opcode = ISD::STRICT_FPOWI;
  5606. break;
  5607. case Intrinsic::experimental_constrained_sin:
  5608. Opcode = ISD::STRICT_FSIN;
  5609. break;
  5610. case Intrinsic::experimental_constrained_cos:
  5611. Opcode = ISD::STRICT_FCOS;
  5612. break;
  5613. case Intrinsic::experimental_constrained_exp:
  5614. Opcode = ISD::STRICT_FEXP;
  5615. break;
  5616. case Intrinsic::experimental_constrained_exp2:
  5617. Opcode = ISD::STRICT_FEXP2;
  5618. break;
  5619. case Intrinsic::experimental_constrained_log:
  5620. Opcode = ISD::STRICT_FLOG;
  5621. break;
  5622. case Intrinsic::experimental_constrained_log10:
  5623. Opcode = ISD::STRICT_FLOG10;
  5624. break;
  5625. case Intrinsic::experimental_constrained_log2:
  5626. Opcode = ISD::STRICT_FLOG2;
  5627. break;
  5628. case Intrinsic::experimental_constrained_rint:
  5629. Opcode = ISD::STRICT_FRINT;
  5630. break;
  5631. case Intrinsic::experimental_constrained_nearbyint:
  5632. Opcode = ISD::STRICT_FNEARBYINT;
  5633. break;
  5634. }
  5635. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5636. SDValue Chain = getRoot();
  5637. SmallVector<EVT, 4> ValueVTs;
  5638. ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
  5639. ValueVTs.push_back(MVT::Other); // Out chain
  5640. SDVTList VTs = DAG.getVTList(ValueVTs);
  5641. SDValue Result;
  5642. if (FPI.isUnaryOp())
  5643. Result = DAG.getNode(Opcode, sdl, VTs,
  5644. { Chain, getValue(FPI.getArgOperand(0)) });
  5645. else if (FPI.isTernaryOp())
  5646. Result = DAG.getNode(Opcode, sdl, VTs,
  5647. { Chain, getValue(FPI.getArgOperand(0)),
  5648. getValue(FPI.getArgOperand(1)),
  5649. getValue(FPI.getArgOperand(2)) });
  5650. else
  5651. Result = DAG.getNode(Opcode, sdl, VTs,
  5652. { Chain, getValue(FPI.getArgOperand(0)),
  5653. getValue(FPI.getArgOperand(1)) });
  5654. assert(Result.getNode()->getNumValues() == 2);
  5655. SDValue OutChain = Result.getValue(1);
  5656. DAG.setRoot(OutChain);
  5657. SDValue FPResult = Result.getValue(0);
  5658. setValue(&FPI, FPResult);
  5659. }
  5660. std::pair<SDValue, SDValue>
  5661. SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
  5662. const BasicBlock *EHPadBB) {
  5663. MachineFunction &MF = DAG.getMachineFunction();
  5664. MachineModuleInfo &MMI = MF.getMMI();
  5665. MCSymbol *BeginLabel = nullptr;
  5666. if (EHPadBB) {
  5667. // Insert a label before the invoke call to mark the try range. This can be
  5668. // used to detect deletion of the invoke via the MachineModuleInfo.
  5669. BeginLabel = MMI.getContext().createTempSymbol();
  5670. // For SjLj, keep track of which landing pads go with which invokes
  5671. // so as to maintain the ordering of pads in the LSDA.
  5672. unsigned CallSiteIndex = MMI.getCurrentCallSite();
  5673. if (CallSiteIndex) {
  5674. MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
  5675. LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
  5676. // Now that the call site is handled, stop tracking it.
  5677. MMI.setCurrentCallSite(0);
  5678. }
  5679. // Both PendingLoads and PendingExports must be flushed here;
  5680. // this call might not return.
  5681. (void)getRoot();
  5682. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
  5683. CLI.setChain(getRoot());
  5684. }
  5685. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5686. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  5687. assert((CLI.IsTailCall || Result.second.getNode()) &&
  5688. "Non-null chain expected with non-tail call!");
  5689. assert((Result.second.getNode() || !Result.first.getNode()) &&
  5690. "Null value expected with tail call!");
  5691. if (!Result.second.getNode()) {
  5692. // As a special case, a null chain means that a tail call has been emitted
  5693. // and the DAG root is already updated.
  5694. HasTailCall = true;
  5695. // Since there's no actual continuation from this block, nothing can be
  5696. // relying on us setting vregs for them.
  5697. PendingExports.clear();
  5698. } else {
  5699. DAG.setRoot(Result.second);
  5700. }
  5701. if (EHPadBB) {
  5702. // Insert a label at the end of the invoke call to mark the try range. This
  5703. // can be used to detect deletion of the invoke via the MachineModuleInfo.
  5704. MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
  5705. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
  5706. // Inform MachineModuleInfo of range.
  5707. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  5708. // There is a platform (e.g. wasm) that uses funclet style IR but does not
  5709. // actually use outlined funclets and their LSDA info style.
  5710. if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
  5711. assert(CLI.CS);
  5712. WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
  5713. EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
  5714. BeginLabel, EndLabel);
  5715. } else {
  5716. MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
  5717. }
  5718. }
  5719. return Result;
  5720. }
  5721. void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
  5722. bool isTailCall,
  5723. const BasicBlock *EHPadBB) {
  5724. auto &DL = DAG.getDataLayout();
  5725. FunctionType *FTy = CS.getFunctionType();
  5726. Type *RetTy = CS.getType();
  5727. TargetLowering::ArgListTy Args;
  5728. Args.reserve(CS.arg_size());
  5729. const Value *SwiftErrorVal = nullptr;
  5730. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5731. // We can't tail call inside a function with a swifterror argument. Lowering
  5732. // does not support this yet. It would have to move into the swifterror
  5733. // register before the call.
  5734. auto *Caller = CS.getInstruction()->getParent()->getParent();
  5735. if (TLI.supportSwiftError() &&
  5736. Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
  5737. isTailCall = false;
  5738. for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
  5739. i != e; ++i) {
  5740. TargetLowering::ArgListEntry Entry;
  5741. const Value *V = *i;
  5742. // Skip empty types
  5743. if (V->getType()->isEmptyTy())
  5744. continue;
  5745. SDValue ArgNode = getValue(V);
  5746. Entry.Node = ArgNode; Entry.Ty = V->getType();
  5747. Entry.setAttributes(&CS, i - CS.arg_begin());
  5748. // Use swifterror virtual register as input to the call.
  5749. if (Entry.IsSwiftError && TLI.supportSwiftError()) {
  5750. SwiftErrorVal = V;
  5751. // We find the virtual register for the actual swifterror argument.
  5752. // Instead of using the Value, we use the virtual register instead.
  5753. Entry.Node = DAG.getRegister(FuncInfo
  5754. .getOrCreateSwiftErrorVRegUseAt(
  5755. CS.getInstruction(), FuncInfo.MBB, V)
  5756. .first,
  5757. EVT(TLI.getPointerTy(DL)));
  5758. }
  5759. Args.push_back(Entry);
  5760. // If we have an explicit sret argument that is an Instruction, (i.e., it
  5761. // might point to function-local memory), we can't meaningfully tail-call.
  5762. if (Entry.IsSRet && isa<Instruction>(V))
  5763. isTailCall = false;
  5764. }
  5765. // Check if target-independent constraints permit a tail call here.
  5766. // Target-dependent constraints are checked within TLI->LowerCallTo.
  5767. if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
  5768. isTailCall = false;
  5769. // Disable tail calls if there is an swifterror argument. Targets have not
  5770. // been updated to support tail calls.
  5771. if (TLI.supportSwiftError() && SwiftErrorVal)
  5772. isTailCall = false;
  5773. TargetLowering::CallLoweringInfo CLI(DAG);
  5774. CLI.setDebugLoc(getCurSDLoc())
  5775. .setChain(getRoot())
  5776. .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
  5777. .setTailCall(isTailCall)
  5778. .setConvergent(CS.isConvergent());
  5779. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  5780. if (Result.first.getNode()) {
  5781. const Instruction *Inst = CS.getInstruction();
  5782. Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
  5783. setValue(Inst, Result.first);
  5784. }
  5785. // The last element of CLI.InVals has the SDValue for swifterror return.
  5786. // Here we copy it to a virtual register and update SwiftErrorMap for
  5787. // book-keeping.
  5788. if (SwiftErrorVal && TLI.supportSwiftError()) {
  5789. // Get the last element of InVals.
  5790. SDValue Src = CLI.InVals.back();
  5791. unsigned VReg; bool CreatedVReg;
  5792. std::tie(VReg, CreatedVReg) =
  5793. FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction());
  5794. SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
  5795. // We update the virtual register for the actual swifterror argument.
  5796. if (CreatedVReg)
  5797. FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg);
  5798. DAG.setRoot(CopyNode);
  5799. }
  5800. }
  5801. static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
  5802. SelectionDAGBuilder &Builder) {
  5803. // Check to see if this load can be trivially constant folded, e.g. if the
  5804. // input is from a string literal.
  5805. if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
  5806. // Cast pointer to the type we really want to load.
  5807. Type *LoadTy =
  5808. Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
  5809. if (LoadVT.isVector())
  5810. LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
  5811. LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
  5812. PointerType::getUnqual(LoadTy));
  5813. if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
  5814. const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
  5815. return Builder.getValue(LoadCst);
  5816. }
  5817. // Otherwise, we have to emit the load. If the pointer is to unfoldable but
  5818. // still constant memory, the input chain can be the entry node.
  5819. SDValue Root;
  5820. bool ConstantMemory = false;
  5821. // Do not serialize (non-volatile) loads of constant memory with anything.
  5822. if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
  5823. Root = Builder.DAG.getEntryNode();
  5824. ConstantMemory = true;
  5825. } else {
  5826. // Do not serialize non-volatile loads against each other.
  5827. Root = Builder.DAG.getRoot();
  5828. }
  5829. SDValue Ptr = Builder.getValue(PtrVal);
  5830. SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
  5831. Ptr, MachinePointerInfo(PtrVal),
  5832. /* Alignment = */ 1);
  5833. if (!ConstantMemory)
  5834. Builder.PendingLoads.push_back(LoadVal.getValue(1));
  5835. return LoadVal;
  5836. }
  5837. /// Record the value for an instruction that produces an integer result,
  5838. /// converting the type where necessary.
  5839. void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
  5840. SDValue Value,
  5841. bool IsSigned) {
  5842. EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  5843. I.getType(), true);
  5844. if (IsSigned)
  5845. Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
  5846. else
  5847. Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
  5848. setValue(&I, Value);
  5849. }
  5850. /// See if we can lower a memcmp call into an optimized form. If so, return
  5851. /// true and lower it. Otherwise return false, and it will be lowered like a
  5852. /// normal call.
  5853. /// The caller already checked that \p I calls the appropriate LibFunc with a
  5854. /// correct prototype.
  5855. bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
  5856. const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
  5857. const Value *Size = I.getArgOperand(2);
  5858. const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
  5859. if (CSize && CSize->getZExtValue() == 0) {
  5860. EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  5861. I.getType(), true);
  5862. setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
  5863. return true;
  5864. }
  5865. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  5866. std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
  5867. DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
  5868. getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
  5869. if (Res.first.getNode()) {
  5870. processIntegerCallValue(I, Res.first, true);
  5871. PendingLoads.push_back(Res.second);
  5872. return true;
  5873. }
  5874. // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
  5875. // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
  5876. if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
  5877. return false;
  5878. // If the target has a fast compare for the given size, it will return a
  5879. // preferred load type for that size. Require that the load VT is legal and
  5880. // that the target supports unaligned loads of that type. Otherwise, return
  5881. // INVALID.
  5882. auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
  5883. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5884. MVT LVT = TLI.hasFastEqualityCompare(NumBits);
  5885. if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
  5886. // TODO: Handle 5 byte compare as 4-byte + 1 byte.
  5887. // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
  5888. // TODO: Check alignment of src and dest ptrs.
  5889. unsigned DstAS = LHS->getType()->getPointerAddressSpace();
  5890. unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
  5891. if (!TLI.isTypeLegal(LVT) ||
  5892. !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
  5893. !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
  5894. LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
  5895. }
  5896. return LVT;
  5897. };
  5898. // This turns into unaligned loads. We only do this if the target natively
  5899. // supports the MVT we'll be loading or if it is small enough (<= 4) that
  5900. // we'll only produce a small number of byte loads.
  5901. MVT LoadVT;
  5902. unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
  5903. switch (NumBitsToCompare) {
  5904. default:
  5905. return false;
  5906. case 16:
  5907. LoadVT = MVT::i16;
  5908. break;
  5909. case 32:
  5910. LoadVT = MVT::i32;
  5911. break;
  5912. case 64:
  5913. case 128:
  5914. case 256:
  5915. LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
  5916. break;
  5917. }
  5918. if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
  5919. return false;
  5920. SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
  5921. SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
  5922. // Bitcast to a wide integer type if the loads are vectors.
  5923. if (LoadVT.isVector()) {
  5924. EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
  5925. LoadL = DAG.getBitcast(CmpVT, LoadL);
  5926. LoadR = DAG.getBitcast(CmpVT, LoadR);
  5927. }
  5928. SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
  5929. processIntegerCallValue(I, Cmp, false);
  5930. return true;
  5931. }
  5932. /// See if we can lower a memchr call into an optimized form. If so, return
  5933. /// true and lower it. Otherwise return false, and it will be lowered like a
  5934. /// normal call.
  5935. /// The caller already checked that \p I calls the appropriate LibFunc with a
  5936. /// correct prototype.
  5937. bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
  5938. const Value *Src = I.getArgOperand(0);
  5939. const Value *Char = I.getArgOperand(1);
  5940. const Value *Length = I.getArgOperand(2);
  5941. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  5942. std::pair<SDValue, SDValue> Res =
  5943. TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
  5944. getValue(Src), getValue(Char), getValue(Length),
  5945. MachinePointerInfo(Src));
  5946. if (Res.first.getNode()) {
  5947. setValue(&I, Res.first);
  5948. PendingLoads.push_back(Res.second);
  5949. return true;
  5950. }
  5951. return false;
  5952. }
  5953. /// See if we can lower a mempcpy call into an optimized form. If so, return
  5954. /// true and lower it. Otherwise return false, and it will be lowered like a
  5955. /// normal call.
  5956. /// The caller already checked that \p I calls the appropriate LibFunc with a
  5957. /// correct prototype.
  5958. bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
  5959. SDValue Dst = getValue(I.getArgOperand(0));
  5960. SDValue Src = getValue(I.getArgOperand(1));
  5961. SDValue Size = getValue(I.getArgOperand(2));
  5962. unsigned DstAlign = DAG.InferPtrAlignment(Dst);
  5963. unsigned SrcAlign = DAG.InferPtrAlignment(Src);
  5964. unsigned Align = std::min(DstAlign, SrcAlign);
  5965. if (Align == 0) // Alignment of one or both could not be inferred.
  5966. Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
  5967. bool isVol = false;
  5968. SDLoc sdl = getCurSDLoc();
  5969. // In the mempcpy context we need to pass in a false value for isTailCall
  5970. // because the return pointer needs to be adjusted by the size of
  5971. // the copied memory.
  5972. SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
  5973. false, /*isTailCall=*/false,
  5974. MachinePointerInfo(I.getArgOperand(0)),
  5975. MachinePointerInfo(I.getArgOperand(1)));
  5976. assert(MC.getNode() != nullptr &&
  5977. "** memcpy should not be lowered as TailCall in mempcpy context **");
  5978. DAG.setRoot(MC);
  5979. // Check if Size needs to be truncated or extended.
  5980. Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
  5981. // Adjust return pointer to point just past the last dst byte.
  5982. SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
  5983. Dst, Size);
  5984. setValue(&I, DstPlusSize);
  5985. return true;
  5986. }
  5987. /// See if we can lower a strcpy call into an optimized form. If so, return
  5988. /// true and lower it, otherwise return false and it will be lowered like a
  5989. /// normal call.
  5990. /// The caller already checked that \p I calls the appropriate LibFunc with a
  5991. /// correct prototype.
  5992. bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
  5993. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  5994. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  5995. std::pair<SDValue, SDValue> Res =
  5996. TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
  5997. getValue(Arg0), getValue(Arg1),
  5998. MachinePointerInfo(Arg0),
  5999. MachinePointerInfo(Arg1), isStpcpy);
  6000. if (Res.first.getNode()) {
  6001. setValue(&I, Res.first);
  6002. DAG.setRoot(Res.second);
  6003. return true;
  6004. }
  6005. return false;
  6006. }
  6007. /// See if we can lower a strcmp call into an optimized form. If so, return
  6008. /// true and lower it, otherwise return false and it will be lowered like a
  6009. /// normal call.
  6010. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6011. /// correct prototype.
  6012. bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
  6013. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  6014. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6015. std::pair<SDValue, SDValue> Res =
  6016. TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
  6017. getValue(Arg0), getValue(Arg1),
  6018. MachinePointerInfo(Arg0),
  6019. MachinePointerInfo(Arg1));
  6020. if (Res.first.getNode()) {
  6021. processIntegerCallValue(I, Res.first, true);
  6022. PendingLoads.push_back(Res.second);
  6023. return true;
  6024. }
  6025. return false;
  6026. }
  6027. /// See if we can lower a strlen call into an optimized form. If so, return
  6028. /// true and lower it, otherwise return false and it will be lowered like a
  6029. /// normal call.
  6030. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6031. /// correct prototype.
  6032. bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
  6033. const Value *Arg0 = I.getArgOperand(0);
  6034. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6035. std::pair<SDValue, SDValue> Res =
  6036. TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
  6037. getValue(Arg0), MachinePointerInfo(Arg0));
  6038. if (Res.first.getNode()) {
  6039. processIntegerCallValue(I, Res.first, false);
  6040. PendingLoads.push_back(Res.second);
  6041. return true;
  6042. }
  6043. return false;
  6044. }
  6045. /// See if we can lower a strnlen call into an optimized form. If so, return
  6046. /// true and lower it, otherwise return false and it will be lowered like a
  6047. /// normal call.
  6048. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6049. /// correct prototype.
  6050. bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
  6051. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  6052. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6053. std::pair<SDValue, SDValue> Res =
  6054. TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
  6055. getValue(Arg0), getValue(Arg1),
  6056. MachinePointerInfo(Arg0));
  6057. if (Res.first.getNode()) {
  6058. processIntegerCallValue(I, Res.first, false);
  6059. PendingLoads.push_back(Res.second);
  6060. return true;
  6061. }
  6062. return false;
  6063. }
  6064. /// See if we can lower a unary floating-point operation into an SDNode with
  6065. /// the specified Opcode. If so, return true and lower it, otherwise return
  6066. /// false and it will be lowered like a normal call.
  6067. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6068. /// correct prototype.
  6069. bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
  6070. unsigned Opcode) {
  6071. // We already checked this call's prototype; verify it doesn't modify errno.
  6072. if (!I.onlyReadsMemory())
  6073. return false;
  6074. SDValue Tmp = getValue(I.getArgOperand(0));
  6075. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
  6076. return true;
  6077. }
  6078. /// See if we can lower a binary floating-point operation into an SDNode with
  6079. /// the specified Opcode. If so, return true and lower it. Otherwise return
  6080. /// false, and it will be lowered like a normal call.
  6081. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6082. /// correct prototype.
  6083. bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
  6084. unsigned Opcode) {
  6085. // We already checked this call's prototype; verify it doesn't modify errno.
  6086. if (!I.onlyReadsMemory())
  6087. return false;
  6088. SDValue Tmp0 = getValue(I.getArgOperand(0));
  6089. SDValue Tmp1 = getValue(I.getArgOperand(1));
  6090. EVT VT = Tmp0.getValueType();
  6091. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
  6092. return true;
  6093. }
  6094. void SelectionDAGBuilder::visitCall(const CallInst &I) {
  6095. // Handle inline assembly differently.
  6096. if (isa<InlineAsm>(I.getCalledValue())) {
  6097. visitInlineAsm(&I);
  6098. return;
  6099. }
  6100. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  6101. computeUsesVAFloatArgument(I, MMI);
  6102. const char *RenameFn = nullptr;
  6103. if (Function *F = I.getCalledFunction()) {
  6104. if (F->isDeclaration()) {
  6105. // Is this an LLVM intrinsic or a target-specific intrinsic?
  6106. unsigned IID = F->getIntrinsicID();
  6107. if (!IID)
  6108. if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
  6109. IID = II->getIntrinsicID(F);
  6110. if (IID) {
  6111. RenameFn = visitIntrinsicCall(I, IID);
  6112. if (!RenameFn)
  6113. return;
  6114. }
  6115. }
  6116. // Check for well-known libc/libm calls. If the function is internal, it
  6117. // can't be a library call. Don't do the check if marked as nobuiltin for
  6118. // some reason or the call site requires strict floating point semantics.
  6119. LibFunc Func;
  6120. if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
  6121. F->hasName() && LibInfo->getLibFunc(*F, Func) &&
  6122. LibInfo->hasOptimizedCodeGen(Func)) {
  6123. switch (Func) {
  6124. default: break;
  6125. case LibFunc_copysign:
  6126. case LibFunc_copysignf:
  6127. case LibFunc_copysignl:
  6128. // We already checked this call's prototype; verify it doesn't modify
  6129. // errno.
  6130. if (I.onlyReadsMemory()) {
  6131. SDValue LHS = getValue(I.getArgOperand(0));
  6132. SDValue RHS = getValue(I.getArgOperand(1));
  6133. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
  6134. LHS.getValueType(), LHS, RHS));
  6135. return;
  6136. }
  6137. break;
  6138. case LibFunc_fabs:
  6139. case LibFunc_fabsf:
  6140. case LibFunc_fabsl:
  6141. if (visitUnaryFloatCall(I, ISD::FABS))
  6142. return;
  6143. break;
  6144. case LibFunc_fmin:
  6145. case LibFunc_fminf:
  6146. case LibFunc_fminl:
  6147. if (visitBinaryFloatCall(I, ISD::FMINNUM))
  6148. return;
  6149. break;
  6150. case LibFunc_fmax:
  6151. case LibFunc_fmaxf:
  6152. case LibFunc_fmaxl:
  6153. if (visitBinaryFloatCall(I, ISD::FMAXNUM))
  6154. return;
  6155. break;
  6156. case LibFunc_sin:
  6157. case LibFunc_sinf:
  6158. case LibFunc_sinl:
  6159. if (visitUnaryFloatCall(I, ISD::FSIN))
  6160. return;
  6161. break;
  6162. case LibFunc_cos:
  6163. case LibFunc_cosf:
  6164. case LibFunc_cosl:
  6165. if (visitUnaryFloatCall(I, ISD::FCOS))
  6166. return;
  6167. break;
  6168. case LibFunc_sqrt:
  6169. case LibFunc_sqrtf:
  6170. case LibFunc_sqrtl:
  6171. case LibFunc_sqrt_finite:
  6172. case LibFunc_sqrtf_finite:
  6173. case LibFunc_sqrtl_finite:
  6174. if (visitUnaryFloatCall(I, ISD::FSQRT))
  6175. return;
  6176. break;
  6177. case LibFunc_floor:
  6178. case LibFunc_floorf:
  6179. case LibFunc_floorl:
  6180. if (visitUnaryFloatCall(I, ISD::FFLOOR))
  6181. return;
  6182. break;
  6183. case LibFunc_nearbyint:
  6184. case LibFunc_nearbyintf:
  6185. case LibFunc_nearbyintl:
  6186. if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
  6187. return;
  6188. break;
  6189. case LibFunc_ceil:
  6190. case LibFunc_ceilf:
  6191. case LibFunc_ceill:
  6192. if (visitUnaryFloatCall(I, ISD::FCEIL))
  6193. return;
  6194. break;
  6195. case LibFunc_rint:
  6196. case LibFunc_rintf:
  6197. case LibFunc_rintl:
  6198. if (visitUnaryFloatCall(I, ISD::FRINT))
  6199. return;
  6200. break;
  6201. case LibFunc_round:
  6202. case LibFunc_roundf:
  6203. case LibFunc_roundl:
  6204. if (visitUnaryFloatCall(I, ISD::FROUND))
  6205. return;
  6206. break;
  6207. case LibFunc_trunc:
  6208. case LibFunc_truncf:
  6209. case LibFunc_truncl:
  6210. if (visitUnaryFloatCall(I, ISD::FTRUNC))
  6211. return;
  6212. break;
  6213. case LibFunc_log2:
  6214. case LibFunc_log2f:
  6215. case LibFunc_log2l:
  6216. if (visitUnaryFloatCall(I, ISD::FLOG2))
  6217. return;
  6218. break;
  6219. case LibFunc_exp2:
  6220. case LibFunc_exp2f:
  6221. case LibFunc_exp2l:
  6222. if (visitUnaryFloatCall(I, ISD::FEXP2))
  6223. return;
  6224. break;
  6225. case LibFunc_memcmp:
  6226. if (visitMemCmpCall(I))
  6227. return;
  6228. break;
  6229. case LibFunc_mempcpy:
  6230. if (visitMemPCpyCall(I))
  6231. return;
  6232. break;
  6233. case LibFunc_memchr:
  6234. if (visitMemChrCall(I))
  6235. return;
  6236. break;
  6237. case LibFunc_strcpy:
  6238. if (visitStrCpyCall(I, false))
  6239. return;
  6240. break;
  6241. case LibFunc_stpcpy:
  6242. if (visitStrCpyCall(I, true))
  6243. return;
  6244. break;
  6245. case LibFunc_strcmp:
  6246. if (visitStrCmpCall(I))
  6247. return;
  6248. break;
  6249. case LibFunc_strlen:
  6250. if (visitStrLenCall(I))
  6251. return;
  6252. break;
  6253. case LibFunc_strnlen:
  6254. if (visitStrNLenCall(I))
  6255. return;
  6256. break;
  6257. }
  6258. }
  6259. }
  6260. SDValue Callee;
  6261. if (!RenameFn)
  6262. Callee = getValue(I.getCalledValue());
  6263. else
  6264. Callee = DAG.getExternalSymbol(
  6265. RenameFn,
  6266. DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
  6267. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  6268. // have to do anything here to lower funclet bundles.
  6269. assert(!I.hasOperandBundlesOtherThan(
  6270. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  6271. "Cannot lower calls with arbitrary operand bundles!");
  6272. if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
  6273. LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
  6274. else
  6275. // Check if we can potentially perform a tail call. More detailed checking
  6276. // is be done within LowerCallTo, after more information about the call is
  6277. // known.
  6278. LowerCallTo(&I, Callee, I.isTailCall());
  6279. }
  6280. namespace {
  6281. /// AsmOperandInfo - This contains information for each constraint that we are
  6282. /// lowering.
  6283. class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
  6284. public:
  6285. /// CallOperand - If this is the result output operand or a clobber
  6286. /// this is null, otherwise it is the incoming operand to the CallInst.
  6287. /// This gets modified as the asm is processed.
  6288. SDValue CallOperand;
  6289. /// AssignedRegs - If this is a register or register class operand, this
  6290. /// contains the set of register corresponding to the operand.
  6291. RegsForValue AssignedRegs;
  6292. explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
  6293. : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
  6294. }
  6295. /// Whether or not this operand accesses memory
  6296. bool hasMemory(const TargetLowering &TLI) const {
  6297. // Indirect operand accesses access memory.
  6298. if (isIndirect)
  6299. return true;
  6300. for (const auto &Code : Codes)
  6301. if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
  6302. return true;
  6303. return false;
  6304. }
  6305. /// getCallOperandValEVT - Return the EVT of the Value* that this operand
  6306. /// corresponds to. If there is no Value* for this operand, it returns
  6307. /// MVT::Other.
  6308. EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
  6309. const DataLayout &DL) const {
  6310. if (!CallOperandVal) return MVT::Other;
  6311. if (isa<BasicBlock>(CallOperandVal))
  6312. return TLI.getPointerTy(DL);
  6313. llvm::Type *OpTy = CallOperandVal->getType();
  6314. // FIXME: code duplicated from TargetLowering::ParseConstraints().
  6315. // If this is an indirect operand, the operand is a pointer to the
  6316. // accessed type.
  6317. if (isIndirect) {
  6318. PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
  6319. if (!PtrTy)
  6320. report_fatal_error("Indirect operand for inline asm not a pointer!");
  6321. OpTy = PtrTy->getElementType();
  6322. }
  6323. // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
  6324. if (StructType *STy = dyn_cast<StructType>(OpTy))
  6325. if (STy->getNumElements() == 1)
  6326. OpTy = STy->getElementType(0);
  6327. // If OpTy is not a single value, it may be a struct/union that we
  6328. // can tile with integers.
  6329. if (!OpTy->isSingleValueType() && OpTy->isSized()) {
  6330. unsigned BitSize = DL.getTypeSizeInBits(OpTy);
  6331. switch (BitSize) {
  6332. default: break;
  6333. case 1:
  6334. case 8:
  6335. case 16:
  6336. case 32:
  6337. case 64:
  6338. case 128:
  6339. OpTy = IntegerType::get(Context, BitSize);
  6340. break;
  6341. }
  6342. }
  6343. return TLI.getValueType(DL, OpTy, true);
  6344. }
  6345. };
  6346. using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
  6347. } // end anonymous namespace
  6348. /// Make sure that the output operand \p OpInfo and its corresponding input
  6349. /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
  6350. /// out).
  6351. static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
  6352. SDISelAsmOperandInfo &MatchingOpInfo,
  6353. SelectionDAG &DAG) {
  6354. if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
  6355. return;
  6356. const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
  6357. const auto &TLI = DAG.getTargetLoweringInfo();
  6358. std::pair<unsigned, const TargetRegisterClass *> MatchRC =
  6359. TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
  6360. OpInfo.ConstraintVT);
  6361. std::pair<unsigned, const TargetRegisterClass *> InputRC =
  6362. TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
  6363. MatchingOpInfo.ConstraintVT);
  6364. if ((OpInfo.ConstraintVT.isInteger() !=
  6365. MatchingOpInfo.ConstraintVT.isInteger()) ||
  6366. (MatchRC.second != InputRC.second)) {
  6367. // FIXME: error out in a more elegant fashion
  6368. report_fatal_error("Unsupported asm: input constraint"
  6369. " with a matching output constraint of"
  6370. " incompatible type!");
  6371. }
  6372. MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
  6373. }
  6374. /// Get a direct memory input to behave well as an indirect operand.
  6375. /// This may introduce stores, hence the need for a \p Chain.
  6376. /// \return The (possibly updated) chain.
  6377. static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
  6378. SDISelAsmOperandInfo &OpInfo,
  6379. SelectionDAG &DAG) {
  6380. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6381. // If we don't have an indirect input, put it in the constpool if we can,
  6382. // otherwise spill it to a stack slot.
  6383. // TODO: This isn't quite right. We need to handle these according to
  6384. // the addressing mode that the constraint wants. Also, this may take
  6385. // an additional register for the computation and we don't want that
  6386. // either.
  6387. // If the operand is a float, integer, or vector constant, spill to a
  6388. // constant pool entry to get its address.
  6389. const Value *OpVal = OpInfo.CallOperandVal;
  6390. if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
  6391. isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
  6392. OpInfo.CallOperand = DAG.getConstantPool(
  6393. cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
  6394. return Chain;
  6395. }
  6396. // Otherwise, create a stack slot and emit a store to it before the asm.
  6397. Type *Ty = OpVal->getType();
  6398. auto &DL = DAG.getDataLayout();
  6399. uint64_t TySize = DL.getTypeAllocSize(Ty);
  6400. unsigned Align = DL.getPrefTypeAlignment(Ty);
  6401. MachineFunction &MF = DAG.getMachineFunction();
  6402. int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
  6403. SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
  6404. Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot,
  6405. MachinePointerInfo::getFixedStack(MF, SSFI));
  6406. OpInfo.CallOperand = StackSlot;
  6407. return Chain;
  6408. }
  6409. /// GetRegistersForValue - Assign registers (virtual or physical) for the
  6410. /// specified operand. We prefer to assign virtual registers, to allow the
  6411. /// register allocator to handle the assignment process. However, if the asm
  6412. /// uses features that we can't model on machineinstrs, we have SDISel do the
  6413. /// allocation. This produces generally horrible, but correct, code.
  6414. ///
  6415. /// OpInfo describes the operand
  6416. /// RefOpInfo describes the matching operand if any, the operand otherwise
  6417. static void GetRegistersForValue(SelectionDAG &DAG, const TargetLowering &TLI,
  6418. const SDLoc &DL, SDISelAsmOperandInfo &OpInfo,
  6419. SDISelAsmOperandInfo &RefOpInfo) {
  6420. LLVMContext &Context = *DAG.getContext();
  6421. MachineFunction &MF = DAG.getMachineFunction();
  6422. SmallVector<unsigned, 4> Regs;
  6423. const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
  6424. // If this is a constraint for a single physreg, or a constraint for a
  6425. // register class, find it.
  6426. std::pair<unsigned, const TargetRegisterClass *> PhysReg =
  6427. TLI.getRegForInlineAsmConstraint(&TRI, RefOpInfo.ConstraintCode,
  6428. RefOpInfo.ConstraintVT);
  6429. unsigned NumRegs = 1;
  6430. if (OpInfo.ConstraintVT != MVT::Other) {
  6431. // If this is an FP operand in an integer register (or visa versa), or more
  6432. // generally if the operand value disagrees with the register class we plan
  6433. // to stick it in, fix the operand type.
  6434. //
  6435. // If this is an input value, the bitcast to the new type is done now.
  6436. // Bitcast for output value is done at the end of visitInlineAsm().
  6437. if ((OpInfo.Type == InlineAsm::isOutput ||
  6438. OpInfo.Type == InlineAsm::isInput) &&
  6439. PhysReg.second &&
  6440. !TRI.isTypeLegalForClass(*PhysReg.second, OpInfo.ConstraintVT)) {
  6441. // Try to convert to the first EVT that the reg class contains. If the
  6442. // types are identical size, use a bitcast to convert (e.g. two differing
  6443. // vector types). Note: output bitcast is done at the end of
  6444. // visitInlineAsm().
  6445. MVT RegVT = *TRI.legalclasstypes_begin(*PhysReg.second);
  6446. if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
  6447. // Exclude indirect inputs while they are unsupported because the code
  6448. // to perform the load is missing and thus OpInfo.CallOperand still
  6449. // refers to the input address rather than the pointed-to value.
  6450. if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
  6451. OpInfo.CallOperand =
  6452. DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
  6453. OpInfo.ConstraintVT = RegVT;
  6454. // If the operand is an FP value and we want it in integer registers,
  6455. // use the corresponding integer type. This turns an f64 value into
  6456. // i64, which can be passed with two i32 values on a 32-bit machine.
  6457. } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
  6458. RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
  6459. if (OpInfo.Type == InlineAsm::isInput)
  6460. OpInfo.CallOperand =
  6461. DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
  6462. OpInfo.ConstraintVT = RegVT;
  6463. }
  6464. }
  6465. NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
  6466. }
  6467. // No need to allocate a matching input constraint since the constraint it's
  6468. // matching to has already been allocated.
  6469. if (OpInfo.isMatchingInputConstraint())
  6470. return;
  6471. MVT RegVT;
  6472. EVT ValueVT = OpInfo.ConstraintVT;
  6473. // If this is a constraint for a specific physical register, like {r17},
  6474. // assign it now.
  6475. if (unsigned AssignedReg = PhysReg.first) {
  6476. const TargetRegisterClass *RC = PhysReg.second;
  6477. if (OpInfo.ConstraintVT == MVT::Other)
  6478. ValueVT = *TRI.legalclasstypes_begin(*RC);
  6479. // Get the actual register value type. This is important, because the user
  6480. // may have asked for (e.g.) the AX register in i32 type. We need to
  6481. // remember that AX is actually i16 to get the right extension.
  6482. RegVT = *TRI.legalclasstypes_begin(*RC);
  6483. // This is an explicit reference to a physical register.
  6484. Regs.push_back(AssignedReg);
  6485. // If this is an expanded reference, add the rest of the regs to Regs.
  6486. if (NumRegs != 1) {
  6487. TargetRegisterClass::iterator I = RC->begin();
  6488. for (; *I != AssignedReg; ++I)
  6489. assert(I != RC->end() && "Didn't find reg!");
  6490. // Already added the first reg.
  6491. --NumRegs; ++I;
  6492. for (; NumRegs; --NumRegs, ++I) {
  6493. assert(I != RC->end() && "Ran out of registers to allocate!");
  6494. Regs.push_back(*I);
  6495. }
  6496. }
  6497. OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
  6498. return;
  6499. }
  6500. // Otherwise, if this was a reference to an LLVM register class, create vregs
  6501. // for this reference.
  6502. if (const TargetRegisterClass *RC = PhysReg.second) {
  6503. RegVT = *TRI.legalclasstypes_begin(*RC);
  6504. if (OpInfo.ConstraintVT == MVT::Other)
  6505. ValueVT = RegVT;
  6506. // Create the appropriate number of virtual registers.
  6507. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  6508. for (; NumRegs; --NumRegs)
  6509. Regs.push_back(RegInfo.createVirtualRegister(RC));
  6510. OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
  6511. return;
  6512. }
  6513. // Otherwise, we couldn't allocate enough registers for this.
  6514. }
  6515. static unsigned
  6516. findMatchingInlineAsmOperand(unsigned OperandNo,
  6517. const std::vector<SDValue> &AsmNodeOperands) {
  6518. // Scan until we find the definition we already emitted of this operand.
  6519. unsigned CurOp = InlineAsm::Op_FirstOperand;
  6520. for (; OperandNo; --OperandNo) {
  6521. // Advance to the next operand.
  6522. unsigned OpFlag =
  6523. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  6524. assert((InlineAsm::isRegDefKind(OpFlag) ||
  6525. InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
  6526. InlineAsm::isMemKind(OpFlag)) &&
  6527. "Skipped past definitions?");
  6528. CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
  6529. }
  6530. return CurOp;
  6531. }
  6532. /// Fill \p Regs with \p NumRegs new virtual registers of type \p RegVT
  6533. /// \return true if it has succeeded, false otherwise
  6534. static bool createVirtualRegs(SmallVector<unsigned, 4> &Regs, unsigned NumRegs,
  6535. MVT RegVT, SelectionDAG &DAG) {
  6536. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6537. MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
  6538. for (unsigned i = 0, e = NumRegs; i != e; ++i) {
  6539. if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT))
  6540. Regs.push_back(RegInfo.createVirtualRegister(RC));
  6541. else
  6542. return false;
  6543. }
  6544. return true;
  6545. }
  6546. namespace {
  6547. class ExtraFlags {
  6548. unsigned Flags = 0;
  6549. public:
  6550. explicit ExtraFlags(ImmutableCallSite CS) {
  6551. const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  6552. if (IA->hasSideEffects())
  6553. Flags |= InlineAsm::Extra_HasSideEffects;
  6554. if (IA->isAlignStack())
  6555. Flags |= InlineAsm::Extra_IsAlignStack;
  6556. if (CS.isConvergent())
  6557. Flags |= InlineAsm::Extra_IsConvergent;
  6558. Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
  6559. }
  6560. void update(const TargetLowering::AsmOperandInfo &OpInfo) {
  6561. // Ideally, we would only check against memory constraints. However, the
  6562. // meaning of an Other constraint can be target-specific and we can't easily
  6563. // reason about it. Therefore, be conservative and set MayLoad/MayStore
  6564. // for Other constraints as well.
  6565. if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
  6566. OpInfo.ConstraintType == TargetLowering::C_Other) {
  6567. if (OpInfo.Type == InlineAsm::isInput)
  6568. Flags |= InlineAsm::Extra_MayLoad;
  6569. else if (OpInfo.Type == InlineAsm::isOutput)
  6570. Flags |= InlineAsm::Extra_MayStore;
  6571. else if (OpInfo.Type == InlineAsm::isClobber)
  6572. Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
  6573. }
  6574. }
  6575. unsigned get() const { return Flags; }
  6576. };
  6577. } // end anonymous namespace
  6578. /// visitInlineAsm - Handle a call to an InlineAsm object.
  6579. void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
  6580. const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  6581. /// ConstraintOperands - Information about all of the constraints.
  6582. SDISelAsmOperandInfoVector ConstraintOperands;
  6583. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6584. TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
  6585. DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
  6586. bool hasMemory = false;
  6587. // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
  6588. ExtraFlags ExtraInfo(CS);
  6589. unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
  6590. unsigned ResNo = 0; // ResNo - The result number of the next output.
  6591. for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
  6592. ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
  6593. SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
  6594. MVT OpVT = MVT::Other;
  6595. // Compute the value type for each operand.
  6596. if (OpInfo.Type == InlineAsm::isInput ||
  6597. (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
  6598. OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
  6599. // Process the call argument. BasicBlocks are labels, currently appearing
  6600. // only in asm's.
  6601. if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
  6602. OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
  6603. } else {
  6604. OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
  6605. }
  6606. OpVT =
  6607. OpInfo
  6608. .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
  6609. .getSimpleVT();
  6610. }
  6611. if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
  6612. // The return value of the call is this value. As such, there is no
  6613. // corresponding argument.
  6614. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  6615. if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
  6616. OpVT = TLI.getSimpleValueType(DAG.getDataLayout(),
  6617. STy->getElementType(ResNo));
  6618. } else {
  6619. assert(ResNo == 0 && "Asm only has one result!");
  6620. OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
  6621. }
  6622. ++ResNo;
  6623. }
  6624. OpInfo.ConstraintVT = OpVT;
  6625. if (!hasMemory)
  6626. hasMemory = OpInfo.hasMemory(TLI);
  6627. // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
  6628. // FIXME: Could we compute this on OpInfo rather than TargetConstraints[i]?
  6629. auto TargetConstraint = TargetConstraints[i];
  6630. // Compute the constraint code and ConstraintType to use.
  6631. TLI.ComputeConstraintToUse(TargetConstraint, SDValue());
  6632. ExtraInfo.update(TargetConstraint);
  6633. }
  6634. SDValue Chain, Flag;
  6635. // We won't need to flush pending loads if this asm doesn't touch
  6636. // memory and is nonvolatile.
  6637. if (hasMemory || IA->hasSideEffects())
  6638. Chain = getRoot();
  6639. else
  6640. Chain = DAG.getRoot();
  6641. // Second pass over the constraints: compute which constraint option to use
  6642. // and assign registers to constraints that want a specific physreg.
  6643. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  6644. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  6645. // If this is an output operand with a matching input operand, look up the
  6646. // matching input. If their types mismatch, e.g. one is an integer, the
  6647. // other is floating point, or their sizes are different, flag it as an
  6648. // error.
  6649. if (OpInfo.hasMatchingInput()) {
  6650. SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
  6651. patchMatchingInput(OpInfo, Input, DAG);
  6652. }
  6653. // Compute the constraint code and ConstraintType to use.
  6654. TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
  6655. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  6656. OpInfo.Type == InlineAsm::isClobber)
  6657. continue;
  6658. // If this is a memory input, and if the operand is not indirect, do what we
  6659. // need to provide an address for the memory input.
  6660. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  6661. !OpInfo.isIndirect) {
  6662. assert((OpInfo.isMultipleAlternative ||
  6663. (OpInfo.Type == InlineAsm::isInput)) &&
  6664. "Can only indirectify direct input operands!");
  6665. // Memory operands really want the address of the value.
  6666. Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
  6667. // There is no longer a Value* corresponding to this operand.
  6668. OpInfo.CallOperandVal = nullptr;
  6669. // It is now an indirect operand.
  6670. OpInfo.isIndirect = true;
  6671. }
  6672. // If this constraint is for a specific register, allocate it before
  6673. // anything else.
  6674. SDISelAsmOperandInfo &RefOpInfo =
  6675. OpInfo.isMatchingInputConstraint()
  6676. ? ConstraintOperands[OpInfo.getMatchedOperand()]
  6677. : ConstraintOperands[i];
  6678. if (RefOpInfo.ConstraintType == TargetLowering::C_Register)
  6679. GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo, RefOpInfo);
  6680. }
  6681. // Third pass - Loop over all of the operands, assigning virtual or physregs
  6682. // to register class operands.
  6683. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  6684. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  6685. SDISelAsmOperandInfo &RefOpInfo =
  6686. OpInfo.isMatchingInputConstraint()
  6687. ? ConstraintOperands[OpInfo.getMatchedOperand()]
  6688. : ConstraintOperands[i];
  6689. // C_Register operands have already been allocated, Other/Memory don't need
  6690. // to be.
  6691. if (RefOpInfo.ConstraintType == TargetLowering::C_RegisterClass)
  6692. GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo, RefOpInfo);
  6693. }
  6694. // AsmNodeOperands - The operands for the ISD::INLINEASM node.
  6695. std::vector<SDValue> AsmNodeOperands;
  6696. AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
  6697. AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
  6698. IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
  6699. // If we have a !srcloc metadata node associated with it, we want to attach
  6700. // this to the ultimately generated inline asm machineinstr. To do this, we
  6701. // pass in the third operand as this (potentially null) inline asm MDNode.
  6702. const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
  6703. AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
  6704. // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
  6705. // bits as operand 3.
  6706. AsmNodeOperands.push_back(DAG.getTargetConstant(
  6707. ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  6708. // Loop over all of the inputs, copying the operand values into the
  6709. // appropriate registers and processing the output regs.
  6710. RegsForValue RetValRegs;
  6711. // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
  6712. std::vector<std::pair<RegsForValue, Value *>> IndirectStoresToEmit;
  6713. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  6714. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  6715. switch (OpInfo.Type) {
  6716. case InlineAsm::isOutput:
  6717. if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
  6718. OpInfo.ConstraintType != TargetLowering::C_Register) {
  6719. // Memory output, or 'other' output (e.g. 'X' constraint).
  6720. assert(OpInfo.isIndirect && "Memory output must be indirect operand");
  6721. unsigned ConstraintID =
  6722. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  6723. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  6724. "Failed to convert memory constraint code to constraint id.");
  6725. // Add information to the INLINEASM node to know about this output.
  6726. unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  6727. OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
  6728. AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
  6729. MVT::i32));
  6730. AsmNodeOperands.push_back(OpInfo.CallOperand);
  6731. break;
  6732. }
  6733. // Otherwise, this is a register or register class output.
  6734. // Copy the output from the appropriate register. Find a register that
  6735. // we can use.
  6736. if (OpInfo.AssignedRegs.Regs.empty()) {
  6737. emitInlineAsmError(
  6738. CS, "couldn't allocate output register for constraint '" +
  6739. Twine(OpInfo.ConstraintCode) + "'");
  6740. return;
  6741. }
  6742. // If this is an indirect operand, store through the pointer after the
  6743. // asm.
  6744. if (OpInfo.isIndirect) {
  6745. IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
  6746. OpInfo.CallOperandVal));
  6747. } else {
  6748. // This is the result value of the call.
  6749. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  6750. // Concatenate this output onto the outputs list.
  6751. RetValRegs.append(OpInfo.AssignedRegs);
  6752. }
  6753. // Add information to the INLINEASM node to know that this register is
  6754. // set.
  6755. OpInfo.AssignedRegs
  6756. .AddInlineAsmOperands(OpInfo.isEarlyClobber
  6757. ? InlineAsm::Kind_RegDefEarlyClobber
  6758. : InlineAsm::Kind_RegDef,
  6759. false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
  6760. break;
  6761. case InlineAsm::isInput: {
  6762. SDValue InOperandVal = OpInfo.CallOperand;
  6763. if (OpInfo.isMatchingInputConstraint()) {
  6764. // If this is required to match an output register we have already set,
  6765. // just use its register.
  6766. auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
  6767. AsmNodeOperands);
  6768. unsigned OpFlag =
  6769. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  6770. if (InlineAsm::isRegDefKind(OpFlag) ||
  6771. InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
  6772. // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
  6773. if (OpInfo.isIndirect) {
  6774. // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
  6775. emitInlineAsmError(CS, "inline asm not supported yet:"
  6776. " don't know how to handle tied "
  6777. "indirect register inputs");
  6778. return;
  6779. }
  6780. MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
  6781. SmallVector<unsigned, 4> Regs;
  6782. if (!createVirtualRegs(Regs,
  6783. InlineAsm::getNumOperandRegisters(OpFlag),
  6784. RegVT, DAG)) {
  6785. emitInlineAsmError(CS, "inline asm error: This value type register "
  6786. "class is not natively supported!");
  6787. return;
  6788. }
  6789. RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
  6790. SDLoc dl = getCurSDLoc();
  6791. // Use the produced MatchedRegs object to
  6792. MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
  6793. CS.getInstruction());
  6794. MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
  6795. true, OpInfo.getMatchedOperand(), dl,
  6796. DAG, AsmNodeOperands);
  6797. break;
  6798. }
  6799. assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
  6800. assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
  6801. "Unexpected number of operands");
  6802. // Add information to the INLINEASM node to know about this input.
  6803. // See InlineAsm.h isUseOperandTiedToDef.
  6804. OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
  6805. OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
  6806. OpInfo.getMatchedOperand());
  6807. AsmNodeOperands.push_back(DAG.getTargetConstant(
  6808. OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  6809. AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
  6810. break;
  6811. }
  6812. // Treat indirect 'X' constraint as memory.
  6813. if (OpInfo.ConstraintType == TargetLowering::C_Other &&
  6814. OpInfo.isIndirect)
  6815. OpInfo.ConstraintType = TargetLowering::C_Memory;
  6816. if (OpInfo.ConstraintType == TargetLowering::C_Other) {
  6817. std::vector<SDValue> Ops;
  6818. TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
  6819. Ops, DAG);
  6820. if (Ops.empty()) {
  6821. emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
  6822. Twine(OpInfo.ConstraintCode) + "'");
  6823. return;
  6824. }
  6825. // Add information to the INLINEASM node to know about this input.
  6826. unsigned ResOpType =
  6827. InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
  6828. AsmNodeOperands.push_back(DAG.getTargetConstant(
  6829. ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  6830. AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
  6831. break;
  6832. }
  6833. if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
  6834. assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
  6835. assert(InOperandVal.getValueType() ==
  6836. TLI.getPointerTy(DAG.getDataLayout()) &&
  6837. "Memory operands expect pointer values");
  6838. unsigned ConstraintID =
  6839. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  6840. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  6841. "Failed to convert memory constraint code to constraint id.");
  6842. // Add information to the INLINEASM node to know about this input.
  6843. unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  6844. ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
  6845. AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
  6846. getCurSDLoc(),
  6847. MVT::i32));
  6848. AsmNodeOperands.push_back(InOperandVal);
  6849. break;
  6850. }
  6851. assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
  6852. OpInfo.ConstraintType == TargetLowering::C_Register) &&
  6853. "Unknown constraint type!");
  6854. // TODO: Support this.
  6855. if (OpInfo.isIndirect) {
  6856. emitInlineAsmError(
  6857. CS, "Don't know how to handle indirect register inputs yet "
  6858. "for constraint '" +
  6859. Twine(OpInfo.ConstraintCode) + "'");
  6860. return;
  6861. }
  6862. // Copy the input into the appropriate registers.
  6863. if (OpInfo.AssignedRegs.Regs.empty()) {
  6864. emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
  6865. Twine(OpInfo.ConstraintCode) + "'");
  6866. return;
  6867. }
  6868. SDLoc dl = getCurSDLoc();
  6869. OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
  6870. Chain, &Flag, CS.getInstruction());
  6871. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
  6872. dl, DAG, AsmNodeOperands);
  6873. break;
  6874. }
  6875. case InlineAsm::isClobber:
  6876. // Add the clobbered value to the operand list, so that the register
  6877. // allocator is aware that the physreg got clobbered.
  6878. if (!OpInfo.AssignedRegs.Regs.empty())
  6879. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
  6880. false, 0, getCurSDLoc(), DAG,
  6881. AsmNodeOperands);
  6882. break;
  6883. }
  6884. }
  6885. // Finish up input operands. Set the input chain and add the flag last.
  6886. AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
  6887. if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
  6888. Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
  6889. DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
  6890. Flag = Chain.getValue(1);
  6891. // If this asm returns a register value, copy the result from that register
  6892. // and set it as the value of the call.
  6893. if (!RetValRegs.Regs.empty()) {
  6894. SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
  6895. Chain, &Flag, CS.getInstruction());
  6896. llvm::Type *CSResultType = CS.getType();
  6897. unsigned numRet;
  6898. ArrayRef<Type *> ResultTypes;
  6899. SmallVector<SDValue, 1> ResultValues(1);
  6900. if (CSResultType->isSingleValueType()) {
  6901. numRet = 1;
  6902. ResultValues[0] = Val;
  6903. ResultTypes = makeArrayRef(CSResultType);
  6904. } else {
  6905. numRet = CSResultType->getNumContainedTypes();
  6906. assert(Val->getNumOperands() == numRet &&
  6907. "Mismatch in number of output operands in asm result");
  6908. ResultTypes = CSResultType->subtypes();
  6909. ArrayRef<SDUse> ValueUses = Val->ops();
  6910. ResultValues.resize(numRet);
  6911. std::transform(ValueUses.begin(), ValueUses.end(), ResultValues.begin(),
  6912. [](const SDUse &u) -> SDValue { return u.get(); });
  6913. }
  6914. SmallVector<EVT, 1> ResultVTs(numRet);
  6915. for (unsigned i = 0; i < numRet; i++) {
  6916. EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), ResultTypes[i]);
  6917. SDValue Val = ResultValues[i];
  6918. assert(ResultTypes[i]->isSized() && "Unexpected unsized type");
  6919. // If the type of the inline asm call site return value is different but
  6920. // has same size as the type of the asm output bitcast it. One example
  6921. // of this is for vectors with different width / number of elements.
  6922. // This can happen for register classes that can contain multiple
  6923. // different value types. The preg or vreg allocated may not have the
  6924. // same VT as was expected.
  6925. //
  6926. // This can also happen for a return value that disagrees with the
  6927. // register class it is put in, eg. a double in a general-purpose
  6928. // register on a 32-bit machine.
  6929. if (ResultVT != Val.getValueType() &&
  6930. ResultVT.getSizeInBits() == Val.getValueSizeInBits())
  6931. Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, Val);
  6932. else if (ResultVT != Val.getValueType() && ResultVT.isInteger() &&
  6933. Val.getValueType().isInteger()) {
  6934. // If a result value was tied to an input value, the computed result
  6935. // may have a wider width than the expected result. Extract the
  6936. // relevant portion.
  6937. Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, Val);
  6938. }
  6939. assert(ResultVT == Val.getValueType() && "Asm result value mismatch!");
  6940. ResultVTs[i] = ResultVT;
  6941. ResultValues[i] = Val;
  6942. }
  6943. Val = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  6944. DAG.getVTList(ResultVTs), ResultValues);
  6945. setValue(CS.getInstruction(), Val);
  6946. // Don't need to use this as a chain in this case.
  6947. if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
  6948. return;
  6949. }
  6950. std::vector<std::pair<SDValue, const Value *>> StoresToEmit;
  6951. // Process indirect outputs, first output all of the flagged copies out of
  6952. // physregs.
  6953. for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
  6954. RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
  6955. const Value *Ptr = IndirectStoresToEmit[i].second;
  6956. SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
  6957. Chain, &Flag, IA);
  6958. StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
  6959. }
  6960. // Emit the non-flagged stores from the physregs.
  6961. SmallVector<SDValue, 8> OutChains;
  6962. for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
  6963. SDValue Val = DAG.getStore(Chain, getCurSDLoc(), StoresToEmit[i].first,
  6964. getValue(StoresToEmit[i].second),
  6965. MachinePointerInfo(StoresToEmit[i].second));
  6966. OutChains.push_back(Val);
  6967. }
  6968. if (!OutChains.empty())
  6969. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
  6970. DAG.setRoot(Chain);
  6971. }
  6972. void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
  6973. const Twine &Message) {
  6974. LLVMContext &Ctx = *DAG.getContext();
  6975. Ctx.emitError(CS.getInstruction(), Message);
  6976. // Make sure we leave the DAG in a valid state
  6977. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6978. SmallVector<EVT, 1> ValueVTs;
  6979. ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
  6980. if (ValueVTs.empty())
  6981. return;
  6982. SmallVector<SDValue, 1> Ops;
  6983. for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
  6984. Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
  6985. setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
  6986. }
  6987. void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
  6988. DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
  6989. MVT::Other, getRoot(),
  6990. getValue(I.getArgOperand(0)),
  6991. DAG.getSrcValue(I.getArgOperand(0))));
  6992. }
  6993. void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
  6994. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6995. const DataLayout &DL = DAG.getDataLayout();
  6996. SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
  6997. getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
  6998. DAG.getSrcValue(I.getOperand(0)),
  6999. DL.getABITypeAlignment(I.getType()));
  7000. setValue(&I, V);
  7001. DAG.setRoot(V.getValue(1));
  7002. }
  7003. void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
  7004. DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
  7005. MVT::Other, getRoot(),
  7006. getValue(I.getArgOperand(0)),
  7007. DAG.getSrcValue(I.getArgOperand(0))));
  7008. }
  7009. void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
  7010. DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
  7011. MVT::Other, getRoot(),
  7012. getValue(I.getArgOperand(0)),
  7013. getValue(I.getArgOperand(1)),
  7014. DAG.getSrcValue(I.getArgOperand(0)),
  7015. DAG.getSrcValue(I.getArgOperand(1))));
  7016. }
  7017. SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
  7018. const Instruction &I,
  7019. SDValue Op) {
  7020. const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
  7021. if (!Range)
  7022. return Op;
  7023. ConstantRange CR = getConstantRangeFromMetadata(*Range);
  7024. if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet())
  7025. return Op;
  7026. APInt Lo = CR.getUnsignedMin();
  7027. if (!Lo.isMinValue())
  7028. return Op;
  7029. APInt Hi = CR.getUnsignedMax();
  7030. unsigned Bits = Hi.getActiveBits();
  7031. EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
  7032. SDLoc SL = getCurSDLoc();
  7033. SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
  7034. DAG.getValueType(SmallVT));
  7035. unsigned NumVals = Op.getNode()->getNumValues();
  7036. if (NumVals == 1)
  7037. return ZExt;
  7038. SmallVector<SDValue, 4> Ops;
  7039. Ops.push_back(ZExt);
  7040. for (unsigned I = 1; I != NumVals; ++I)
  7041. Ops.push_back(Op.getValue(I));
  7042. return DAG.getMergeValues(Ops, SL);
  7043. }
  7044. /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
  7045. /// the call being lowered.
  7046. ///
  7047. /// This is a helper for lowering intrinsics that follow a target calling
  7048. /// convention or require stack pointer adjustment. Only a subset of the
  7049. /// intrinsic's operands need to participate in the calling convention.
  7050. void SelectionDAGBuilder::populateCallLoweringInfo(
  7051. TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS,
  7052. unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
  7053. bool IsPatchPoint) {
  7054. TargetLowering::ArgListTy Args;
  7055. Args.reserve(NumArgs);
  7056. // Populate the argument list.
  7057. // Attributes for args start at offset 1, after the return attribute.
  7058. for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
  7059. ArgI != ArgE; ++ArgI) {
  7060. const Value *V = CS->getOperand(ArgI);
  7061. assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
  7062. TargetLowering::ArgListEntry Entry;
  7063. Entry.Node = getValue(V);
  7064. Entry.Ty = V->getType();
  7065. Entry.setAttributes(&CS, ArgI);
  7066. Args.push_back(Entry);
  7067. }
  7068. CLI.setDebugLoc(getCurSDLoc())
  7069. .setChain(getRoot())
  7070. .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args))
  7071. .setDiscardResult(CS->use_empty())
  7072. .setIsPatchPoint(IsPatchPoint);
  7073. }
  7074. /// Add a stack map intrinsic call's live variable operands to a stackmap
  7075. /// or patchpoint target node's operand list.
  7076. ///
  7077. /// Constants are converted to TargetConstants purely as an optimization to
  7078. /// avoid constant materialization and register allocation.
  7079. ///
  7080. /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
  7081. /// generate addess computation nodes, and so ExpandISelPseudo can convert the
  7082. /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
  7083. /// address materialization and register allocation, but may also be required
  7084. /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
  7085. /// alloca in the entry block, then the runtime may assume that the alloca's
  7086. /// StackMap location can be read immediately after compilation and that the
  7087. /// location is valid at any point during execution (this is similar to the
  7088. /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
  7089. /// only available in a register, then the runtime would need to trap when
  7090. /// execution reaches the StackMap in order to read the alloca's location.
  7091. static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
  7092. const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
  7093. SelectionDAGBuilder &Builder) {
  7094. for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
  7095. SDValue OpVal = Builder.getValue(CS.getArgument(i));
  7096. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
  7097. Ops.push_back(
  7098. Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
  7099. Ops.push_back(
  7100. Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
  7101. } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
  7102. const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
  7103. Ops.push_back(Builder.DAG.getTargetFrameIndex(
  7104. FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
  7105. } else
  7106. Ops.push_back(OpVal);
  7107. }
  7108. }
  7109. /// Lower llvm.experimental.stackmap directly to its target opcode.
  7110. void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
  7111. // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
  7112. // [live variables...])
  7113. assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
  7114. SDValue Chain, InFlag, Callee, NullPtr;
  7115. SmallVector<SDValue, 32> Ops;
  7116. SDLoc DL = getCurSDLoc();
  7117. Callee = getValue(CI.getCalledValue());
  7118. NullPtr = DAG.getIntPtrConstant(0, DL, true);
  7119. // The stackmap intrinsic only records the live variables (the arguemnts
  7120. // passed to it) and emits NOPS (if requested). Unlike the patchpoint
  7121. // intrinsic, this won't be lowered to a function call. This means we don't
  7122. // have to worry about calling conventions and target specific lowering code.
  7123. // Instead we perform the call lowering right here.
  7124. //
  7125. // chain, flag = CALLSEQ_START(chain, 0, 0)
  7126. // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
  7127. // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
  7128. //
  7129. Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
  7130. InFlag = Chain.getValue(1);
  7131. // Add the <id> and <numBytes> constants.
  7132. SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
  7133. Ops.push_back(DAG.getTargetConstant(
  7134. cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
  7135. SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
  7136. Ops.push_back(DAG.getTargetConstant(
  7137. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
  7138. MVT::i32));
  7139. // Push live variables for the stack map.
  7140. addStackMapLiveVars(&CI, 2, DL, Ops, *this);
  7141. // We are not pushing any register mask info here on the operands list,
  7142. // because the stackmap doesn't clobber anything.
  7143. // Push the chain and the glue flag.
  7144. Ops.push_back(Chain);
  7145. Ops.push_back(InFlag);
  7146. // Create the STACKMAP node.
  7147. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  7148. SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
  7149. Chain = SDValue(SM, 0);
  7150. InFlag = Chain.getValue(1);
  7151. Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
  7152. // Stackmaps don't generate values, so nothing goes into the NodeMap.
  7153. // Set the root to the target-lowered call chain.
  7154. DAG.setRoot(Chain);
  7155. // Inform the Frame Information that we have a stackmap in this function.
  7156. FuncInfo.MF->getFrameInfo().setHasStackMap();
  7157. }
  7158. /// Lower llvm.experimental.patchpoint directly to its target opcode.
  7159. void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
  7160. const BasicBlock *EHPadBB) {
  7161. // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
  7162. // i32 <numBytes>,
  7163. // i8* <target>,
  7164. // i32 <numArgs>,
  7165. // [Args...],
  7166. // [live variables...])
  7167. CallingConv::ID CC = CS.getCallingConv();
  7168. bool IsAnyRegCC = CC == CallingConv::AnyReg;
  7169. bool HasDef = !CS->getType()->isVoidTy();
  7170. SDLoc dl = getCurSDLoc();
  7171. SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
  7172. // Handle immediate and symbolic callees.
  7173. if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
  7174. Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
  7175. /*isTarget=*/true);
  7176. else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
  7177. Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
  7178. SDLoc(SymbolicCallee),
  7179. SymbolicCallee->getValueType(0));
  7180. // Get the real number of arguments participating in the call <numArgs>
  7181. SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
  7182. unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
  7183. // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
  7184. // Intrinsics include all meta-operands up to but not including CC.
  7185. unsigned NumMetaOpers = PatchPointOpers::CCPos;
  7186. assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
  7187. "Not enough arguments provided to the patchpoint intrinsic");
  7188. // For AnyRegCC the arguments are lowered later on manually.
  7189. unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
  7190. Type *ReturnTy =
  7191. IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
  7192. TargetLowering::CallLoweringInfo CLI(DAG);
  7193. populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy,
  7194. true);
  7195. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  7196. SDNode *CallEnd = Result.second.getNode();
  7197. if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
  7198. CallEnd = CallEnd->getOperand(0).getNode();
  7199. /// Get a call instruction from the call sequence chain.
  7200. /// Tail calls are not allowed.
  7201. assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
  7202. "Expected a callseq node.");
  7203. SDNode *Call = CallEnd->getOperand(0).getNode();
  7204. bool HasGlue = Call->getGluedNode();
  7205. // Replace the target specific call node with the patchable intrinsic.
  7206. SmallVector<SDValue, 8> Ops;
  7207. // Add the <id> and <numBytes> constants.
  7208. SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
  7209. Ops.push_back(DAG.getTargetConstant(
  7210. cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
  7211. SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
  7212. Ops.push_back(DAG.getTargetConstant(
  7213. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
  7214. MVT::i32));
  7215. // Add the callee.
  7216. Ops.push_back(Callee);
  7217. // Adjust <numArgs> to account for any arguments that have been passed on the
  7218. // stack instead.
  7219. // Call Node: Chain, Target, {Args}, RegMask, [Glue]
  7220. unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
  7221. NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
  7222. Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
  7223. // Add the calling convention
  7224. Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
  7225. // Add the arguments we omitted previously. The register allocator should
  7226. // place these in any free register.
  7227. if (IsAnyRegCC)
  7228. for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
  7229. Ops.push_back(getValue(CS.getArgument(i)));
  7230. // Push the arguments from the call instruction up to the register mask.
  7231. SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
  7232. Ops.append(Call->op_begin() + 2, e);
  7233. // Push live variables for the stack map.
  7234. addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
  7235. // Push the register mask info.
  7236. if (HasGlue)
  7237. Ops.push_back(*(Call->op_end()-2));
  7238. else
  7239. Ops.push_back(*(Call->op_end()-1));
  7240. // Push the chain (this is originally the first operand of the call, but
  7241. // becomes now the last or second to last operand).
  7242. Ops.push_back(*(Call->op_begin()));
  7243. // Push the glue flag (last operand).
  7244. if (HasGlue)
  7245. Ops.push_back(*(Call->op_end()-1));
  7246. SDVTList NodeTys;
  7247. if (IsAnyRegCC && HasDef) {
  7248. // Create the return types based on the intrinsic definition
  7249. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7250. SmallVector<EVT, 3> ValueVTs;
  7251. ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
  7252. assert(ValueVTs.size() == 1 && "Expected only one return value type.");
  7253. // There is always a chain and a glue type at the end
  7254. ValueVTs.push_back(MVT::Other);
  7255. ValueVTs.push_back(MVT::Glue);
  7256. NodeTys = DAG.getVTList(ValueVTs);
  7257. } else
  7258. NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  7259. // Replace the target specific call node with a PATCHPOINT node.
  7260. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
  7261. dl, NodeTys, Ops);
  7262. // Update the NodeMap.
  7263. if (HasDef) {
  7264. if (IsAnyRegCC)
  7265. setValue(CS.getInstruction(), SDValue(MN, 0));
  7266. else
  7267. setValue(CS.getInstruction(), Result.first);
  7268. }
  7269. // Fixup the consumers of the intrinsic. The chain and glue may be used in the
  7270. // call sequence. Furthermore the location of the chain and glue can change
  7271. // when the AnyReg calling convention is used and the intrinsic returns a
  7272. // value.
  7273. if (IsAnyRegCC && HasDef) {
  7274. SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
  7275. SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
  7276. DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
  7277. } else
  7278. DAG.ReplaceAllUsesWith(Call, MN);
  7279. DAG.DeleteNode(Call);
  7280. // Inform the Frame Information that we have a patchpoint in this function.
  7281. FuncInfo.MF->getFrameInfo().setHasPatchPoint();
  7282. }
  7283. void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
  7284. unsigned Intrinsic) {
  7285. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7286. SDValue Op1 = getValue(I.getArgOperand(0));
  7287. SDValue Op2;
  7288. if (I.getNumArgOperands() > 1)
  7289. Op2 = getValue(I.getArgOperand(1));
  7290. SDLoc dl = getCurSDLoc();
  7291. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  7292. SDValue Res;
  7293. FastMathFlags FMF;
  7294. if (isa<FPMathOperator>(I))
  7295. FMF = I.getFastMathFlags();
  7296. switch (Intrinsic) {
  7297. case Intrinsic::experimental_vector_reduce_fadd:
  7298. if (FMF.isFast())
  7299. Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2);
  7300. else
  7301. Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
  7302. break;
  7303. case Intrinsic::experimental_vector_reduce_fmul:
  7304. if (FMF.isFast())
  7305. Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2);
  7306. else
  7307. Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
  7308. break;
  7309. case Intrinsic::experimental_vector_reduce_add:
  7310. Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
  7311. break;
  7312. case Intrinsic::experimental_vector_reduce_mul:
  7313. Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
  7314. break;
  7315. case Intrinsic::experimental_vector_reduce_and:
  7316. Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
  7317. break;
  7318. case Intrinsic::experimental_vector_reduce_or:
  7319. Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
  7320. break;
  7321. case Intrinsic::experimental_vector_reduce_xor:
  7322. Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
  7323. break;
  7324. case Intrinsic::experimental_vector_reduce_smax:
  7325. Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
  7326. break;
  7327. case Intrinsic::experimental_vector_reduce_smin:
  7328. Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
  7329. break;
  7330. case Intrinsic::experimental_vector_reduce_umax:
  7331. Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
  7332. break;
  7333. case Intrinsic::experimental_vector_reduce_umin:
  7334. Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
  7335. break;
  7336. case Intrinsic::experimental_vector_reduce_fmax:
  7337. Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
  7338. break;
  7339. case Intrinsic::experimental_vector_reduce_fmin:
  7340. Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
  7341. break;
  7342. default:
  7343. llvm_unreachable("Unhandled vector reduce intrinsic");
  7344. }
  7345. setValue(&I, Res);
  7346. }
  7347. /// Returns an AttributeList representing the attributes applied to the return
  7348. /// value of the given call.
  7349. static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
  7350. SmallVector<Attribute::AttrKind, 2> Attrs;
  7351. if (CLI.RetSExt)
  7352. Attrs.push_back(Attribute::SExt);
  7353. if (CLI.RetZExt)
  7354. Attrs.push_back(Attribute::ZExt);
  7355. if (CLI.IsInReg)
  7356. Attrs.push_back(Attribute::InReg);
  7357. return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
  7358. Attrs);
  7359. }
  7360. /// TargetLowering::LowerCallTo - This is the default LowerCallTo
  7361. /// implementation, which just calls LowerCall.
  7362. /// FIXME: When all targets are
  7363. /// migrated to using LowerCall, this hook should be integrated into SDISel.
  7364. std::pair<SDValue, SDValue>
  7365. TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
  7366. // Handle the incoming return values from the call.
  7367. CLI.Ins.clear();
  7368. Type *OrigRetTy = CLI.RetTy;
  7369. SmallVector<EVT, 4> RetTys;
  7370. SmallVector<uint64_t, 4> Offsets;
  7371. auto &DL = CLI.DAG.getDataLayout();
  7372. ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
  7373. if (CLI.IsPostTypeLegalization) {
  7374. // If we are lowering a libcall after legalization, split the return type.
  7375. SmallVector<EVT, 4> OldRetTys = std::move(RetTys);
  7376. SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets);
  7377. for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
  7378. EVT RetVT = OldRetTys[i];
  7379. uint64_t Offset = OldOffsets[i];
  7380. MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
  7381. unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
  7382. unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
  7383. RetTys.append(NumRegs, RegisterVT);
  7384. for (unsigned j = 0; j != NumRegs; ++j)
  7385. Offsets.push_back(Offset + j * RegisterVTByteSZ);
  7386. }
  7387. }
  7388. SmallVector<ISD::OutputArg, 4> Outs;
  7389. GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
  7390. bool CanLowerReturn =
  7391. this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
  7392. CLI.IsVarArg, Outs, CLI.RetTy->getContext());
  7393. SDValue DemoteStackSlot;
  7394. int DemoteStackIdx = -100;
  7395. if (!CanLowerReturn) {
  7396. // FIXME: equivalent assert?
  7397. // assert(!CS.hasInAllocaArgument() &&
  7398. // "sret demotion is incompatible with inalloca");
  7399. uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
  7400. unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
  7401. MachineFunction &MF = CLI.DAG.getMachineFunction();
  7402. DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
  7403. Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
  7404. DL.getAllocaAddrSpace());
  7405. DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
  7406. ArgListEntry Entry;
  7407. Entry.Node = DemoteStackSlot;
  7408. Entry.Ty = StackSlotPtrType;
  7409. Entry.IsSExt = false;
  7410. Entry.IsZExt = false;
  7411. Entry.IsInReg = false;
  7412. Entry.IsSRet = true;
  7413. Entry.IsNest = false;
  7414. Entry.IsByVal = false;
  7415. Entry.IsReturned = false;
  7416. Entry.IsSwiftSelf = false;
  7417. Entry.IsSwiftError = false;
  7418. Entry.Alignment = Align;
  7419. CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
  7420. CLI.NumFixedArgs += 1;
  7421. CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
  7422. // sret demotion isn't compatible with tail-calls, since the sret argument
  7423. // points into the callers stack frame.
  7424. CLI.IsTailCall = false;
  7425. } else {
  7426. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  7427. EVT VT = RetTys[I];
  7428. MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  7429. CLI.CallConv, VT);
  7430. unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  7431. CLI.CallConv, VT);
  7432. for (unsigned i = 0; i != NumRegs; ++i) {
  7433. ISD::InputArg MyFlags;
  7434. MyFlags.VT = RegisterVT;
  7435. MyFlags.ArgVT = VT;
  7436. MyFlags.Used = CLI.IsReturnValueUsed;
  7437. if (CLI.RetSExt)
  7438. MyFlags.Flags.setSExt();
  7439. if (CLI.RetZExt)
  7440. MyFlags.Flags.setZExt();
  7441. if (CLI.IsInReg)
  7442. MyFlags.Flags.setInReg();
  7443. CLI.Ins.push_back(MyFlags);
  7444. }
  7445. }
  7446. }
  7447. // We push in swifterror return as the last element of CLI.Ins.
  7448. ArgListTy &Args = CLI.getArgs();
  7449. if (supportSwiftError()) {
  7450. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  7451. if (Args[i].IsSwiftError) {
  7452. ISD::InputArg MyFlags;
  7453. MyFlags.VT = getPointerTy(DL);
  7454. MyFlags.ArgVT = EVT(getPointerTy(DL));
  7455. MyFlags.Flags.setSwiftError();
  7456. CLI.Ins.push_back(MyFlags);
  7457. }
  7458. }
  7459. }
  7460. // Handle all of the outgoing arguments.
  7461. CLI.Outs.clear();
  7462. CLI.OutVals.clear();
  7463. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  7464. SmallVector<EVT, 4> ValueVTs;
  7465. ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
  7466. // FIXME: Split arguments if CLI.IsPostTypeLegalization
  7467. Type *FinalType = Args[i].Ty;
  7468. if (Args[i].IsByVal)
  7469. FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
  7470. bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
  7471. FinalType, CLI.CallConv, CLI.IsVarArg);
  7472. for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
  7473. ++Value) {
  7474. EVT VT = ValueVTs[Value];
  7475. Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
  7476. SDValue Op = SDValue(Args[i].Node.getNode(),
  7477. Args[i].Node.getResNo() + Value);
  7478. ISD::ArgFlagsTy Flags;
  7479. // Certain targets (such as MIPS), may have a different ABI alignment
  7480. // for a type depending on the context. Give the target a chance to
  7481. // specify the alignment it wants.
  7482. unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
  7483. if (Args[i].IsZExt)
  7484. Flags.setZExt();
  7485. if (Args[i].IsSExt)
  7486. Flags.setSExt();
  7487. if (Args[i].IsInReg) {
  7488. // If we are using vectorcall calling convention, a structure that is
  7489. // passed InReg - is surely an HVA
  7490. if (CLI.CallConv == CallingConv::X86_VectorCall &&
  7491. isa<StructType>(FinalType)) {
  7492. // The first value of a structure is marked
  7493. if (0 == Value)
  7494. Flags.setHvaStart();
  7495. Flags.setHva();
  7496. }
  7497. // Set InReg Flag
  7498. Flags.setInReg();
  7499. }
  7500. if (Args[i].IsSRet)
  7501. Flags.setSRet();
  7502. if (Args[i].IsSwiftSelf)
  7503. Flags.setSwiftSelf();
  7504. if (Args[i].IsSwiftError)
  7505. Flags.setSwiftError();
  7506. if (Args[i].IsByVal)
  7507. Flags.setByVal();
  7508. if (Args[i].IsInAlloca) {
  7509. Flags.setInAlloca();
  7510. // Set the byval flag for CCAssignFn callbacks that don't know about
  7511. // inalloca. This way we can know how many bytes we should've allocated
  7512. // and how many bytes a callee cleanup function will pop. If we port
  7513. // inalloca to more targets, we'll have to add custom inalloca handling
  7514. // in the various CC lowering callbacks.
  7515. Flags.setByVal();
  7516. }
  7517. if (Args[i].IsByVal || Args[i].IsInAlloca) {
  7518. PointerType *Ty = cast<PointerType>(Args[i].Ty);
  7519. Type *ElementTy = Ty->getElementType();
  7520. Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
  7521. // For ByVal, alignment should come from FE. BE will guess if this
  7522. // info is not there but there are cases it cannot get right.
  7523. unsigned FrameAlign;
  7524. if (Args[i].Alignment)
  7525. FrameAlign = Args[i].Alignment;
  7526. else
  7527. FrameAlign = getByValTypeAlignment(ElementTy, DL);
  7528. Flags.setByValAlign(FrameAlign);
  7529. }
  7530. if (Args[i].IsNest)
  7531. Flags.setNest();
  7532. if (NeedsRegBlock)
  7533. Flags.setInConsecutiveRegs();
  7534. Flags.setOrigAlign(OriginalAlignment);
  7535. MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  7536. CLI.CallConv, VT);
  7537. unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  7538. CLI.CallConv, VT);
  7539. SmallVector<SDValue, 4> Parts(NumParts);
  7540. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  7541. if (Args[i].IsSExt)
  7542. ExtendKind = ISD::SIGN_EXTEND;
  7543. else if (Args[i].IsZExt)
  7544. ExtendKind = ISD::ZERO_EXTEND;
  7545. // Conservatively only handle 'returned' on non-vectors that can be lowered,
  7546. // for now.
  7547. if (Args[i].IsReturned && !Op.getValueType().isVector() &&
  7548. CanLowerReturn) {
  7549. assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
  7550. "unexpected use of 'returned'");
  7551. // Before passing 'returned' to the target lowering code, ensure that
  7552. // either the register MVT and the actual EVT are the same size or that
  7553. // the return value and argument are extended in the same way; in these
  7554. // cases it's safe to pass the argument register value unchanged as the
  7555. // return register value (although it's at the target's option whether
  7556. // to do so)
  7557. // TODO: allow code generation to take advantage of partially preserved
  7558. // registers rather than clobbering the entire register when the
  7559. // parameter extension method is not compatible with the return
  7560. // extension method
  7561. if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
  7562. (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
  7563. CLI.RetZExt == Args[i].IsZExt))
  7564. Flags.setReturned();
  7565. }
  7566. getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
  7567. CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
  7568. for (unsigned j = 0; j != NumParts; ++j) {
  7569. // if it isn't first piece, alignment must be 1
  7570. ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
  7571. i < CLI.NumFixedArgs,
  7572. i, j*Parts[j].getValueType().getStoreSize());
  7573. if (NumParts > 1 && j == 0)
  7574. MyFlags.Flags.setSplit();
  7575. else if (j != 0) {
  7576. MyFlags.Flags.setOrigAlign(1);
  7577. if (j == NumParts - 1)
  7578. MyFlags.Flags.setSplitEnd();
  7579. }
  7580. CLI.Outs.push_back(MyFlags);
  7581. CLI.OutVals.push_back(Parts[j]);
  7582. }
  7583. if (NeedsRegBlock && Value == NumValues - 1)
  7584. CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
  7585. }
  7586. }
  7587. SmallVector<SDValue, 4> InVals;
  7588. CLI.Chain = LowerCall(CLI, InVals);
  7589. // Update CLI.InVals to use outside of this function.
  7590. CLI.InVals = InVals;
  7591. // Verify that the target's LowerCall behaved as expected.
  7592. assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
  7593. "LowerCall didn't return a valid chain!");
  7594. assert((!CLI.IsTailCall || InVals.empty()) &&
  7595. "LowerCall emitted a return value for a tail call!");
  7596. assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
  7597. "LowerCall didn't emit the correct number of values!");
  7598. // For a tail call, the return value is merely live-out and there aren't
  7599. // any nodes in the DAG representing it. Return a special value to
  7600. // indicate that a tail call has been emitted and no more Instructions
  7601. // should be processed in the current block.
  7602. if (CLI.IsTailCall) {
  7603. CLI.DAG.setRoot(CLI.Chain);
  7604. return std::make_pair(SDValue(), SDValue());
  7605. }
  7606. #ifndef NDEBUG
  7607. for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
  7608. assert(InVals[i].getNode() && "LowerCall emitted a null value!");
  7609. assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
  7610. "LowerCall emitted a value with the wrong type!");
  7611. }
  7612. #endif
  7613. SmallVector<SDValue, 4> ReturnValues;
  7614. if (!CanLowerReturn) {
  7615. // The instruction result is the result of loading from the
  7616. // hidden sret parameter.
  7617. SmallVector<EVT, 1> PVTs;
  7618. Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
  7619. ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
  7620. assert(PVTs.size() == 1 && "Pointers should fit in one register");
  7621. EVT PtrVT = PVTs[0];
  7622. unsigned NumValues = RetTys.size();
  7623. ReturnValues.resize(NumValues);
  7624. SmallVector<SDValue, 4> Chains(NumValues);
  7625. // An aggregate return value cannot wrap around the address space, so
  7626. // offsets to its parts don't wrap either.
  7627. SDNodeFlags Flags;
  7628. Flags.setNoUnsignedWrap(true);
  7629. for (unsigned i = 0; i < NumValues; ++i) {
  7630. SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
  7631. CLI.DAG.getConstant(Offsets[i], CLI.DL,
  7632. PtrVT), Flags);
  7633. SDValue L = CLI.DAG.getLoad(
  7634. RetTys[i], CLI.DL, CLI.Chain, Add,
  7635. MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
  7636. DemoteStackIdx, Offsets[i]),
  7637. /* Alignment = */ 1);
  7638. ReturnValues[i] = L;
  7639. Chains[i] = L.getValue(1);
  7640. }
  7641. CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
  7642. } else {
  7643. // Collect the legal value parts into potentially illegal values
  7644. // that correspond to the original function's return values.
  7645. Optional<ISD::NodeType> AssertOp;
  7646. if (CLI.RetSExt)
  7647. AssertOp = ISD::AssertSext;
  7648. else if (CLI.RetZExt)
  7649. AssertOp = ISD::AssertZext;
  7650. unsigned CurReg = 0;
  7651. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  7652. EVT VT = RetTys[I];
  7653. MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  7654. CLI.CallConv, VT);
  7655. unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  7656. CLI.CallConv, VT);
  7657. ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
  7658. NumRegs, RegisterVT, VT, nullptr,
  7659. CLI.CallConv, AssertOp));
  7660. CurReg += NumRegs;
  7661. }
  7662. // For a function returning void, there is no return value. We can't create
  7663. // such a node, so we just return a null return value in that case. In
  7664. // that case, nothing will actually look at the value.
  7665. if (ReturnValues.empty())
  7666. return std::make_pair(SDValue(), CLI.Chain);
  7667. }
  7668. SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
  7669. CLI.DAG.getVTList(RetTys), ReturnValues);
  7670. return std::make_pair(Res, CLI.Chain);
  7671. }
  7672. void TargetLowering::LowerOperationWrapper(SDNode *N,
  7673. SmallVectorImpl<SDValue> &Results,
  7674. SelectionDAG &DAG) const {
  7675. if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
  7676. Results.push_back(Res);
  7677. }
  7678. SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
  7679. llvm_unreachable("LowerOperation not implemented for this target!");
  7680. }
  7681. void
  7682. SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
  7683. SDValue Op = getNonRegisterValue(V);
  7684. assert((Op.getOpcode() != ISD::CopyFromReg ||
  7685. cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
  7686. "Copy from a reg to the same reg!");
  7687. assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
  7688. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7689. // If this is an InlineAsm we have to match the registers required, not the
  7690. // notional registers required by the type.
  7691. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
  7692. None); // This is not an ABI copy.
  7693. SDValue Chain = DAG.getEntryNode();
  7694. ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
  7695. FuncInfo.PreferredExtendType.end())
  7696. ? ISD::ANY_EXTEND
  7697. : FuncInfo.PreferredExtendType[V];
  7698. RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
  7699. PendingExports.push_back(Chain);
  7700. }
  7701. #include "llvm/CodeGen/SelectionDAGISel.h"
  7702. /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
  7703. /// entry block, return true. This includes arguments used by switches, since
  7704. /// the switch may expand into multiple basic blocks.
  7705. static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
  7706. // With FastISel active, we may be splitting blocks, so force creation
  7707. // of virtual registers for all non-dead arguments.
  7708. if (FastISel)
  7709. return A->use_empty();
  7710. const BasicBlock &Entry = A->getParent()->front();
  7711. for (const User *U : A->users())
  7712. if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
  7713. return false; // Use not in entry block.
  7714. return true;
  7715. }
  7716. using ArgCopyElisionMapTy =
  7717. DenseMap<const Argument *,
  7718. std::pair<const AllocaInst *, const StoreInst *>>;
  7719. /// Scan the entry block of the function in FuncInfo for arguments that look
  7720. /// like copies into a local alloca. Record any copied arguments in
  7721. /// ArgCopyElisionCandidates.
  7722. static void
  7723. findArgumentCopyElisionCandidates(const DataLayout &DL,
  7724. FunctionLoweringInfo *FuncInfo,
  7725. ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
  7726. // Record the state of every static alloca used in the entry block. Argument
  7727. // allocas are all used in the entry block, so we need approximately as many
  7728. // entries as we have arguments.
  7729. enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
  7730. SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
  7731. unsigned NumArgs = FuncInfo->Fn->arg_size();
  7732. StaticAllocas.reserve(NumArgs * 2);
  7733. auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
  7734. if (!V)
  7735. return nullptr;
  7736. V = V->stripPointerCasts();
  7737. const auto *AI = dyn_cast<AllocaInst>(V);
  7738. if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
  7739. return nullptr;
  7740. auto Iter = StaticAllocas.insert({AI, Unknown});
  7741. return &Iter.first->second;
  7742. };
  7743. // Look for stores of arguments to static allocas. Look through bitcasts and
  7744. // GEPs to handle type coercions, as long as the alloca is fully initialized
  7745. // by the store. Any non-store use of an alloca escapes it and any subsequent
  7746. // unanalyzed store might write it.
  7747. // FIXME: Handle structs initialized with multiple stores.
  7748. for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
  7749. // Look for stores, and handle non-store uses conservatively.
  7750. const auto *SI = dyn_cast<StoreInst>(&I);
  7751. if (!SI) {
  7752. // We will look through cast uses, so ignore them completely.
  7753. if (I.isCast())
  7754. continue;
  7755. // Ignore debug info intrinsics, they don't escape or store to allocas.
  7756. if (isa<DbgInfoIntrinsic>(I))
  7757. continue;
  7758. // This is an unknown instruction. Assume it escapes or writes to all
  7759. // static alloca operands.
  7760. for (const Use &U : I.operands()) {
  7761. if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
  7762. *Info = StaticAllocaInfo::Clobbered;
  7763. }
  7764. continue;
  7765. }
  7766. // If the stored value is a static alloca, mark it as escaped.
  7767. if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
  7768. *Info = StaticAllocaInfo::Clobbered;
  7769. // Check if the destination is a static alloca.
  7770. const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
  7771. StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
  7772. if (!Info)
  7773. continue;
  7774. const AllocaInst *AI = cast<AllocaInst>(Dst);
  7775. // Skip allocas that have been initialized or clobbered.
  7776. if (*Info != StaticAllocaInfo::Unknown)
  7777. continue;
  7778. // Check if the stored value is an argument, and that this store fully
  7779. // initializes the alloca. Don't elide copies from the same argument twice.
  7780. const Value *Val = SI->getValueOperand()->stripPointerCasts();
  7781. const auto *Arg = dyn_cast<Argument>(Val);
  7782. if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
  7783. Arg->getType()->isEmptyTy() ||
  7784. DL.getTypeStoreSize(Arg->getType()) !=
  7785. DL.getTypeAllocSize(AI->getAllocatedType()) ||
  7786. ArgCopyElisionCandidates.count(Arg)) {
  7787. *Info = StaticAllocaInfo::Clobbered;
  7788. continue;
  7789. }
  7790. LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
  7791. << '\n');
  7792. // Mark this alloca and store for argument copy elision.
  7793. *Info = StaticAllocaInfo::Elidable;
  7794. ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
  7795. // Stop scanning if we've seen all arguments. This will happen early in -O0
  7796. // builds, which is useful, because -O0 builds have large entry blocks and
  7797. // many allocas.
  7798. if (ArgCopyElisionCandidates.size() == NumArgs)
  7799. break;
  7800. }
  7801. }
  7802. /// Try to elide argument copies from memory into a local alloca. Succeeds if
  7803. /// ArgVal is a load from a suitable fixed stack object.
  7804. static void tryToElideArgumentCopy(
  7805. FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
  7806. DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
  7807. SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
  7808. ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
  7809. SDValue ArgVal, bool &ArgHasUses) {
  7810. // Check if this is a load from a fixed stack object.
  7811. auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
  7812. if (!LNode)
  7813. return;
  7814. auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
  7815. if (!FINode)
  7816. return;
  7817. // Check that the fixed stack object is the right size and alignment.
  7818. // Look at the alignment that the user wrote on the alloca instead of looking
  7819. // at the stack object.
  7820. auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
  7821. assert(ArgCopyIter != ArgCopyElisionCandidates.end());
  7822. const AllocaInst *AI = ArgCopyIter->second.first;
  7823. int FixedIndex = FINode->getIndex();
  7824. int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
  7825. int OldIndex = AllocaIndex;
  7826. MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
  7827. if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
  7828. LLVM_DEBUG(
  7829. dbgs() << " argument copy elision failed due to bad fixed stack "
  7830. "object size\n");
  7831. return;
  7832. }
  7833. unsigned RequiredAlignment = AI->getAlignment();
  7834. if (!RequiredAlignment) {
  7835. RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
  7836. AI->getAllocatedType());
  7837. }
  7838. if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
  7839. LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca "
  7840. "greater than stack argument alignment ("
  7841. << RequiredAlignment << " vs "
  7842. << MFI.getObjectAlignment(FixedIndex) << ")\n");
  7843. return;
  7844. }
  7845. // Perform the elision. Delete the old stack object and replace its only use
  7846. // in the variable info map. Mark the stack object as mutable.
  7847. LLVM_DEBUG({
  7848. dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
  7849. << " Replacing frame index " << OldIndex << " with " << FixedIndex
  7850. << '\n';
  7851. });
  7852. MFI.RemoveStackObject(OldIndex);
  7853. MFI.setIsImmutableObjectIndex(FixedIndex, false);
  7854. AllocaIndex = FixedIndex;
  7855. ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
  7856. Chains.push_back(ArgVal.getValue(1));
  7857. // Avoid emitting code for the store implementing the copy.
  7858. const StoreInst *SI = ArgCopyIter->second.second;
  7859. ElidedArgCopyInstrs.insert(SI);
  7860. // Check for uses of the argument again so that we can avoid exporting ArgVal
  7861. // if it is't used by anything other than the store.
  7862. for (const Value *U : Arg.users()) {
  7863. if (U != SI) {
  7864. ArgHasUses = true;
  7865. break;
  7866. }
  7867. }
  7868. }
  7869. void SelectionDAGISel::LowerArguments(const Function &F) {
  7870. SelectionDAG &DAG = SDB->DAG;
  7871. SDLoc dl = SDB->getCurSDLoc();
  7872. const DataLayout &DL = DAG.getDataLayout();
  7873. SmallVector<ISD::InputArg, 16> Ins;
  7874. if (!FuncInfo->CanLowerReturn) {
  7875. // Put in an sret pointer parameter before all the other parameters.
  7876. SmallVector<EVT, 1> ValueVTs;
  7877. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  7878. F.getReturnType()->getPointerTo(
  7879. DAG.getDataLayout().getAllocaAddrSpace()),
  7880. ValueVTs);
  7881. // NOTE: Assuming that a pointer will never break down to more than one VT
  7882. // or one register.
  7883. ISD::ArgFlagsTy Flags;
  7884. Flags.setSRet();
  7885. MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
  7886. ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
  7887. ISD::InputArg::NoArgIndex, 0);
  7888. Ins.push_back(RetArg);
  7889. }
  7890. // Look for stores of arguments to static allocas. Mark such arguments with a
  7891. // flag to ask the target to give us the memory location of that argument if
  7892. // available.
  7893. ArgCopyElisionMapTy ArgCopyElisionCandidates;
  7894. findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
  7895. // Set up the incoming argument description vector.
  7896. for (const Argument &Arg : F.args()) {
  7897. unsigned ArgNo = Arg.getArgNo();
  7898. SmallVector<EVT, 4> ValueVTs;
  7899. ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
  7900. bool isArgValueUsed = !Arg.use_empty();
  7901. unsigned PartBase = 0;
  7902. Type *FinalType = Arg.getType();
  7903. if (Arg.hasAttribute(Attribute::ByVal))
  7904. FinalType = cast<PointerType>(FinalType)->getElementType();
  7905. bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
  7906. FinalType, F.getCallingConv(), F.isVarArg());
  7907. for (unsigned Value = 0, NumValues = ValueVTs.size();
  7908. Value != NumValues; ++Value) {
  7909. EVT VT = ValueVTs[Value];
  7910. Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
  7911. ISD::ArgFlagsTy Flags;
  7912. // Certain targets (such as MIPS), may have a different ABI alignment
  7913. // for a type depending on the context. Give the target a chance to
  7914. // specify the alignment it wants.
  7915. unsigned OriginalAlignment =
  7916. TLI->getABIAlignmentForCallingConv(ArgTy, DL);
  7917. if (Arg.hasAttribute(Attribute::ZExt))
  7918. Flags.setZExt();
  7919. if (Arg.hasAttribute(Attribute::SExt))
  7920. Flags.setSExt();
  7921. if (Arg.hasAttribute(Attribute::InReg)) {
  7922. // If we are using vectorcall calling convention, a structure that is
  7923. // passed InReg - is surely an HVA
  7924. if (F.getCallingConv() == CallingConv::X86_VectorCall &&
  7925. isa<StructType>(Arg.getType())) {
  7926. // The first value of a structure is marked
  7927. if (0 == Value)
  7928. Flags.setHvaStart();
  7929. Flags.setHva();
  7930. }
  7931. // Set InReg Flag
  7932. Flags.setInReg();
  7933. }
  7934. if (Arg.hasAttribute(Attribute::StructRet))
  7935. Flags.setSRet();
  7936. if (Arg.hasAttribute(Attribute::SwiftSelf))
  7937. Flags.setSwiftSelf();
  7938. if (Arg.hasAttribute(Attribute::SwiftError))
  7939. Flags.setSwiftError();
  7940. if (Arg.hasAttribute(Attribute::ByVal))
  7941. Flags.setByVal();
  7942. if (Arg.hasAttribute(Attribute::InAlloca)) {
  7943. Flags.setInAlloca();
  7944. // Set the byval flag for CCAssignFn callbacks that don't know about
  7945. // inalloca. This way we can know how many bytes we should've allocated
  7946. // and how many bytes a callee cleanup function will pop. If we port
  7947. // inalloca to more targets, we'll have to add custom inalloca handling
  7948. // in the various CC lowering callbacks.
  7949. Flags.setByVal();
  7950. }
  7951. if (F.getCallingConv() == CallingConv::X86_INTR) {
  7952. // IA Interrupt passes frame (1st parameter) by value in the stack.
  7953. if (ArgNo == 0)
  7954. Flags.setByVal();
  7955. }
  7956. if (Flags.isByVal() || Flags.isInAlloca()) {
  7957. PointerType *Ty = cast<PointerType>(Arg.getType());
  7958. Type *ElementTy = Ty->getElementType();
  7959. Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
  7960. // For ByVal, alignment should be passed from FE. BE will guess if
  7961. // this info is not there but there are cases it cannot get right.
  7962. unsigned FrameAlign;
  7963. if (Arg.getParamAlignment())
  7964. FrameAlign = Arg.getParamAlignment();
  7965. else
  7966. FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
  7967. Flags.setByValAlign(FrameAlign);
  7968. }
  7969. if (Arg.hasAttribute(Attribute::Nest))
  7970. Flags.setNest();
  7971. if (NeedsRegBlock)
  7972. Flags.setInConsecutiveRegs();
  7973. Flags.setOrigAlign(OriginalAlignment);
  7974. if (ArgCopyElisionCandidates.count(&Arg))
  7975. Flags.setCopyElisionCandidate();
  7976. MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
  7977. *CurDAG->getContext(), F.getCallingConv(), VT);
  7978. unsigned NumRegs = TLI->getNumRegistersForCallingConv(
  7979. *CurDAG->getContext(), F.getCallingConv(), VT);
  7980. for (unsigned i = 0; i != NumRegs; ++i) {
  7981. ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
  7982. ArgNo, PartBase+i*RegisterVT.getStoreSize());
  7983. if (NumRegs > 1 && i == 0)
  7984. MyFlags.Flags.setSplit();
  7985. // if it isn't first piece, alignment must be 1
  7986. else if (i > 0) {
  7987. MyFlags.Flags.setOrigAlign(1);
  7988. if (i == NumRegs - 1)
  7989. MyFlags.Flags.setSplitEnd();
  7990. }
  7991. Ins.push_back(MyFlags);
  7992. }
  7993. if (NeedsRegBlock && Value == NumValues - 1)
  7994. Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
  7995. PartBase += VT.getStoreSize();
  7996. }
  7997. }
  7998. // Call the target to set up the argument values.
  7999. SmallVector<SDValue, 8> InVals;
  8000. SDValue NewRoot = TLI->LowerFormalArguments(
  8001. DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
  8002. // Verify that the target's LowerFormalArguments behaved as expected.
  8003. assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
  8004. "LowerFormalArguments didn't return a valid chain!");
  8005. assert(InVals.size() == Ins.size() &&
  8006. "LowerFormalArguments didn't emit the correct number of values!");
  8007. LLVM_DEBUG({
  8008. for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
  8009. assert(InVals[i].getNode() &&
  8010. "LowerFormalArguments emitted a null value!");
  8011. assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
  8012. "LowerFormalArguments emitted a value with the wrong type!");
  8013. }
  8014. });
  8015. // Update the DAG with the new chain value resulting from argument lowering.
  8016. DAG.setRoot(NewRoot);
  8017. // Set up the argument values.
  8018. unsigned i = 0;
  8019. if (!FuncInfo->CanLowerReturn) {
  8020. // Create a virtual register for the sret pointer, and put in a copy
  8021. // from the sret argument into it.
  8022. SmallVector<EVT, 1> ValueVTs;
  8023. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  8024. F.getReturnType()->getPointerTo(
  8025. DAG.getDataLayout().getAllocaAddrSpace()),
  8026. ValueVTs);
  8027. MVT VT = ValueVTs[0].getSimpleVT();
  8028. MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
  8029. Optional<ISD::NodeType> AssertOp = None;
  8030. SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
  8031. nullptr, F.getCallingConv(), AssertOp);
  8032. MachineFunction& MF = SDB->DAG.getMachineFunction();
  8033. MachineRegisterInfo& RegInfo = MF.getRegInfo();
  8034. unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
  8035. FuncInfo->DemoteRegister = SRetReg;
  8036. NewRoot =
  8037. SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
  8038. DAG.setRoot(NewRoot);
  8039. // i indexes lowered arguments. Bump it past the hidden sret argument.
  8040. ++i;
  8041. }
  8042. SmallVector<SDValue, 4> Chains;
  8043. DenseMap<int, int> ArgCopyElisionFrameIndexMap;
  8044. for (const Argument &Arg : F.args()) {
  8045. SmallVector<SDValue, 4> ArgValues;
  8046. SmallVector<EVT, 4> ValueVTs;
  8047. ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
  8048. unsigned NumValues = ValueVTs.size();
  8049. if (NumValues == 0)
  8050. continue;
  8051. bool ArgHasUses = !Arg.use_empty();
  8052. // Elide the copying store if the target loaded this argument from a
  8053. // suitable fixed stack object.
  8054. if (Ins[i].Flags.isCopyElisionCandidate()) {
  8055. tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
  8056. ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
  8057. InVals[i], ArgHasUses);
  8058. }
  8059. // If this argument is unused then remember its value. It is used to generate
  8060. // debugging information.
  8061. bool isSwiftErrorArg =
  8062. TLI->supportSwiftError() &&
  8063. Arg.hasAttribute(Attribute::SwiftError);
  8064. if (!ArgHasUses && !isSwiftErrorArg) {
  8065. SDB->setUnusedArgValue(&Arg, InVals[i]);
  8066. // Also remember any frame index for use in FastISel.
  8067. if (FrameIndexSDNode *FI =
  8068. dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
  8069. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  8070. }
  8071. for (unsigned Val = 0; Val != NumValues; ++Val) {
  8072. EVT VT = ValueVTs[Val];
  8073. MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
  8074. F.getCallingConv(), VT);
  8075. unsigned NumParts = TLI->getNumRegistersForCallingConv(
  8076. *CurDAG->getContext(), F.getCallingConv(), VT);
  8077. // Even an apparant 'unused' swifterror argument needs to be returned. So
  8078. // we do generate a copy for it that can be used on return from the
  8079. // function.
  8080. if (ArgHasUses || isSwiftErrorArg) {
  8081. Optional<ISD::NodeType> AssertOp;
  8082. if (Arg.hasAttribute(Attribute::SExt))
  8083. AssertOp = ISD::AssertSext;
  8084. else if (Arg.hasAttribute(Attribute::ZExt))
  8085. AssertOp = ISD::AssertZext;
  8086. ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
  8087. PartVT, VT, nullptr,
  8088. F.getCallingConv(), AssertOp));
  8089. }
  8090. i += NumParts;
  8091. }
  8092. // We don't need to do anything else for unused arguments.
  8093. if (ArgValues.empty())
  8094. continue;
  8095. // Note down frame index.
  8096. if (FrameIndexSDNode *FI =
  8097. dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
  8098. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  8099. SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
  8100. SDB->getCurSDLoc());
  8101. SDB->setValue(&Arg, Res);
  8102. if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
  8103. // We want to associate the argument with the frame index, among
  8104. // involved operands, that correspond to the lowest address. The
  8105. // getCopyFromParts function, called earlier, is swapping the order of
  8106. // the operands to BUILD_PAIR depending on endianness. The result of
  8107. // that swapping is that the least significant bits of the argument will
  8108. // be in the first operand of the BUILD_PAIR node, and the most
  8109. // significant bits will be in the second operand.
  8110. unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
  8111. if (LoadSDNode *LNode =
  8112. dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
  8113. if (FrameIndexSDNode *FI =
  8114. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  8115. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  8116. }
  8117. // Update the SwiftErrorVRegDefMap.
  8118. if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
  8119. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  8120. if (TargetRegisterInfo::isVirtualRegister(Reg))
  8121. FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB,
  8122. FuncInfo->SwiftErrorArg, Reg);
  8123. }
  8124. // If this argument is live outside of the entry block, insert a copy from
  8125. // wherever we got it to the vreg that other BB's will reference it as.
  8126. if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
  8127. // If we can, though, try to skip creating an unnecessary vreg.
  8128. // FIXME: This isn't very clean... it would be nice to make this more
  8129. // general. It's also subtly incompatible with the hacks FastISel
  8130. // uses with vregs.
  8131. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  8132. if (TargetRegisterInfo::isVirtualRegister(Reg)) {
  8133. FuncInfo->ValueMap[&Arg] = Reg;
  8134. continue;
  8135. }
  8136. }
  8137. if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
  8138. FuncInfo->InitializeRegForValue(&Arg);
  8139. SDB->CopyToExportRegsIfNeeded(&Arg);
  8140. }
  8141. }
  8142. if (!Chains.empty()) {
  8143. Chains.push_back(NewRoot);
  8144. NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  8145. }
  8146. DAG.setRoot(NewRoot);
  8147. assert(i == InVals.size() && "Argument register count mismatch!");
  8148. // If any argument copy elisions occurred and we have debug info, update the
  8149. // stale frame indices used in the dbg.declare variable info table.
  8150. MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
  8151. if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
  8152. for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
  8153. auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
  8154. if (I != ArgCopyElisionFrameIndexMap.end())
  8155. VI.Slot = I->second;
  8156. }
  8157. }
  8158. // Finally, if the target has anything special to do, allow it to do so.
  8159. EmitFunctionEntryCode();
  8160. }
  8161. /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
  8162. /// ensure constants are generated when needed. Remember the virtual registers
  8163. /// that need to be added to the Machine PHI nodes as input. We cannot just
  8164. /// directly add them, because expansion might result in multiple MBB's for one
  8165. /// BB. As such, the start of the BB might correspond to a different MBB than
  8166. /// the end.
  8167. void
  8168. SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
  8169. const TerminatorInst *TI = LLVMBB->getTerminator();
  8170. SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
  8171. // Check PHI nodes in successors that expect a value to be available from this
  8172. // block.
  8173. for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
  8174. const BasicBlock *SuccBB = TI->getSuccessor(succ);
  8175. if (!isa<PHINode>(SuccBB->begin())) continue;
  8176. MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
  8177. // If this terminator has multiple identical successors (common for
  8178. // switches), only handle each succ once.
  8179. if (!SuccsHandled.insert(SuccMBB).second)
  8180. continue;
  8181. MachineBasicBlock::iterator MBBI = SuccMBB->begin();
  8182. // At this point we know that there is a 1-1 correspondence between LLVM PHI
  8183. // nodes and Machine PHI nodes, but the incoming operands have not been
  8184. // emitted yet.
  8185. for (const PHINode &PN : SuccBB->phis()) {
  8186. // Ignore dead phi's.
  8187. if (PN.use_empty())
  8188. continue;
  8189. // Skip empty types
  8190. if (PN.getType()->isEmptyTy())
  8191. continue;
  8192. unsigned Reg;
  8193. const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
  8194. if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
  8195. unsigned &RegOut = ConstantsOut[C];
  8196. if (RegOut == 0) {
  8197. RegOut = FuncInfo.CreateRegs(C->getType());
  8198. CopyValueToVirtualRegister(C, RegOut);
  8199. }
  8200. Reg = RegOut;
  8201. } else {
  8202. DenseMap<const Value *, unsigned>::iterator I =
  8203. FuncInfo.ValueMap.find(PHIOp);
  8204. if (I != FuncInfo.ValueMap.end())
  8205. Reg = I->second;
  8206. else {
  8207. assert(isa<AllocaInst>(PHIOp) &&
  8208. FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
  8209. "Didn't codegen value into a register!??");
  8210. Reg = FuncInfo.CreateRegs(PHIOp->getType());
  8211. CopyValueToVirtualRegister(PHIOp, Reg);
  8212. }
  8213. }
  8214. // Remember that this register needs to added to the machine PHI node as
  8215. // the input for this MBB.
  8216. SmallVector<EVT, 4> ValueVTs;
  8217. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8218. ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
  8219. for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
  8220. EVT VT = ValueVTs[vti];
  8221. unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
  8222. for (unsigned i = 0, e = NumRegisters; i != e; ++i)
  8223. FuncInfo.PHINodesToUpdate.push_back(
  8224. std::make_pair(&*MBBI++, Reg + i));
  8225. Reg += NumRegisters;
  8226. }
  8227. }
  8228. }
  8229. ConstantsOut.clear();
  8230. }
  8231. /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
  8232. /// is 0.
  8233. MachineBasicBlock *
  8234. SelectionDAGBuilder::StackProtectorDescriptor::
  8235. AddSuccessorMBB(const BasicBlock *BB,
  8236. MachineBasicBlock *ParentMBB,
  8237. bool IsLikely,
  8238. MachineBasicBlock *SuccMBB) {
  8239. // If SuccBB has not been created yet, create it.
  8240. if (!SuccMBB) {
  8241. MachineFunction *MF = ParentMBB->getParent();
  8242. MachineFunction::iterator BBI(ParentMBB);
  8243. SuccMBB = MF->CreateMachineBasicBlock(BB);
  8244. MF->insert(++BBI, SuccMBB);
  8245. }
  8246. // Add it as a successor of ParentMBB.
  8247. ParentMBB->addSuccessor(
  8248. SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
  8249. return SuccMBB;
  8250. }
  8251. MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
  8252. MachineFunction::iterator I(MBB);
  8253. if (++I == FuncInfo.MF->end())
  8254. return nullptr;
  8255. return &*I;
  8256. }
  8257. /// During lowering new call nodes can be created (such as memset, etc.).
  8258. /// Those will become new roots of the current DAG, but complications arise
  8259. /// when they are tail calls. In such cases, the call lowering will update
  8260. /// the root, but the builder still needs to know that a tail call has been
  8261. /// lowered in order to avoid generating an additional return.
  8262. void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
  8263. // If the node is null, we do have a tail call.
  8264. if (MaybeTC.getNode() != nullptr)
  8265. DAG.setRoot(MaybeTC);
  8266. else
  8267. HasTailCall = true;
  8268. }
  8269. uint64_t
  8270. SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters,
  8271. unsigned First, unsigned Last) const {
  8272. assert(Last >= First);
  8273. const APInt &LowCase = Clusters[First].Low->getValue();
  8274. const APInt &HighCase = Clusters[Last].High->getValue();
  8275. assert(LowCase.getBitWidth() == HighCase.getBitWidth());
  8276. // FIXME: A range of consecutive cases has 100% density, but only requires one
  8277. // comparison to lower. We should discriminate against such consecutive ranges
  8278. // in jump tables.
  8279. return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1;
  8280. }
  8281. uint64_t SelectionDAGBuilder::getJumpTableNumCases(
  8282. const SmallVectorImpl<unsigned> &TotalCases, unsigned First,
  8283. unsigned Last) const {
  8284. assert(Last >= First);
  8285. assert(TotalCases[Last] >= TotalCases[First]);
  8286. uint64_t NumCases =
  8287. TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
  8288. return NumCases;
  8289. }
  8290. bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters,
  8291. unsigned First, unsigned Last,
  8292. const SwitchInst *SI,
  8293. MachineBasicBlock *DefaultMBB,
  8294. CaseCluster &JTCluster) {
  8295. assert(First <= Last);
  8296. auto Prob = BranchProbability::getZero();
  8297. unsigned NumCmps = 0;
  8298. std::vector<MachineBasicBlock*> Table;
  8299. DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
  8300. // Initialize probabilities in JTProbs.
  8301. for (unsigned I = First; I <= Last; ++I)
  8302. JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
  8303. for (unsigned I = First; I <= Last; ++I) {
  8304. assert(Clusters[I].Kind == CC_Range);
  8305. Prob += Clusters[I].Prob;
  8306. const APInt &Low = Clusters[I].Low->getValue();
  8307. const APInt &High = Clusters[I].High->getValue();
  8308. NumCmps += (Low == High) ? 1 : 2;
  8309. if (I != First) {
  8310. // Fill the gap between this and the previous cluster.
  8311. const APInt &PreviousHigh = Clusters[I - 1].High->getValue();
  8312. assert(PreviousHigh.slt(Low));
  8313. uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
  8314. for (uint64_t J = 0; J < Gap; J++)
  8315. Table.push_back(DefaultMBB);
  8316. }
  8317. uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
  8318. for (uint64_t J = 0; J < ClusterSize; ++J)
  8319. Table.push_back(Clusters[I].MBB);
  8320. JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
  8321. }
  8322. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8323. unsigned NumDests = JTProbs.size();
  8324. if (TLI.isSuitableForBitTests(
  8325. NumDests, NumCmps, Clusters[First].Low->getValue(),
  8326. Clusters[Last].High->getValue(), DAG.getDataLayout())) {
  8327. // Clusters[First..Last] should be lowered as bit tests instead.
  8328. return false;
  8329. }
  8330. // Create the MBB that will load from and jump through the table.
  8331. // Note: We create it here, but it's not inserted into the function yet.
  8332. MachineFunction *CurMF = FuncInfo.MF;
  8333. MachineBasicBlock *JumpTableMBB =
  8334. CurMF->CreateMachineBasicBlock(SI->getParent());
  8335. // Add successors. Note: use table order for determinism.
  8336. SmallPtrSet<MachineBasicBlock *, 8> Done;
  8337. for (MachineBasicBlock *Succ : Table) {
  8338. if (Done.count(Succ))
  8339. continue;
  8340. addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
  8341. Done.insert(Succ);
  8342. }
  8343. JumpTableMBB->normalizeSuccProbs();
  8344. unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
  8345. ->createJumpTableIndex(Table);
  8346. // Set up the jump table info.
  8347. JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
  8348. JumpTableHeader JTH(Clusters[First].Low->getValue(),
  8349. Clusters[Last].High->getValue(), SI->getCondition(),
  8350. nullptr, false);
  8351. JTCases.emplace_back(std::move(JTH), std::move(JT));
  8352. JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
  8353. JTCases.size() - 1, Prob);
  8354. return true;
  8355. }
  8356. void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
  8357. const SwitchInst *SI,
  8358. MachineBasicBlock *DefaultMBB) {
  8359. #ifndef NDEBUG
  8360. // Clusters must be non-empty, sorted, and only contain Range clusters.
  8361. assert(!Clusters.empty());
  8362. for (CaseCluster &C : Clusters)
  8363. assert(C.Kind == CC_Range);
  8364. for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
  8365. assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
  8366. #endif
  8367. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8368. if (!TLI.areJTsAllowed(SI->getParent()->getParent()))
  8369. return;
  8370. const int64_t N = Clusters.size();
  8371. const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries();
  8372. const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2;
  8373. if (N < 2 || N < MinJumpTableEntries)
  8374. return;
  8375. // TotalCases[i]: Total nbr of cases in Clusters[0..i].
  8376. SmallVector<unsigned, 8> TotalCases(N);
  8377. for (unsigned i = 0; i < N; ++i) {
  8378. const APInt &Hi = Clusters[i].High->getValue();
  8379. const APInt &Lo = Clusters[i].Low->getValue();
  8380. TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
  8381. if (i != 0)
  8382. TotalCases[i] += TotalCases[i - 1];
  8383. }
  8384. // Cheap case: the whole range may be suitable for jump table.
  8385. uint64_t Range = getJumpTableRange(Clusters,0, N - 1);
  8386. uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1);
  8387. assert(NumCases < UINT64_MAX / 100);
  8388. assert(Range >= NumCases);
  8389. if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
  8390. CaseCluster JTCluster;
  8391. if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
  8392. Clusters[0] = JTCluster;
  8393. Clusters.resize(1);
  8394. return;
  8395. }
  8396. }
  8397. // The algorithm below is not suitable for -O0.
  8398. if (TM.getOptLevel() == CodeGenOpt::None)
  8399. return;
  8400. // Split Clusters into minimum number of dense partitions. The algorithm uses
  8401. // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
  8402. // for the Case Statement'" (1994), but builds the MinPartitions array in
  8403. // reverse order to make it easier to reconstruct the partitions in ascending
  8404. // order. In the choice between two optimal partitionings, it picks the one
  8405. // which yields more jump tables.
  8406. // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
  8407. SmallVector<unsigned, 8> MinPartitions(N);
  8408. // LastElement[i] is the last element of the partition starting at i.
  8409. SmallVector<unsigned, 8> LastElement(N);
  8410. // PartitionsScore[i] is used to break ties when choosing between two
  8411. // partitionings resulting in the same number of partitions.
  8412. SmallVector<unsigned, 8> PartitionsScore(N);
  8413. // For PartitionsScore, a small number of comparisons is considered as good as
  8414. // a jump table and a single comparison is considered better than a jump
  8415. // table.
  8416. enum PartitionScores : unsigned {
  8417. NoTable = 0,
  8418. Table = 1,
  8419. FewCases = 1,
  8420. SingleCase = 2
  8421. };
  8422. // Base case: There is only one way to partition Clusters[N-1].
  8423. MinPartitions[N - 1] = 1;
  8424. LastElement[N - 1] = N - 1;
  8425. PartitionsScore[N - 1] = PartitionScores::SingleCase;
  8426. // Note: loop indexes are signed to avoid underflow.
  8427. for (int64_t i = N - 2; i >= 0; i--) {
  8428. // Find optimal partitioning of Clusters[i..N-1].
  8429. // Baseline: Put Clusters[i] into a partition on its own.
  8430. MinPartitions[i] = MinPartitions[i + 1] + 1;
  8431. LastElement[i] = i;
  8432. PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase;
  8433. // Search for a solution that results in fewer partitions.
  8434. for (int64_t j = N - 1; j > i; j--) {
  8435. // Try building a partition from Clusters[i..j].
  8436. uint64_t Range = getJumpTableRange(Clusters, i, j);
  8437. uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j);
  8438. assert(NumCases < UINT64_MAX / 100);
  8439. assert(Range >= NumCases);
  8440. if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
  8441. unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
  8442. unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1];
  8443. int64_t NumEntries = j - i + 1;
  8444. if (NumEntries == 1)
  8445. Score += PartitionScores::SingleCase;
  8446. else if (NumEntries <= SmallNumberOfEntries)
  8447. Score += PartitionScores::FewCases;
  8448. else if (NumEntries >= MinJumpTableEntries)
  8449. Score += PartitionScores::Table;
  8450. // If this leads to fewer partitions, or to the same number of
  8451. // partitions with better score, it is a better partitioning.
  8452. if (NumPartitions < MinPartitions[i] ||
  8453. (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) {
  8454. MinPartitions[i] = NumPartitions;
  8455. LastElement[i] = j;
  8456. PartitionsScore[i] = Score;
  8457. }
  8458. }
  8459. }
  8460. }
  8461. // Iterate over the partitions, replacing some with jump tables in-place.
  8462. unsigned DstIndex = 0;
  8463. for (unsigned First = 0, Last; First < N; First = Last + 1) {
  8464. Last = LastElement[First];
  8465. assert(Last >= First);
  8466. assert(DstIndex <= First);
  8467. unsigned NumClusters = Last - First + 1;
  8468. CaseCluster JTCluster;
  8469. if (NumClusters >= MinJumpTableEntries &&
  8470. buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
  8471. Clusters[DstIndex++] = JTCluster;
  8472. } else {
  8473. for (unsigned I = First; I <= Last; ++I)
  8474. std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
  8475. }
  8476. }
  8477. Clusters.resize(DstIndex);
  8478. }
  8479. bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
  8480. unsigned First, unsigned Last,
  8481. const SwitchInst *SI,
  8482. CaseCluster &BTCluster) {
  8483. assert(First <= Last);
  8484. if (First == Last)
  8485. return false;
  8486. BitVector Dests(FuncInfo.MF->getNumBlockIDs());
  8487. unsigned NumCmps = 0;
  8488. for (int64_t I = First; I <= Last; ++I) {
  8489. assert(Clusters[I].Kind == CC_Range);
  8490. Dests.set(Clusters[I].MBB->getNumber());
  8491. NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
  8492. }
  8493. unsigned NumDests = Dests.count();
  8494. APInt Low = Clusters[First].Low->getValue();
  8495. APInt High = Clusters[Last].High->getValue();
  8496. assert(Low.slt(High));
  8497. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8498. const DataLayout &DL = DAG.getDataLayout();
  8499. if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL))
  8500. return false;
  8501. APInt LowBound;
  8502. APInt CmpRange;
  8503. const int BitWidth = TLI.getPointerTy(DL).getSizeInBits();
  8504. assert(TLI.rangeFitsInWord(Low, High, DL) &&
  8505. "Case range must fit in bit mask!");
  8506. // Check if the clusters cover a contiguous range such that no value in the
  8507. // range will jump to the default statement.
  8508. bool ContiguousRange = true;
  8509. for (int64_t I = First + 1; I <= Last; ++I) {
  8510. if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
  8511. ContiguousRange = false;
  8512. break;
  8513. }
  8514. }
  8515. if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
  8516. // Optimize the case where all the case values fit in a word without having
  8517. // to subtract minValue. In this case, we can optimize away the subtraction.
  8518. LowBound = APInt::getNullValue(Low.getBitWidth());
  8519. CmpRange = High;
  8520. ContiguousRange = false;
  8521. } else {
  8522. LowBound = Low;
  8523. CmpRange = High - Low;
  8524. }
  8525. CaseBitsVector CBV;
  8526. auto TotalProb = BranchProbability::getZero();
  8527. for (unsigned i = First; i <= Last; ++i) {
  8528. // Find the CaseBits for this destination.
  8529. unsigned j;
  8530. for (j = 0; j < CBV.size(); ++j)
  8531. if (CBV[j].BB == Clusters[i].MBB)
  8532. break;
  8533. if (j == CBV.size())
  8534. CBV.push_back(
  8535. CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
  8536. CaseBits *CB = &CBV[j];
  8537. // Update Mask, Bits and ExtraProb.
  8538. uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
  8539. uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
  8540. assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
  8541. CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
  8542. CB->Bits += Hi - Lo + 1;
  8543. CB->ExtraProb += Clusters[i].Prob;
  8544. TotalProb += Clusters[i].Prob;
  8545. }
  8546. BitTestInfo BTI;
  8547. llvm::sort(CBV, [](const CaseBits &a, const CaseBits &b) {
  8548. // Sort by probability first, number of bits second, bit mask third.
  8549. if (a.ExtraProb != b.ExtraProb)
  8550. return a.ExtraProb > b.ExtraProb;
  8551. if (a.Bits != b.Bits)
  8552. return a.Bits > b.Bits;
  8553. return a.Mask < b.Mask;
  8554. });
  8555. for (auto &CB : CBV) {
  8556. MachineBasicBlock *BitTestBB =
  8557. FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
  8558. BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
  8559. }
  8560. BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
  8561. SI->getCondition(), -1U, MVT::Other, false,
  8562. ContiguousRange, nullptr, nullptr, std::move(BTI),
  8563. TotalProb);
  8564. BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
  8565. BitTestCases.size() - 1, TotalProb);
  8566. return true;
  8567. }
  8568. void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
  8569. const SwitchInst *SI) {
  8570. // Partition Clusters into as few subsets as possible, where each subset has a
  8571. // range that fits in a machine word and has <= 3 unique destinations.
  8572. #ifndef NDEBUG
  8573. // Clusters must be sorted and contain Range or JumpTable clusters.
  8574. assert(!Clusters.empty());
  8575. assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
  8576. for (const CaseCluster &C : Clusters)
  8577. assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
  8578. for (unsigned i = 1; i < Clusters.size(); ++i)
  8579. assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
  8580. #endif
  8581. // The algorithm below is not suitable for -O0.
  8582. if (TM.getOptLevel() == CodeGenOpt::None)
  8583. return;
  8584. // If target does not have legal shift left, do not emit bit tests at all.
  8585. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8586. const DataLayout &DL = DAG.getDataLayout();
  8587. EVT PTy = TLI.getPointerTy(DL);
  8588. if (!TLI.isOperationLegal(ISD::SHL, PTy))
  8589. return;
  8590. int BitWidth = PTy.getSizeInBits();
  8591. const int64_t N = Clusters.size();
  8592. // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
  8593. SmallVector<unsigned, 8> MinPartitions(N);
  8594. // LastElement[i] is the last element of the partition starting at i.
  8595. SmallVector<unsigned, 8> LastElement(N);
  8596. // FIXME: This might not be the best algorithm for finding bit test clusters.
  8597. // Base case: There is only one way to partition Clusters[N-1].
  8598. MinPartitions[N - 1] = 1;
  8599. LastElement[N - 1] = N - 1;
  8600. // Note: loop indexes are signed to avoid underflow.
  8601. for (int64_t i = N - 2; i >= 0; --i) {
  8602. // Find optimal partitioning of Clusters[i..N-1].
  8603. // Baseline: Put Clusters[i] into a partition on its own.
  8604. MinPartitions[i] = MinPartitions[i + 1] + 1;
  8605. LastElement[i] = i;
  8606. // Search for a solution that results in fewer partitions.
  8607. // Note: the search is limited by BitWidth, reducing time complexity.
  8608. for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
  8609. // Try building a partition from Clusters[i..j].
  8610. // Check the range.
  8611. if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(),
  8612. Clusters[j].High->getValue(), DL))
  8613. continue;
  8614. // Check nbr of destinations and cluster types.
  8615. // FIXME: This works, but doesn't seem very efficient.
  8616. bool RangesOnly = true;
  8617. BitVector Dests(FuncInfo.MF->getNumBlockIDs());
  8618. for (int64_t k = i; k <= j; k++) {
  8619. if (Clusters[k].Kind != CC_Range) {
  8620. RangesOnly = false;
  8621. break;
  8622. }
  8623. Dests.set(Clusters[k].MBB->getNumber());
  8624. }
  8625. if (!RangesOnly || Dests.count() > 3)
  8626. break;
  8627. // Check if it's a better partition.
  8628. unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
  8629. if (NumPartitions < MinPartitions[i]) {
  8630. // Found a better partition.
  8631. MinPartitions[i] = NumPartitions;
  8632. LastElement[i] = j;
  8633. }
  8634. }
  8635. }
  8636. // Iterate over the partitions, replacing with bit-test clusters in-place.
  8637. unsigned DstIndex = 0;
  8638. for (unsigned First = 0, Last; First < N; First = Last + 1) {
  8639. Last = LastElement[First];
  8640. assert(First <= Last);
  8641. assert(DstIndex <= First);
  8642. CaseCluster BitTestCluster;
  8643. if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
  8644. Clusters[DstIndex++] = BitTestCluster;
  8645. } else {
  8646. size_t NumClusters = Last - First + 1;
  8647. std::memmove(&Clusters[DstIndex], &Clusters[First],
  8648. sizeof(Clusters[0]) * NumClusters);
  8649. DstIndex += NumClusters;
  8650. }
  8651. }
  8652. Clusters.resize(DstIndex);
  8653. }
  8654. void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
  8655. MachineBasicBlock *SwitchMBB,
  8656. MachineBasicBlock *DefaultMBB) {
  8657. MachineFunction *CurMF = FuncInfo.MF;
  8658. MachineBasicBlock *NextMBB = nullptr;
  8659. MachineFunction::iterator BBI(W.MBB);
  8660. if (++BBI != FuncInfo.MF->end())
  8661. NextMBB = &*BBI;
  8662. unsigned Size = W.LastCluster - W.FirstCluster + 1;
  8663. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  8664. if (Size == 2 && W.MBB == SwitchMBB) {
  8665. // If any two of the cases has the same destination, and if one value
  8666. // is the same as the other, but has one bit unset that the other has set,
  8667. // use bit manipulation to do two compares at once. For example:
  8668. // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
  8669. // TODO: This could be extended to merge any 2 cases in switches with 3
  8670. // cases.
  8671. // TODO: Handle cases where W.CaseBB != SwitchBB.
  8672. CaseCluster &Small = *W.FirstCluster;
  8673. CaseCluster &Big = *W.LastCluster;
  8674. if (Small.Low == Small.High && Big.Low == Big.High &&
  8675. Small.MBB == Big.MBB) {
  8676. const APInt &SmallValue = Small.Low->getValue();
  8677. const APInt &BigValue = Big.Low->getValue();
  8678. // Check that there is only one bit different.
  8679. APInt CommonBit = BigValue ^ SmallValue;
  8680. if (CommonBit.isPowerOf2()) {
  8681. SDValue CondLHS = getValue(Cond);
  8682. EVT VT = CondLHS.getValueType();
  8683. SDLoc DL = getCurSDLoc();
  8684. SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
  8685. DAG.getConstant(CommonBit, DL, VT));
  8686. SDValue Cond = DAG.getSetCC(
  8687. DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
  8688. ISD::SETEQ);
  8689. // Update successor info.
  8690. // Both Small and Big will jump to Small.BB, so we sum up the
  8691. // probabilities.
  8692. addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
  8693. if (BPI)
  8694. addSuccessorWithProb(
  8695. SwitchMBB, DefaultMBB,
  8696. // The default destination is the first successor in IR.
  8697. BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
  8698. else
  8699. addSuccessorWithProb(SwitchMBB, DefaultMBB);
  8700. // Insert the true branch.
  8701. SDValue BrCond =
  8702. DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
  8703. DAG.getBasicBlock(Small.MBB));
  8704. // Insert the false branch.
  8705. BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
  8706. DAG.getBasicBlock(DefaultMBB));
  8707. DAG.setRoot(BrCond);
  8708. return;
  8709. }
  8710. }
  8711. }
  8712. if (TM.getOptLevel() != CodeGenOpt::None) {
  8713. // Here, we order cases by probability so the most likely case will be
  8714. // checked first. However, two clusters can have the same probability in
  8715. // which case their relative ordering is non-deterministic. So we use Low
  8716. // as a tie-breaker as clusters are guaranteed to never overlap.
  8717. llvm::sort(W.FirstCluster, W.LastCluster + 1,
  8718. [](const CaseCluster &a, const CaseCluster &b) {
  8719. return a.Prob != b.Prob ?
  8720. a.Prob > b.Prob :
  8721. a.Low->getValue().slt(b.Low->getValue());
  8722. });
  8723. // Rearrange the case blocks so that the last one falls through if possible
  8724. // without changing the order of probabilities.
  8725. for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
  8726. --I;
  8727. if (I->Prob > W.LastCluster->Prob)
  8728. break;
  8729. if (I->Kind == CC_Range && I->MBB == NextMBB) {
  8730. std::swap(*I, *W.LastCluster);
  8731. break;
  8732. }
  8733. }
  8734. }
  8735. // Compute total probability.
  8736. BranchProbability DefaultProb = W.DefaultProb;
  8737. BranchProbability UnhandledProbs = DefaultProb;
  8738. for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
  8739. UnhandledProbs += I->Prob;
  8740. MachineBasicBlock *CurMBB = W.MBB;
  8741. for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
  8742. MachineBasicBlock *Fallthrough;
  8743. if (I == W.LastCluster) {
  8744. // For the last cluster, fall through to the default destination.
  8745. Fallthrough = DefaultMBB;
  8746. } else {
  8747. Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
  8748. CurMF->insert(BBI, Fallthrough);
  8749. // Put Cond in a virtual register to make it available from the new blocks.
  8750. ExportFromCurrentBlock(Cond);
  8751. }
  8752. UnhandledProbs -= I->Prob;
  8753. switch (I->Kind) {
  8754. case CC_JumpTable: {
  8755. // FIXME: Optimize away range check based on pivot comparisons.
  8756. JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
  8757. JumpTable *JT = &JTCases[I->JTCasesIndex].second;
  8758. // The jump block hasn't been inserted yet; insert it here.
  8759. MachineBasicBlock *JumpMBB = JT->MBB;
  8760. CurMF->insert(BBI, JumpMBB);
  8761. auto JumpProb = I->Prob;
  8762. auto FallthroughProb = UnhandledProbs;
  8763. // If the default statement is a target of the jump table, we evenly
  8764. // distribute the default probability to successors of CurMBB. Also
  8765. // update the probability on the edge from JumpMBB to Fallthrough.
  8766. for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
  8767. SE = JumpMBB->succ_end();
  8768. SI != SE; ++SI) {
  8769. if (*SI == DefaultMBB) {
  8770. JumpProb += DefaultProb / 2;
  8771. FallthroughProb -= DefaultProb / 2;
  8772. JumpMBB->setSuccProbability(SI, DefaultProb / 2);
  8773. JumpMBB->normalizeSuccProbs();
  8774. break;
  8775. }
  8776. }
  8777. addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
  8778. addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
  8779. CurMBB->normalizeSuccProbs();
  8780. // The jump table header will be inserted in our current block, do the
  8781. // range check, and fall through to our fallthrough block.
  8782. JTH->HeaderBB = CurMBB;
  8783. JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
  8784. // If we're in the right place, emit the jump table header right now.
  8785. if (CurMBB == SwitchMBB) {
  8786. visitJumpTableHeader(*JT, *JTH, SwitchMBB);
  8787. JTH->Emitted = true;
  8788. }
  8789. break;
  8790. }
  8791. case CC_BitTests: {
  8792. // FIXME: Optimize away range check based on pivot comparisons.
  8793. BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
  8794. // The bit test blocks haven't been inserted yet; insert them here.
  8795. for (BitTestCase &BTC : BTB->Cases)
  8796. CurMF->insert(BBI, BTC.ThisBB);
  8797. // Fill in fields of the BitTestBlock.
  8798. BTB->Parent = CurMBB;
  8799. BTB->Default = Fallthrough;
  8800. BTB->DefaultProb = UnhandledProbs;
  8801. // If the cases in bit test don't form a contiguous range, we evenly
  8802. // distribute the probability on the edge to Fallthrough to two
  8803. // successors of CurMBB.
  8804. if (!BTB->ContiguousRange) {
  8805. BTB->Prob += DefaultProb / 2;
  8806. BTB->DefaultProb -= DefaultProb / 2;
  8807. }
  8808. // If we're in the right place, emit the bit test header right now.
  8809. if (CurMBB == SwitchMBB) {
  8810. visitBitTestHeader(*BTB, SwitchMBB);
  8811. BTB->Emitted = true;
  8812. }
  8813. break;
  8814. }
  8815. case CC_Range: {
  8816. const Value *RHS, *LHS, *MHS;
  8817. ISD::CondCode CC;
  8818. if (I->Low == I->High) {
  8819. // Check Cond == I->Low.
  8820. CC = ISD::SETEQ;
  8821. LHS = Cond;
  8822. RHS=I->Low;
  8823. MHS = nullptr;
  8824. } else {
  8825. // Check I->Low <= Cond <= I->High.
  8826. CC = ISD::SETLE;
  8827. LHS = I->Low;
  8828. MHS = Cond;
  8829. RHS = I->High;
  8830. }
  8831. // The false probability is the sum of all unhandled cases.
  8832. CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
  8833. getCurSDLoc(), I->Prob, UnhandledProbs);
  8834. if (CurMBB == SwitchMBB)
  8835. visitSwitchCase(CB, SwitchMBB);
  8836. else
  8837. SwitchCases.push_back(CB);
  8838. break;
  8839. }
  8840. }
  8841. CurMBB = Fallthrough;
  8842. }
  8843. }
  8844. unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
  8845. CaseClusterIt First,
  8846. CaseClusterIt Last) {
  8847. return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
  8848. if (X.Prob != CC.Prob)
  8849. return X.Prob > CC.Prob;
  8850. // Ties are broken by comparing the case value.
  8851. return X.Low->getValue().slt(CC.Low->getValue());
  8852. });
  8853. }
  8854. void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
  8855. const SwitchWorkListItem &W,
  8856. Value *Cond,
  8857. MachineBasicBlock *SwitchMBB) {
  8858. assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
  8859. "Clusters not sorted?");
  8860. assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
  8861. // Balance the tree based on branch probabilities to create a near-optimal (in
  8862. // terms of search time given key frequency) binary search tree. See e.g. Kurt
  8863. // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
  8864. CaseClusterIt LastLeft = W.FirstCluster;
  8865. CaseClusterIt FirstRight = W.LastCluster;
  8866. auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
  8867. auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
  8868. // Move LastLeft and FirstRight towards each other from opposite directions to
  8869. // find a partitioning of the clusters which balances the probability on both
  8870. // sides. If LeftProb and RightProb are equal, alternate which side is
  8871. // taken to ensure 0-probability nodes are distributed evenly.
  8872. unsigned I = 0;
  8873. while (LastLeft + 1 < FirstRight) {
  8874. if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
  8875. LeftProb += (++LastLeft)->Prob;
  8876. else
  8877. RightProb += (--FirstRight)->Prob;
  8878. I++;
  8879. }
  8880. while (true) {
  8881. // Our binary search tree differs from a typical BST in that ours can have up
  8882. // to three values in each leaf. The pivot selection above doesn't take that
  8883. // into account, which means the tree might require more nodes and be less
  8884. // efficient. We compensate for this here.
  8885. unsigned NumLeft = LastLeft - W.FirstCluster + 1;
  8886. unsigned NumRight = W.LastCluster - FirstRight + 1;
  8887. if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
  8888. // If one side has less than 3 clusters, and the other has more than 3,
  8889. // consider taking a cluster from the other side.
  8890. if (NumLeft < NumRight) {
  8891. // Consider moving the first cluster on the right to the left side.
  8892. CaseCluster &CC = *FirstRight;
  8893. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  8894. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  8895. if (LeftSideRank <= RightSideRank) {
  8896. // Moving the cluster to the left does not demote it.
  8897. ++LastLeft;
  8898. ++FirstRight;
  8899. continue;
  8900. }
  8901. } else {
  8902. assert(NumRight < NumLeft);
  8903. // Consider moving the last element on the left to the right side.
  8904. CaseCluster &CC = *LastLeft;
  8905. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  8906. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  8907. if (RightSideRank <= LeftSideRank) {
  8908. // Moving the cluster to the right does not demot it.
  8909. --LastLeft;
  8910. --FirstRight;
  8911. continue;
  8912. }
  8913. }
  8914. }
  8915. break;
  8916. }
  8917. assert(LastLeft + 1 == FirstRight);
  8918. assert(LastLeft >= W.FirstCluster);
  8919. assert(FirstRight <= W.LastCluster);
  8920. // Use the first element on the right as pivot since we will make less-than
  8921. // comparisons against it.
  8922. CaseClusterIt PivotCluster = FirstRight;
  8923. assert(PivotCluster > W.FirstCluster);
  8924. assert(PivotCluster <= W.LastCluster);
  8925. CaseClusterIt FirstLeft = W.FirstCluster;
  8926. CaseClusterIt LastRight = W.LastCluster;
  8927. const ConstantInt *Pivot = PivotCluster->Low;
  8928. // New blocks will be inserted immediately after the current one.
  8929. MachineFunction::iterator BBI(W.MBB);
  8930. ++BBI;
  8931. // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
  8932. // we can branch to its destination directly if it's squeezed exactly in
  8933. // between the known lower bound and Pivot - 1.
  8934. MachineBasicBlock *LeftMBB;
  8935. if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
  8936. FirstLeft->Low == W.GE &&
  8937. (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
  8938. LeftMBB = FirstLeft->MBB;
  8939. } else {
  8940. LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  8941. FuncInfo.MF->insert(BBI, LeftMBB);
  8942. WorkList.push_back(
  8943. {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
  8944. // Put Cond in a virtual register to make it available from the new blocks.
  8945. ExportFromCurrentBlock(Cond);
  8946. }
  8947. // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
  8948. // single cluster, RHS.Low == Pivot, and we can branch to its destination
  8949. // directly if RHS.High equals the current upper bound.
  8950. MachineBasicBlock *RightMBB;
  8951. if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
  8952. W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
  8953. RightMBB = FirstRight->MBB;
  8954. } else {
  8955. RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  8956. FuncInfo.MF->insert(BBI, RightMBB);
  8957. WorkList.push_back(
  8958. {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
  8959. // Put Cond in a virtual register to make it available from the new blocks.
  8960. ExportFromCurrentBlock(Cond);
  8961. }
  8962. // Create the CaseBlock record that will be used to lower the branch.
  8963. CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
  8964. getCurSDLoc(), LeftProb, RightProb);
  8965. if (W.MBB == SwitchMBB)
  8966. visitSwitchCase(CB, SwitchMBB);
  8967. else
  8968. SwitchCases.push_back(CB);
  8969. }
  8970. // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
  8971. // from the swith statement.
  8972. static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
  8973. BranchProbability PeeledCaseProb) {
  8974. if (PeeledCaseProb == BranchProbability::getOne())
  8975. return BranchProbability::getZero();
  8976. BranchProbability SwitchProb = PeeledCaseProb.getCompl();
  8977. uint32_t Numerator = CaseProb.getNumerator();
  8978. uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
  8979. return BranchProbability(Numerator, std::max(Numerator, Denominator));
  8980. }
  8981. // Try to peel the top probability case if it exceeds the threshold.
  8982. // Return current MachineBasicBlock for the switch statement if the peeling
  8983. // does not occur.
  8984. // If the peeling is performed, return the newly created MachineBasicBlock
  8985. // for the peeled switch statement. Also update Clusters to remove the peeled
  8986. // case. PeeledCaseProb is the BranchProbability for the peeled case.
  8987. MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
  8988. const SwitchInst &SI, CaseClusterVector &Clusters,
  8989. BranchProbability &PeeledCaseProb) {
  8990. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  8991. // Don't perform if there is only one cluster or optimizing for size.
  8992. if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
  8993. TM.getOptLevel() == CodeGenOpt::None ||
  8994. SwitchMBB->getParent()->getFunction().optForMinSize())
  8995. return SwitchMBB;
  8996. BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
  8997. unsigned PeeledCaseIndex = 0;
  8998. bool SwitchPeeled = false;
  8999. for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
  9000. CaseCluster &CC = Clusters[Index];
  9001. if (CC.Prob < TopCaseProb)
  9002. continue;
  9003. TopCaseProb = CC.Prob;
  9004. PeeledCaseIndex = Index;
  9005. SwitchPeeled = true;
  9006. }
  9007. if (!SwitchPeeled)
  9008. return SwitchMBB;
  9009. LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
  9010. << TopCaseProb << "\n");
  9011. // Record the MBB for the peeled switch statement.
  9012. MachineFunction::iterator BBI(SwitchMBB);
  9013. ++BBI;
  9014. MachineBasicBlock *PeeledSwitchMBB =
  9015. FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
  9016. FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
  9017. ExportFromCurrentBlock(SI.getCondition());
  9018. auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
  9019. SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
  9020. nullptr, nullptr, TopCaseProb.getCompl()};
  9021. lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
  9022. Clusters.erase(PeeledCaseIt);
  9023. for (CaseCluster &CC : Clusters) {
  9024. LLVM_DEBUG(
  9025. dbgs() << "Scale the probablity for one cluster, before scaling: "
  9026. << CC.Prob << "\n");
  9027. CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
  9028. LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
  9029. }
  9030. PeeledCaseProb = TopCaseProb;
  9031. return PeeledSwitchMBB;
  9032. }
  9033. void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
  9034. // Extract cases from the switch.
  9035. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  9036. CaseClusterVector Clusters;
  9037. Clusters.reserve(SI.getNumCases());
  9038. for (auto I : SI.cases()) {
  9039. MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
  9040. const ConstantInt *CaseVal = I.getCaseValue();
  9041. BranchProbability Prob =
  9042. BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
  9043. : BranchProbability(1, SI.getNumCases() + 1);
  9044. Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
  9045. }
  9046. MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
  9047. // Cluster adjacent cases with the same destination. We do this at all
  9048. // optimization levels because it's cheap to do and will make codegen faster
  9049. // if there are many clusters.
  9050. sortAndRangeify(Clusters);
  9051. if (TM.getOptLevel() != CodeGenOpt::None) {
  9052. // Replace an unreachable default with the most popular destination.
  9053. // FIXME: Exploit unreachable default more aggressively.
  9054. bool UnreachableDefault =
  9055. isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg());
  9056. if (UnreachableDefault && !Clusters.empty()) {
  9057. DenseMap<const BasicBlock *, unsigned> Popularity;
  9058. unsigned MaxPop = 0;
  9059. const BasicBlock *MaxBB = nullptr;
  9060. for (auto I : SI.cases()) {
  9061. const BasicBlock *BB = I.getCaseSuccessor();
  9062. if (++Popularity[BB] > MaxPop) {
  9063. MaxPop = Popularity[BB];
  9064. MaxBB = BB;
  9065. }
  9066. }
  9067. // Set new default.
  9068. assert(MaxPop > 0 && MaxBB);
  9069. DefaultMBB = FuncInfo.MBBMap[MaxBB];
  9070. // Remove cases that were pointing to the destination that is now the
  9071. // default.
  9072. CaseClusterVector New;
  9073. New.reserve(Clusters.size());
  9074. for (CaseCluster &CC : Clusters) {
  9075. if (CC.MBB != DefaultMBB)
  9076. New.push_back(CC);
  9077. }
  9078. Clusters = std::move(New);
  9079. }
  9080. }
  9081. // The branch probablity of the peeled case.
  9082. BranchProbability PeeledCaseProb = BranchProbability::getZero();
  9083. MachineBasicBlock *PeeledSwitchMBB =
  9084. peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
  9085. // If there is only the default destination, jump there directly.
  9086. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  9087. if (Clusters.empty()) {
  9088. assert(PeeledSwitchMBB == SwitchMBB);
  9089. SwitchMBB->addSuccessor(DefaultMBB);
  9090. if (DefaultMBB != NextBlock(SwitchMBB)) {
  9091. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  9092. getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
  9093. }
  9094. return;
  9095. }
  9096. findJumpTables(Clusters, &SI, DefaultMBB);
  9097. findBitTestClusters(Clusters, &SI);
  9098. LLVM_DEBUG({
  9099. dbgs() << "Case clusters: ";
  9100. for (const CaseCluster &C : Clusters) {
  9101. if (C.Kind == CC_JumpTable)
  9102. dbgs() << "JT:";
  9103. if (C.Kind == CC_BitTests)
  9104. dbgs() << "BT:";
  9105. C.Low->getValue().print(dbgs(), true);
  9106. if (C.Low != C.High) {
  9107. dbgs() << '-';
  9108. C.High->getValue().print(dbgs(), true);
  9109. }
  9110. dbgs() << ' ';
  9111. }
  9112. dbgs() << '\n';
  9113. });
  9114. assert(!Clusters.empty());
  9115. SwitchWorkList WorkList;
  9116. CaseClusterIt First = Clusters.begin();
  9117. CaseClusterIt Last = Clusters.end() - 1;
  9118. auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
  9119. // Scale the branchprobability for DefaultMBB if the peel occurs and
  9120. // DefaultMBB is not replaced.
  9121. if (PeeledCaseProb != BranchProbability::getZero() &&
  9122. DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
  9123. DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
  9124. WorkList.push_back(
  9125. {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
  9126. while (!WorkList.empty()) {
  9127. SwitchWorkListItem W = WorkList.back();
  9128. WorkList.pop_back();
  9129. unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
  9130. if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
  9131. !DefaultMBB->getParent()->getFunction().optForMinSize()) {
  9132. // For optimized builds, lower large range as a balanced binary tree.
  9133. splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
  9134. continue;
  9135. }
  9136. lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
  9137. }
  9138. }