SelectionDAGBuilder.cpp 388 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029
  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 "llvm/ADT/APFloat.h"
  15. #include "llvm/ADT/APInt.h"
  16. #include "llvm/ADT/ArrayRef.h"
  17. #include "llvm/ADT/BitVector.h"
  18. #include "llvm/ADT/DenseMap.h"
  19. #include "llvm/ADT/None.h"
  20. #include "llvm/ADT/Optional.h"
  21. #include "llvm/ADT/STLExtras.h"
  22. #include "llvm/ADT/SmallPtrSet.h"
  23. #include "llvm/ADT/SmallSet.h"
  24. #include "llvm/ADT/SmallVector.h"
  25. #include "llvm/ADT/StringRef.h"
  26. #include "llvm/ADT/Triple.h"
  27. #include "llvm/ADT/Twine.h"
  28. #include "llvm/Analysis/AliasAnalysis.h"
  29. #include "llvm/Analysis/BranchProbabilityInfo.h"
  30. #include "llvm/Analysis/ConstantFolding.h"
  31. #include "llvm/Analysis/EHPersonalities.h"
  32. #include "llvm/Analysis/Loads.h"
  33. #include "llvm/Analysis/MemoryLocation.h"
  34. #include "llvm/Analysis/TargetLibraryInfo.h"
  35. #include "llvm/Analysis/ValueTracking.h"
  36. #include "llvm/Analysis/VectorUtils.h"
  37. #include "llvm/CodeGen/Analysis.h"
  38. #include "llvm/CodeGen/FunctionLoweringInfo.h"
  39. #include "llvm/CodeGen/GCMetadata.h"
  40. #include "llvm/CodeGen/ISDOpcodes.h"
  41. #include "llvm/CodeGen/MachineBasicBlock.h"
  42. #include "llvm/CodeGen/MachineFrameInfo.h"
  43. #include "llvm/CodeGen/MachineFunction.h"
  44. #include "llvm/CodeGen/MachineInstr.h"
  45. #include "llvm/CodeGen/MachineInstrBuilder.h"
  46. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  47. #include "llvm/CodeGen/MachineMemOperand.h"
  48. #include "llvm/CodeGen/MachineModuleInfo.h"
  49. #include "llvm/CodeGen/MachineOperand.h"
  50. #include "llvm/CodeGen/MachineRegisterInfo.h"
  51. #include "llvm/CodeGen/MachineValueType.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/MathExtras.h"
  105. #include "llvm/Support/raw_ostream.h"
  106. #include "llvm/Target/TargetIntrinsicInfo.h"
  107. #include "llvm/Target/TargetMachine.h"
  108. #include "llvm/Target/TargetOptions.h"
  109. #include <algorithm>
  110. #include <cassert>
  111. #include <cstddef>
  112. #include <cstdint>
  113. #include <cstring>
  114. #include <iterator>
  115. #include <limits>
  116. #include <numeric>
  117. #include <tuple>
  118. #include <utility>
  119. #include <vector>
  120. using namespace llvm;
  121. #define DEBUG_TYPE "isel"
  122. /// LimitFloatPrecision - Generate low-precision inline sequences for
  123. /// some float libcalls (6, 8 or 12 bits).
  124. static unsigned LimitFloatPrecision;
  125. static cl::opt<unsigned, true>
  126. LimitFPPrecision("limit-float-precision",
  127. cl::desc("Generate low-precision inline sequences "
  128. "for some float libcalls"),
  129. cl::location(LimitFloatPrecision), cl::Hidden,
  130. cl::init(0));
  131. static cl::opt<unsigned> SwitchPeelThreshold(
  132. "switch-peel-threshold", cl::Hidden, cl::init(66),
  133. cl::desc("Set the case probability threshold for peeling the case from a "
  134. "switch statement. A value greater than 100 will void this "
  135. "optimization"));
  136. // Limit the width of DAG chains. This is important in general to prevent
  137. // DAG-based analysis from blowing up. For example, alias analysis and
  138. // load clustering may not complete in reasonable time. It is difficult to
  139. // recognize and avoid this situation within each individual analysis, and
  140. // future analyses are likely to have the same behavior. Limiting DAG width is
  141. // the safe approach and will be especially important with global DAGs.
  142. //
  143. // MaxParallelChains default is arbitrarily high to avoid affecting
  144. // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
  145. // sequence over this should have been converted to llvm.memcpy by the
  146. // frontend. It is easy to induce this behavior with .ll code such as:
  147. // %buffer = alloca [4096 x i8]
  148. // %data = load [4096 x i8]* %argPtr
  149. // store [4096 x i8] %data, [4096 x i8]* %buffer
  150. static const unsigned MaxParallelChains = 64;
  151. // True if the Value passed requires ABI mangling as it is a parameter to a
  152. // function or a return value from a function which is not an intrinsic.
  153. static bool isABIRegCopy(const Value *V) {
  154. const bool IsRetInst = V && isa<ReturnInst>(V);
  155. const bool IsCallInst = V && isa<CallInst>(V);
  156. const bool IsInLineAsm =
  157. IsCallInst && static_cast<const CallInst *>(V)->isInlineAsm();
  158. const bool IsIndirectFunctionCall =
  159. IsCallInst && !IsInLineAsm &&
  160. !static_cast<const CallInst *>(V)->getCalledFunction();
  161. // It is possible that the call instruction is an inline asm statement or an
  162. // indirect function call in which case the return value of
  163. // getCalledFunction() would be nullptr.
  164. const bool IsInstrinsicCall =
  165. IsCallInst && !IsInLineAsm && !IsIndirectFunctionCall &&
  166. static_cast<const CallInst *>(V)->getCalledFunction()->getIntrinsicID() !=
  167. Intrinsic::not_intrinsic;
  168. return IsRetInst || (IsCallInst && (!IsInLineAsm && !IsInstrinsicCall));
  169. }
  170. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  171. const SDValue *Parts, unsigned NumParts,
  172. MVT PartVT, EVT ValueVT, const Value *V,
  173. bool IsABIRegCopy);
  174. /// getCopyFromParts - Create a value that contains the specified legal parts
  175. /// combined into the value they represent. If the parts combine to a type
  176. /// larger than ValueVT then AssertOp can be used to specify whether the extra
  177. /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
  178. /// (ISD::AssertSext).
  179. static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
  180. const SDValue *Parts, unsigned NumParts,
  181. MVT PartVT, EVT ValueVT, const Value *V,
  182. Optional<ISD::NodeType> AssertOp = None,
  183. bool IsABIRegCopy = false) {
  184. if (ValueVT.isVector())
  185. return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
  186. PartVT, ValueVT, V, IsABIRegCopy);
  187. assert(NumParts > 0 && "No parts to assemble!");
  188. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  189. SDValue Val = Parts[0];
  190. if (NumParts > 1) {
  191. // Assemble the value from multiple parts.
  192. if (ValueVT.isInteger()) {
  193. unsigned PartBits = PartVT.getSizeInBits();
  194. unsigned ValueBits = ValueVT.getSizeInBits();
  195. // Assemble the power of 2 part.
  196. unsigned RoundParts = NumParts & (NumParts - 1) ?
  197. 1 << Log2_32(NumParts) : NumParts;
  198. unsigned RoundBits = PartBits * RoundParts;
  199. EVT RoundVT = RoundBits == ValueBits ?
  200. ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
  201. SDValue Lo, Hi;
  202. EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
  203. if (RoundParts > 2) {
  204. Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
  205. PartVT, HalfVT, V);
  206. Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
  207. RoundParts / 2, PartVT, HalfVT, V);
  208. } else {
  209. Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
  210. Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
  211. }
  212. if (DAG.getDataLayout().isBigEndian())
  213. std::swap(Lo, Hi);
  214. Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
  215. if (RoundParts < NumParts) {
  216. // Assemble the trailing non-power-of-2 part.
  217. unsigned OddParts = NumParts - RoundParts;
  218. EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
  219. Hi = getCopyFromParts(DAG, DL,
  220. Parts + RoundParts, OddParts, PartVT, OddVT, V);
  221. // Combine the round and odd parts.
  222. Lo = Val;
  223. if (DAG.getDataLayout().isBigEndian())
  224. std::swap(Lo, Hi);
  225. EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  226. Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
  227. Hi =
  228. DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
  229. DAG.getConstant(Lo.getValueSizeInBits(), DL,
  230. TLI.getPointerTy(DAG.getDataLayout())));
  231. Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
  232. Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
  233. }
  234. } else if (PartVT.isFloatingPoint()) {
  235. // FP split into multiple FP parts (for ppcf128)
  236. assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
  237. "Unexpected split");
  238. SDValue Lo, Hi;
  239. Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
  240. Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
  241. if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
  242. std::swap(Lo, Hi);
  243. Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
  244. } else {
  245. // FP split into integer parts (soft fp)
  246. assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
  247. !PartVT.isVector() && "Unexpected split");
  248. EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  249. Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
  250. }
  251. }
  252. // There is now one part, held in Val. Correct it to match ValueVT.
  253. // PartEVT is the type of the register class that holds the value.
  254. // ValueVT is the type of the inline asm operation.
  255. EVT PartEVT = Val.getValueType();
  256. if (PartEVT == ValueVT)
  257. return Val;
  258. if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
  259. ValueVT.bitsLT(PartEVT)) {
  260. // For an FP value in an integer part, we need to truncate to the right
  261. // width first.
  262. PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  263. Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
  264. }
  265. // Handle types that have the same size.
  266. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
  267. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  268. // Handle types with different sizes.
  269. if (PartEVT.isInteger() && ValueVT.isInteger()) {
  270. if (ValueVT.bitsLT(PartEVT)) {
  271. // For a truncate, see if we have any information to
  272. // indicate whether the truncated bits will always be
  273. // zero or sign-extension.
  274. if (AssertOp.hasValue())
  275. Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
  276. DAG.getValueType(ValueVT));
  277. return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  278. }
  279. return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
  280. }
  281. if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  282. // FP_ROUND's are always exact here.
  283. if (ValueVT.bitsLT(Val.getValueType()))
  284. return DAG.getNode(
  285. ISD::FP_ROUND, DL, ValueVT, Val,
  286. DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
  287. return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
  288. }
  289. llvm_unreachable("Unknown mismatch!");
  290. }
  291. static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
  292. const Twine &ErrMsg) {
  293. const Instruction *I = dyn_cast_or_null<Instruction>(V);
  294. if (!V)
  295. return Ctx.emitError(ErrMsg);
  296. const char *AsmError = ", possible invalid constraint for vector type";
  297. if (const CallInst *CI = dyn_cast<CallInst>(I))
  298. if (isa<InlineAsm>(CI->getCalledValue()))
  299. return Ctx.emitError(I, ErrMsg + AsmError);
  300. return Ctx.emitError(I, ErrMsg);
  301. }
  302. /// getCopyFromPartsVector - Create a value that contains the specified legal
  303. /// parts combined into the value they represent. If the parts combine to a
  304. /// type larger than ValueVT then AssertOp can be used to specify whether the
  305. /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
  306. /// ValueVT (ISD::AssertSext).
  307. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  308. const SDValue *Parts, unsigned NumParts,
  309. MVT PartVT, EVT ValueVT, const Value *V,
  310. bool IsABIRegCopy) {
  311. assert(ValueVT.isVector() && "Not a vector value");
  312. assert(NumParts > 0 && "No parts to assemble!");
  313. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  314. SDValue Val = Parts[0];
  315. // Handle a multi-element vector.
  316. if (NumParts > 1) {
  317. EVT IntermediateVT;
  318. MVT RegisterVT;
  319. unsigned NumIntermediates;
  320. unsigned NumRegs;
  321. if (IsABIRegCopy) {
  322. NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
  323. *DAG.getContext(), ValueVT, IntermediateVT, NumIntermediates,
  324. RegisterVT);
  325. } else {
  326. NumRegs =
  327. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  328. NumIntermediates, RegisterVT);
  329. }
  330. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  331. NumParts = NumRegs; // Silence a compiler warning.
  332. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  333. assert(RegisterVT.getSizeInBits() ==
  334. Parts[0].getSimpleValueType().getSizeInBits() &&
  335. "Part type sizes don't match!");
  336. // Assemble the parts into intermediate operands.
  337. SmallVector<SDValue, 8> Ops(NumIntermediates);
  338. if (NumIntermediates == NumParts) {
  339. // If the register was not expanded, truncate or copy the value,
  340. // as appropriate.
  341. for (unsigned i = 0; i != NumParts; ++i)
  342. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
  343. PartVT, IntermediateVT, V);
  344. } else if (NumParts > 0) {
  345. // If the intermediate type was expanded, build the intermediate
  346. // operands from the parts.
  347. assert(NumParts % NumIntermediates == 0 &&
  348. "Must expand into a divisible number of parts!");
  349. unsigned Factor = NumParts / NumIntermediates;
  350. for (unsigned i = 0; i != NumIntermediates; ++i)
  351. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
  352. PartVT, IntermediateVT, V);
  353. }
  354. // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
  355. // intermediate operands.
  356. EVT BuiltVectorTy =
  357. EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
  358. (IntermediateVT.isVector()
  359. ? IntermediateVT.getVectorNumElements() * NumParts
  360. : NumIntermediates));
  361. Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
  362. : ISD::BUILD_VECTOR,
  363. DL, BuiltVectorTy, Ops);
  364. }
  365. // There is now one part, held in Val. Correct it to match ValueVT.
  366. EVT PartEVT = Val.getValueType();
  367. if (PartEVT == ValueVT)
  368. return Val;
  369. if (PartEVT.isVector()) {
  370. // If the element type of the source/dest vectors are the same, but the
  371. // parts vector has more elements than the value vector, then we have a
  372. // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
  373. // elements we want.
  374. if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
  375. assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
  376. "Cannot narrow, it would be a lossy transformation");
  377. return DAG.getNode(
  378. ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
  379. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  380. }
  381. // Vector/Vector bitcast.
  382. if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
  383. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  384. assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
  385. "Cannot handle this kind of promotion");
  386. // Promoted vector extract
  387. return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
  388. }
  389. // Trivial bitcast if the types are the same size and the destination
  390. // vector type is legal.
  391. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
  392. TLI.isTypeLegal(ValueVT))
  393. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  394. if (ValueVT.getVectorNumElements() != 1) {
  395. // Certain ABIs require that vectors are passed as integers. For vectors
  396. // are the same size, this is an obvious bitcast.
  397. if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
  398. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  399. } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
  400. // Bitcast Val back the original type and extract the corresponding
  401. // vector we want.
  402. unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
  403. EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
  404. ValueVT.getVectorElementType(), Elts);
  405. Val = DAG.getBitcast(WiderVecType, Val);
  406. return DAG.getNode(
  407. ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
  408. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  409. }
  410. diagnosePossiblyInvalidConstraint(
  411. *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
  412. return DAG.getUNDEF(ValueVT);
  413. }
  414. // Handle cases such as i8 -> <1 x i1>
  415. EVT ValueSVT = ValueVT.getVectorElementType();
  416. if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
  417. Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
  418. : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
  419. return DAG.getBuildVector(ValueVT, DL, Val);
  420. }
  421. static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
  422. SDValue Val, SDValue *Parts, unsigned NumParts,
  423. MVT PartVT, const Value *V, bool IsABIRegCopy);
  424. /// getCopyToParts - Create a series of nodes that contain the specified value
  425. /// split into legal parts. If the parts contain more bits than Val, then, for
  426. /// integers, ExtendKind can be used to specify how to generate the extra bits.
  427. static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
  428. SDValue *Parts, unsigned NumParts, MVT PartVT,
  429. const Value *V,
  430. ISD::NodeType ExtendKind = ISD::ANY_EXTEND,
  431. bool IsABIRegCopy = false) {
  432. EVT ValueVT = Val.getValueType();
  433. // Handle the vector case separately.
  434. if (ValueVT.isVector())
  435. return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
  436. IsABIRegCopy);
  437. unsigned PartBits = PartVT.getSizeInBits();
  438. unsigned OrigNumParts = NumParts;
  439. assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
  440. "Copying to an illegal type!");
  441. if (NumParts == 0)
  442. return;
  443. assert(!ValueVT.isVector() && "Vector case handled elsewhere");
  444. EVT PartEVT = PartVT;
  445. if (PartEVT == ValueVT) {
  446. assert(NumParts == 1 && "No-op copy with multiple parts!");
  447. Parts[0] = Val;
  448. return;
  449. }
  450. if (NumParts * PartBits > ValueVT.getSizeInBits()) {
  451. // If the parts cover more bits than the value has, promote the value.
  452. if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  453. assert(NumParts == 1 && "Do not know what to promote to!");
  454. Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
  455. } else {
  456. if (ValueVT.isFloatingPoint()) {
  457. // FP values need to be bitcast, then extended if they are being put
  458. // into a larger container.
  459. ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  460. Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  461. }
  462. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  463. ValueVT.isInteger() &&
  464. "Unknown mismatch!");
  465. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  466. Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
  467. if (PartVT == MVT::x86mmx)
  468. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  469. }
  470. } else if (PartBits == ValueVT.getSizeInBits()) {
  471. // Different types of the same size.
  472. assert(NumParts == 1 && PartEVT != ValueVT);
  473. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  474. } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
  475. // If the parts cover less bits than value has, truncate the value.
  476. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  477. ValueVT.isInteger() &&
  478. "Unknown mismatch!");
  479. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  480. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  481. if (PartVT == MVT::x86mmx)
  482. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  483. }
  484. // The value may have changed - recompute ValueVT.
  485. ValueVT = Val.getValueType();
  486. assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
  487. "Failed to tile the value with PartVT!");
  488. if (NumParts == 1) {
  489. if (PartEVT != ValueVT) {
  490. diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
  491. "scalar-to-vector conversion failed");
  492. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  493. }
  494. Parts[0] = Val;
  495. return;
  496. }
  497. // Expand the value into multiple parts.
  498. if (NumParts & (NumParts - 1)) {
  499. // The number of parts is not a power of 2. Split off and copy the tail.
  500. assert(PartVT.isInteger() && ValueVT.isInteger() &&
  501. "Do not know what to expand to!");
  502. unsigned RoundParts = 1 << Log2_32(NumParts);
  503. unsigned RoundBits = RoundParts * PartBits;
  504. unsigned OddParts = NumParts - RoundParts;
  505. SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
  506. DAG.getIntPtrConstant(RoundBits, DL));
  507. getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
  508. if (DAG.getDataLayout().isBigEndian())
  509. // The odd parts were reversed by getCopyToParts - unreverse them.
  510. std::reverse(Parts + RoundParts, Parts + NumParts);
  511. NumParts = RoundParts;
  512. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  513. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  514. }
  515. // The number of parts is a power of 2. Repeatedly bisect the value using
  516. // EXTRACT_ELEMENT.
  517. Parts[0] = DAG.getNode(ISD::BITCAST, DL,
  518. EVT::getIntegerVT(*DAG.getContext(),
  519. ValueVT.getSizeInBits()),
  520. Val);
  521. for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
  522. for (unsigned i = 0; i < NumParts; i += StepSize) {
  523. unsigned ThisBits = StepSize * PartBits / 2;
  524. EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
  525. SDValue &Part0 = Parts[i];
  526. SDValue &Part1 = Parts[i+StepSize/2];
  527. Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  528. ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
  529. Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  530. ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
  531. if (ThisBits == PartBits && ThisVT != PartVT) {
  532. Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
  533. Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
  534. }
  535. }
  536. }
  537. if (DAG.getDataLayout().isBigEndian())
  538. std::reverse(Parts, Parts + OrigNumParts);
  539. }
  540. /// getCopyToPartsVector - Create a series of nodes that contain the specified
  541. /// value split into legal parts.
  542. static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  543. SDValue Val, SDValue *Parts, unsigned NumParts,
  544. MVT PartVT, const Value *V,
  545. bool IsABIRegCopy) {
  546. EVT ValueVT = Val.getValueType();
  547. assert(ValueVT.isVector() && "Not a vector");
  548. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  549. if (NumParts == 1) {
  550. EVT PartEVT = PartVT;
  551. if (PartEVT == ValueVT) {
  552. // Nothing to do.
  553. } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
  554. // Bitconvert vector->vector case.
  555. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  556. } else if (PartVT.isVector() &&
  557. PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
  558. PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
  559. EVT ElementVT = PartVT.getVectorElementType();
  560. // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
  561. // undef elements.
  562. SmallVector<SDValue, 16> Ops;
  563. for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
  564. Ops.push_back(DAG.getNode(
  565. ISD::EXTRACT_VECTOR_ELT, DL, ElementVT, Val,
  566. DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))));
  567. for (unsigned i = ValueVT.getVectorNumElements(),
  568. e = PartVT.getVectorNumElements(); i != e; ++i)
  569. Ops.push_back(DAG.getUNDEF(ElementVT));
  570. Val = DAG.getBuildVector(PartVT, DL, Ops);
  571. // FIXME: Use CONCAT for 2x -> 4x.
  572. //SDValue UndefElts = DAG.getUNDEF(VectorTy);
  573. //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
  574. } else if (PartVT.isVector() &&
  575. PartEVT.getVectorElementType().bitsGE(
  576. ValueVT.getVectorElementType()) &&
  577. PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
  578. // Promoted vector extract
  579. Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
  580. } else {
  581. if (ValueVT.getVectorNumElements() == 1) {
  582. Val = DAG.getNode(
  583. ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
  584. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  585. } else {
  586. assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
  587. "lossy conversion of vector to scalar type");
  588. EVT IntermediateType =
  589. EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  590. Val = DAG.getBitcast(IntermediateType, Val);
  591. Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
  592. }
  593. }
  594. assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
  595. Parts[0] = Val;
  596. return;
  597. }
  598. // Handle a multi-element vector.
  599. EVT IntermediateVT;
  600. MVT RegisterVT;
  601. unsigned NumIntermediates;
  602. unsigned NumRegs;
  603. if (IsABIRegCopy) {
  604. NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
  605. *DAG.getContext(), ValueVT, IntermediateVT, NumIntermediates,
  606. RegisterVT);
  607. } else {
  608. NumRegs =
  609. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  610. NumIntermediates, RegisterVT);
  611. }
  612. unsigned NumElements = ValueVT.getVectorNumElements();
  613. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  614. NumParts = NumRegs; // Silence a compiler warning.
  615. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  616. // Convert the vector to the appropiate type if necessary.
  617. unsigned DestVectorNoElts =
  618. NumIntermediates *
  619. (IntermediateVT.isVector() ? IntermediateVT.getVectorNumElements() : 1);
  620. EVT BuiltVectorTy = EVT::getVectorVT(
  621. *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
  622. if (Val.getValueType() != BuiltVectorTy)
  623. Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
  624. // Split the vector into intermediate operands.
  625. SmallVector<SDValue, 8> Ops(NumIntermediates);
  626. for (unsigned i = 0; i != NumIntermediates; ++i) {
  627. if (IntermediateVT.isVector())
  628. Ops[i] =
  629. DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
  630. DAG.getConstant(i * (NumElements / NumIntermediates), DL,
  631. TLI.getVectorIdxTy(DAG.getDataLayout())));
  632. else
  633. Ops[i] = DAG.getNode(
  634. ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
  635. DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  636. }
  637. // Split the intermediate operands into legal parts.
  638. if (NumParts == NumIntermediates) {
  639. // If the register was not expanded, promote or copy the value,
  640. // as appropriate.
  641. for (unsigned i = 0; i != NumParts; ++i)
  642. getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
  643. } else if (NumParts > 0) {
  644. // If the intermediate type was expanded, split each the value into
  645. // legal parts.
  646. assert(NumIntermediates != 0 && "division by zero");
  647. assert(NumParts % NumIntermediates == 0 &&
  648. "Must expand into a divisible number of parts!");
  649. unsigned Factor = NumParts / NumIntermediates;
  650. for (unsigned i = 0; i != NumIntermediates; ++i)
  651. getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
  652. }
  653. }
  654. RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
  655. EVT valuevt, bool IsABIMangledValue)
  656. : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
  657. RegCount(1, regs.size()), IsABIMangled(IsABIMangledValue) {}
  658. RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
  659. const DataLayout &DL, unsigned Reg, Type *Ty,
  660. bool IsABIMangledValue) {
  661. ComputeValueVTs(TLI, DL, Ty, ValueVTs);
  662. IsABIMangled = IsABIMangledValue;
  663. for (EVT ValueVT : ValueVTs) {
  664. unsigned NumRegs = IsABIMangledValue
  665. ? TLI.getNumRegistersForCallingConv(Context, ValueVT)
  666. : TLI.getNumRegisters(Context, ValueVT);
  667. MVT RegisterVT = IsABIMangledValue
  668. ? TLI.getRegisterTypeForCallingConv(Context, ValueVT)
  669. : TLI.getRegisterType(Context, ValueVT);
  670. for (unsigned i = 0; i != NumRegs; ++i)
  671. Regs.push_back(Reg + i);
  672. RegVTs.push_back(RegisterVT);
  673. RegCount.push_back(NumRegs);
  674. Reg += NumRegs;
  675. }
  676. }
  677. SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
  678. FunctionLoweringInfo &FuncInfo,
  679. const SDLoc &dl, SDValue &Chain,
  680. SDValue *Flag, const Value *V) const {
  681. // A Value with type {} or [0 x %t] needs no registers.
  682. if (ValueVTs.empty())
  683. return SDValue();
  684. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  685. // Assemble the legal parts into the final values.
  686. SmallVector<SDValue, 4> Values(ValueVTs.size());
  687. SmallVector<SDValue, 8> Parts;
  688. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  689. // Copy the legal parts from the registers.
  690. EVT ValueVT = ValueVTs[Value];
  691. unsigned NumRegs = RegCount[Value];
  692. MVT RegisterVT = IsABIMangled
  693. ? TLI.getRegisterTypeForCallingConv(RegVTs[Value])
  694. : RegVTs[Value];
  695. Parts.resize(NumRegs);
  696. for (unsigned i = 0; i != NumRegs; ++i) {
  697. SDValue P;
  698. if (!Flag) {
  699. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
  700. } else {
  701. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
  702. *Flag = P.getValue(2);
  703. }
  704. Chain = P.getValue(1);
  705. Parts[i] = P;
  706. // If the source register was virtual and if we know something about it,
  707. // add an assert node.
  708. if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
  709. !RegisterVT.isInteger() || RegisterVT.isVector())
  710. continue;
  711. const FunctionLoweringInfo::LiveOutInfo *LOI =
  712. FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
  713. if (!LOI)
  714. continue;
  715. unsigned RegSize = RegisterVT.getSizeInBits();
  716. unsigned NumSignBits = LOI->NumSignBits;
  717. unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
  718. if (NumZeroBits == RegSize) {
  719. // The current value is a zero.
  720. // Explicitly express that as it would be easier for
  721. // optimizations to kick in.
  722. Parts[i] = DAG.getConstant(0, dl, RegisterVT);
  723. continue;
  724. }
  725. // FIXME: We capture more information than the dag can represent. For
  726. // now, just use the tightest assertzext/assertsext possible.
  727. bool isSExt = true;
  728. EVT FromVT(MVT::Other);
  729. if (NumSignBits == RegSize) {
  730. isSExt = true; // ASSERT SEXT 1
  731. FromVT = MVT::i1;
  732. } else if (NumZeroBits >= RegSize - 1) {
  733. isSExt = false; // ASSERT ZEXT 1
  734. FromVT = MVT::i1;
  735. } else if (NumSignBits > RegSize - 8) {
  736. isSExt = true; // ASSERT SEXT 8
  737. FromVT = MVT::i8;
  738. } else if (NumZeroBits >= RegSize - 8) {
  739. isSExt = false; // ASSERT ZEXT 8
  740. FromVT = MVT::i8;
  741. } else if (NumSignBits > RegSize - 16) {
  742. isSExt = true; // ASSERT SEXT 16
  743. FromVT = MVT::i16;
  744. } else if (NumZeroBits >= RegSize - 16) {
  745. isSExt = false; // ASSERT ZEXT 16
  746. FromVT = MVT::i16;
  747. } else if (NumSignBits > RegSize - 32) {
  748. isSExt = true; // ASSERT SEXT 32
  749. FromVT = MVT::i32;
  750. } else if (NumZeroBits >= RegSize - 32) {
  751. isSExt = false; // ASSERT ZEXT 32
  752. FromVT = MVT::i32;
  753. } else {
  754. continue;
  755. }
  756. // Add an assertion node.
  757. assert(FromVT != MVT::Other);
  758. Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
  759. RegisterVT, P, DAG.getValueType(FromVT));
  760. }
  761. Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
  762. NumRegs, RegisterVT, ValueVT, V);
  763. Part += NumRegs;
  764. Parts.clear();
  765. }
  766. return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
  767. }
  768. void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
  769. const SDLoc &dl, SDValue &Chain, SDValue *Flag,
  770. const Value *V,
  771. ISD::NodeType PreferredExtendType) const {
  772. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  773. ISD::NodeType ExtendKind = PreferredExtendType;
  774. // Get the list of the values's legal parts.
  775. unsigned NumRegs = Regs.size();
  776. SmallVector<SDValue, 8> Parts(NumRegs);
  777. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  778. unsigned NumParts = RegCount[Value];
  779. MVT RegisterVT = IsABIMangled
  780. ? TLI.getRegisterTypeForCallingConv(RegVTs[Value])
  781. : RegVTs[Value];
  782. if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
  783. ExtendKind = ISD::ZERO_EXTEND;
  784. getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
  785. &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
  786. Part += NumParts;
  787. }
  788. // Copy the parts into the registers.
  789. SmallVector<SDValue, 8> Chains(NumRegs);
  790. for (unsigned i = 0; i != NumRegs; ++i) {
  791. SDValue Part;
  792. if (!Flag) {
  793. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
  794. } else {
  795. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
  796. *Flag = Part.getValue(1);
  797. }
  798. Chains[i] = Part.getValue(0);
  799. }
  800. if (NumRegs == 1 || Flag)
  801. // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
  802. // flagged to it. That is the CopyToReg nodes and the user are considered
  803. // a single scheduling unit. If we create a TokenFactor and return it as
  804. // chain, then the TokenFactor is both a predecessor (operand) of the
  805. // user as well as a successor (the TF operands are flagged to the user).
  806. // c1, f1 = CopyToReg
  807. // c2, f2 = CopyToReg
  808. // c3 = TokenFactor c1, c2
  809. // ...
  810. // = op c3, ..., f2
  811. Chain = Chains[NumRegs-1];
  812. else
  813. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  814. }
  815. void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
  816. unsigned MatchingIdx, const SDLoc &dl,
  817. SelectionDAG &DAG,
  818. std::vector<SDValue> &Ops) const {
  819. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  820. unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
  821. if (HasMatching)
  822. Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
  823. else if (!Regs.empty() &&
  824. TargetRegisterInfo::isVirtualRegister(Regs.front())) {
  825. // Put the register class of the virtual registers in the flag word. That
  826. // way, later passes can recompute register class constraints for inline
  827. // assembly as well as normal instructions.
  828. // Don't do this for tied operands that can use the regclass information
  829. // from the def.
  830. const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
  831. const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
  832. Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
  833. }
  834. SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
  835. Ops.push_back(Res);
  836. if (Code == InlineAsm::Kind_Clobber) {
  837. // Clobbers should always have a 1:1 mapping with registers, and may
  838. // reference registers that have illegal (e.g. vector) types. Hence, we
  839. // shouldn't try to apply any sort of splitting logic to them.
  840. assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
  841. "No 1:1 mapping from clobbers to regs?");
  842. unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
  843. (void)SP;
  844. for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
  845. Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
  846. assert(
  847. (Regs[I] != SP ||
  848. DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
  849. "If we clobbered the stack pointer, MFI should know about it.");
  850. }
  851. return;
  852. }
  853. for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
  854. unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
  855. MVT RegisterVT = RegVTs[Value];
  856. for (unsigned i = 0; i != NumRegs; ++i) {
  857. assert(Reg < Regs.size() && "Mismatch in # registers expected");
  858. unsigned TheReg = Regs[Reg++];
  859. Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
  860. }
  861. }
  862. }
  863. void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
  864. const TargetLibraryInfo *li) {
  865. AA = aa;
  866. GFI = gfi;
  867. LibInfo = li;
  868. DL = &DAG.getDataLayout();
  869. Context = DAG.getContext();
  870. LPadToCallSiteMap.clear();
  871. }
  872. void SelectionDAGBuilder::clear() {
  873. NodeMap.clear();
  874. UnusedArgNodeMap.clear();
  875. PendingLoads.clear();
  876. PendingExports.clear();
  877. CurInst = nullptr;
  878. HasTailCall = false;
  879. SDNodeOrder = LowestSDNodeOrder;
  880. StatepointLowering.clear();
  881. }
  882. void SelectionDAGBuilder::clearDanglingDebugInfo() {
  883. DanglingDebugInfoMap.clear();
  884. }
  885. SDValue SelectionDAGBuilder::getRoot() {
  886. if (PendingLoads.empty())
  887. return DAG.getRoot();
  888. if (PendingLoads.size() == 1) {
  889. SDValue Root = PendingLoads[0];
  890. DAG.setRoot(Root);
  891. PendingLoads.clear();
  892. return Root;
  893. }
  894. // Otherwise, we have to make a token factor node.
  895. SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  896. PendingLoads);
  897. PendingLoads.clear();
  898. DAG.setRoot(Root);
  899. return Root;
  900. }
  901. SDValue SelectionDAGBuilder::getControlRoot() {
  902. SDValue Root = DAG.getRoot();
  903. if (PendingExports.empty())
  904. return Root;
  905. // Turn all of the CopyToReg chains into one factored node.
  906. if (Root.getOpcode() != ISD::EntryToken) {
  907. unsigned i = 0, e = PendingExports.size();
  908. for (; i != e; ++i) {
  909. assert(PendingExports[i].getNode()->getNumOperands() > 1);
  910. if (PendingExports[i].getNode()->getOperand(0) == Root)
  911. break; // Don't add the root if we already indirectly depend on it.
  912. }
  913. if (i == e)
  914. PendingExports.push_back(Root);
  915. }
  916. Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  917. PendingExports);
  918. PendingExports.clear();
  919. DAG.setRoot(Root);
  920. return Root;
  921. }
  922. void SelectionDAGBuilder::visit(const Instruction &I) {
  923. // Set up outgoing PHI node register values before emitting the terminator.
  924. if (isa<TerminatorInst>(&I)) {
  925. HandlePHINodesInSuccessorBlocks(I.getParent());
  926. }
  927. // Increase the SDNodeOrder if dealing with a non-debug instruction.
  928. if (!isa<DbgInfoIntrinsic>(I))
  929. ++SDNodeOrder;
  930. CurInst = &I;
  931. visit(I.getOpcode(), I);
  932. if (!isa<TerminatorInst>(&I) && !HasTailCall &&
  933. !isStatepoint(&I)) // statepoints handle their exports internally
  934. CopyToExportRegsIfNeeded(&I);
  935. CurInst = nullptr;
  936. }
  937. void SelectionDAGBuilder::visitPHI(const PHINode &) {
  938. llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
  939. }
  940. void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
  941. // Note: this doesn't use InstVisitor, because it has to work with
  942. // ConstantExpr's in addition to instructions.
  943. switch (Opcode) {
  944. default: llvm_unreachable("Unknown instruction type encountered!");
  945. // Build the switch statement using the Instruction.def file.
  946. #define HANDLE_INST(NUM, OPCODE, CLASS) \
  947. case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
  948. #include "llvm/IR/Instruction.def"
  949. }
  950. }
  951. // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
  952. // generate the debug data structures now that we've seen its definition.
  953. void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
  954. SDValue Val) {
  955. DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
  956. if (DDI.getDI()) {
  957. const DbgValueInst *DI = DDI.getDI();
  958. DebugLoc dl = DDI.getdl();
  959. unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
  960. DILocalVariable *Variable = DI->getVariable();
  961. DIExpression *Expr = DI->getExpression();
  962. assert(Variable->isValidLocationForIntrinsic(dl) &&
  963. "Expected inlined-at fields to agree");
  964. SDDbgValue *SDV;
  965. if (Val.getNode()) {
  966. if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
  967. SDV = getDbgValue(Val, Variable, Expr, dl, DbgSDNodeOrder);
  968. DAG.AddDbgValue(SDV, Val.getNode(), false);
  969. }
  970. } else
  971. DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
  972. DanglingDebugInfoMap[V] = DanglingDebugInfo();
  973. }
  974. }
  975. /// getCopyFromRegs - If there was virtual register allocated for the value V
  976. /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
  977. SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
  978. DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
  979. SDValue Result;
  980. if (It != FuncInfo.ValueMap.end()) {
  981. unsigned InReg = It->second;
  982. RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
  983. DAG.getDataLayout(), InReg, Ty, isABIRegCopy(V));
  984. SDValue Chain = DAG.getEntryNode();
  985. Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
  986. V);
  987. resolveDanglingDebugInfo(V, Result);
  988. }
  989. return Result;
  990. }
  991. /// getValue - Return an SDValue for the given Value.
  992. SDValue SelectionDAGBuilder::getValue(const Value *V) {
  993. // If we already have an SDValue for this value, use it. It's important
  994. // to do this first, so that we don't create a CopyFromReg if we already
  995. // have a regular SDValue.
  996. SDValue &N = NodeMap[V];
  997. if (N.getNode()) return N;
  998. // If there's a virtual register allocated and initialized for this
  999. // value, use it.
  1000. if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
  1001. return copyFromReg;
  1002. // Otherwise create a new SDValue and remember it.
  1003. SDValue Val = getValueImpl(V);
  1004. NodeMap[V] = Val;
  1005. resolveDanglingDebugInfo(V, Val);
  1006. return Val;
  1007. }
  1008. // Return true if SDValue exists for the given Value
  1009. bool SelectionDAGBuilder::findValue(const Value *V) const {
  1010. return (NodeMap.find(V) != NodeMap.end()) ||
  1011. (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
  1012. }
  1013. /// getNonRegisterValue - Return an SDValue for the given Value, but
  1014. /// don't look in FuncInfo.ValueMap for a virtual register.
  1015. SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
  1016. // If we already have an SDValue for this value, use it.
  1017. SDValue &N = NodeMap[V];
  1018. if (N.getNode()) {
  1019. if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
  1020. // Remove the debug location from the node as the node is about to be used
  1021. // in a location which may differ from the original debug location. This
  1022. // is relevant to Constant and ConstantFP nodes because they can appear
  1023. // as constant expressions inside PHI nodes.
  1024. N->setDebugLoc(DebugLoc());
  1025. }
  1026. return N;
  1027. }
  1028. // Otherwise create a new SDValue and remember it.
  1029. SDValue Val = getValueImpl(V);
  1030. NodeMap[V] = Val;
  1031. resolveDanglingDebugInfo(V, Val);
  1032. return Val;
  1033. }
  1034. /// getValueImpl - Helper function for getValue and getNonRegisterValue.
  1035. /// Create an SDValue for the given value.
  1036. SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
  1037. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1038. if (const Constant *C = dyn_cast<Constant>(V)) {
  1039. EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
  1040. if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
  1041. return DAG.getConstant(*CI, getCurSDLoc(), VT);
  1042. if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
  1043. return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
  1044. if (isa<ConstantPointerNull>(C)) {
  1045. unsigned AS = V->getType()->getPointerAddressSpace();
  1046. return DAG.getConstant(0, getCurSDLoc(),
  1047. TLI.getPointerTy(DAG.getDataLayout(), AS));
  1048. }
  1049. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
  1050. return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
  1051. if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
  1052. return DAG.getUNDEF(VT);
  1053. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  1054. visit(CE->getOpcode(), *CE);
  1055. SDValue N1 = NodeMap[V];
  1056. assert(N1.getNode() && "visit didn't populate the NodeMap!");
  1057. return N1;
  1058. }
  1059. if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
  1060. SmallVector<SDValue, 4> Constants;
  1061. for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
  1062. OI != OE; ++OI) {
  1063. SDNode *Val = getValue(*OI).getNode();
  1064. // If the operand is an empty aggregate, there are no values.
  1065. if (!Val) continue;
  1066. // Add each leaf value from the operand to the Constants list
  1067. // to form a flattened list of all the values.
  1068. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  1069. Constants.push_back(SDValue(Val, i));
  1070. }
  1071. return DAG.getMergeValues(Constants, getCurSDLoc());
  1072. }
  1073. if (const ConstantDataSequential *CDS =
  1074. dyn_cast<ConstantDataSequential>(C)) {
  1075. SmallVector<SDValue, 4> Ops;
  1076. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  1077. SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
  1078. // Add each leaf value from the operand to the Constants list
  1079. // to form a flattened list of all the values.
  1080. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  1081. Ops.push_back(SDValue(Val, i));
  1082. }
  1083. if (isa<ArrayType>(CDS->getType()))
  1084. return DAG.getMergeValues(Ops, getCurSDLoc());
  1085. return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
  1086. }
  1087. if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
  1088. assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
  1089. "Unknown struct or array constant!");
  1090. SmallVector<EVT, 4> ValueVTs;
  1091. ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
  1092. unsigned NumElts = ValueVTs.size();
  1093. if (NumElts == 0)
  1094. return SDValue(); // empty struct
  1095. SmallVector<SDValue, 4> Constants(NumElts);
  1096. for (unsigned i = 0; i != NumElts; ++i) {
  1097. EVT EltVT = ValueVTs[i];
  1098. if (isa<UndefValue>(C))
  1099. Constants[i] = DAG.getUNDEF(EltVT);
  1100. else if (EltVT.isFloatingPoint())
  1101. Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  1102. else
  1103. Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
  1104. }
  1105. return DAG.getMergeValues(Constants, getCurSDLoc());
  1106. }
  1107. if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
  1108. return DAG.getBlockAddress(BA, VT);
  1109. VectorType *VecTy = cast<VectorType>(V->getType());
  1110. unsigned NumElements = VecTy->getNumElements();
  1111. // Now that we know the number and type of the elements, get that number of
  1112. // elements into the Ops array based on what kind of constant it is.
  1113. SmallVector<SDValue, 16> Ops;
  1114. if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
  1115. for (unsigned i = 0; i != NumElements; ++i)
  1116. Ops.push_back(getValue(CV->getOperand(i)));
  1117. } else {
  1118. assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
  1119. EVT EltVT =
  1120. TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
  1121. SDValue Op;
  1122. if (EltVT.isFloatingPoint())
  1123. Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  1124. else
  1125. Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
  1126. Ops.assign(NumElements, Op);
  1127. }
  1128. // Create a BUILD_VECTOR node.
  1129. return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
  1130. }
  1131. // If this is a static alloca, generate it as the frameindex instead of
  1132. // computation.
  1133. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  1134. DenseMap<const AllocaInst*, int>::iterator SI =
  1135. FuncInfo.StaticAllocaMap.find(AI);
  1136. if (SI != FuncInfo.StaticAllocaMap.end())
  1137. return DAG.getFrameIndex(SI->second,
  1138. TLI.getFrameIndexTy(DAG.getDataLayout()));
  1139. }
  1140. // If this is an instruction which fast-isel has deferred, select it now.
  1141. if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
  1142. unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
  1143. RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
  1144. Inst->getType(), isABIRegCopy(V));
  1145. SDValue Chain = DAG.getEntryNode();
  1146. return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
  1147. }
  1148. llvm_unreachable("Can't get register for value!");
  1149. }
  1150. void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
  1151. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1152. bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
  1153. bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
  1154. MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
  1155. // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
  1156. if (IsMSVCCXX || IsCoreCLR)
  1157. CatchPadMBB->setIsEHFuncletEntry();
  1158. DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, getControlRoot()));
  1159. }
  1160. void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
  1161. // Update machine-CFG edge.
  1162. MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
  1163. FuncInfo.MBB->addSuccessor(TargetMBB);
  1164. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1165. bool IsSEH = isAsynchronousEHPersonality(Pers);
  1166. if (IsSEH) {
  1167. // If this is not a fall-through branch or optimizations are switched off,
  1168. // emit the branch.
  1169. if (TargetMBB != NextBlock(FuncInfo.MBB) ||
  1170. TM.getOptLevel() == CodeGenOpt::None)
  1171. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  1172. getControlRoot(), DAG.getBasicBlock(TargetMBB)));
  1173. return;
  1174. }
  1175. // Figure out the funclet membership for the catchret's successor.
  1176. // This will be used by the FuncletLayout pass to determine how to order the
  1177. // BB's.
  1178. // A 'catchret' returns to the outer scope's color.
  1179. Value *ParentPad = I.getCatchSwitchParentPad();
  1180. const BasicBlock *SuccessorColor;
  1181. if (isa<ConstantTokenNone>(ParentPad))
  1182. SuccessorColor = &FuncInfo.Fn->getEntryBlock();
  1183. else
  1184. SuccessorColor = cast<Instruction>(ParentPad)->getParent();
  1185. assert(SuccessorColor && "No parent funclet for catchret!");
  1186. MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
  1187. assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
  1188. // Create the terminator node.
  1189. SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
  1190. getControlRoot(), DAG.getBasicBlock(TargetMBB),
  1191. DAG.getBasicBlock(SuccessorColorMBB));
  1192. DAG.setRoot(Ret);
  1193. }
  1194. void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
  1195. // Don't emit any special code for the cleanuppad instruction. It just marks
  1196. // the start of a funclet.
  1197. FuncInfo.MBB->setIsEHFuncletEntry();
  1198. FuncInfo.MBB->setIsCleanupFuncletEntry();
  1199. }
  1200. /// When an invoke or a cleanupret unwinds to the next EH pad, there are
  1201. /// many places it could ultimately go. In the IR, we have a single unwind
  1202. /// destination, but in the machine CFG, we enumerate all the possible blocks.
  1203. /// This function skips over imaginary basic blocks that hold catchswitch
  1204. /// instructions, and finds all the "real" machine
  1205. /// basic block destinations. As those destinations may not be successors of
  1206. /// EHPadBB, here we also calculate the edge probability to those destinations.
  1207. /// The passed-in Prob is the edge probability to EHPadBB.
  1208. static void findUnwindDestinations(
  1209. FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
  1210. BranchProbability Prob,
  1211. SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
  1212. &UnwindDests) {
  1213. EHPersonality Personality =
  1214. classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1215. bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
  1216. bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
  1217. while (EHPadBB) {
  1218. const Instruction *Pad = EHPadBB->getFirstNonPHI();
  1219. BasicBlock *NewEHPadBB = nullptr;
  1220. if (isa<LandingPadInst>(Pad)) {
  1221. // Stop on landingpads. They are not funclets.
  1222. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1223. break;
  1224. } else if (isa<CleanupPadInst>(Pad)) {
  1225. // Stop on cleanup pads. Cleanups are always funclet entries for all known
  1226. // personalities.
  1227. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1228. UnwindDests.back().first->setIsEHFuncletEntry();
  1229. break;
  1230. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
  1231. // Add the catchpad handlers to the possible destinations.
  1232. for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
  1233. UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
  1234. // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
  1235. if (IsMSVCCXX || IsCoreCLR)
  1236. UnwindDests.back().first->setIsEHFuncletEntry();
  1237. }
  1238. NewEHPadBB = CatchSwitch->getUnwindDest();
  1239. } else {
  1240. continue;
  1241. }
  1242. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1243. if (BPI && NewEHPadBB)
  1244. Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
  1245. EHPadBB = NewEHPadBB;
  1246. }
  1247. }
  1248. void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
  1249. // Update successor info.
  1250. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  1251. auto UnwindDest = I.getUnwindDest();
  1252. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1253. BranchProbability UnwindDestProb =
  1254. (BPI && UnwindDest)
  1255. ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
  1256. : BranchProbability::getZero();
  1257. findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
  1258. for (auto &UnwindDest : UnwindDests) {
  1259. UnwindDest.first->setIsEHPad();
  1260. addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
  1261. }
  1262. FuncInfo.MBB->normalizeSuccProbs();
  1263. // Create the terminator node.
  1264. SDValue Ret =
  1265. DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
  1266. DAG.setRoot(Ret);
  1267. }
  1268. void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
  1269. report_fatal_error("visitCatchSwitch not yet implemented!");
  1270. }
  1271. void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
  1272. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1273. auto &DL = DAG.getDataLayout();
  1274. SDValue Chain = getControlRoot();
  1275. SmallVector<ISD::OutputArg, 8> Outs;
  1276. SmallVector<SDValue, 8> OutVals;
  1277. // Calls to @llvm.experimental.deoptimize don't generate a return value, so
  1278. // lower
  1279. //
  1280. // %val = call <ty> @llvm.experimental.deoptimize()
  1281. // ret <ty> %val
  1282. //
  1283. // differently.
  1284. if (I.getParent()->getTerminatingDeoptimizeCall()) {
  1285. LowerDeoptimizingReturn();
  1286. return;
  1287. }
  1288. if (!FuncInfo.CanLowerReturn) {
  1289. unsigned DemoteReg = FuncInfo.DemoteRegister;
  1290. const Function *F = I.getParent()->getParent();
  1291. // Emit a store of the return value through the virtual register.
  1292. // Leave Outs empty so that LowerReturn won't try to load return
  1293. // registers the usual way.
  1294. SmallVector<EVT, 1> PtrValueVTs;
  1295. ComputeValueVTs(TLI, DL,
  1296. F->getReturnType()->getPointerTo(
  1297. DAG.getDataLayout().getAllocaAddrSpace()),
  1298. PtrValueVTs);
  1299. SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
  1300. DemoteReg, PtrValueVTs[0]);
  1301. SDValue RetOp = getValue(I.getOperand(0));
  1302. SmallVector<EVT, 4> ValueVTs;
  1303. SmallVector<uint64_t, 4> Offsets;
  1304. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets);
  1305. unsigned NumValues = ValueVTs.size();
  1306. SmallVector<SDValue, 4> Chains(NumValues);
  1307. for (unsigned i = 0; i != NumValues; ++i) {
  1308. // An aggregate return value cannot wrap around the address space, so
  1309. // offsets to its parts don't wrap either.
  1310. SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
  1311. Chains[i] = DAG.getStore(
  1312. Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i),
  1313. // FIXME: better loc info would be nice.
  1314. Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
  1315. }
  1316. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
  1317. MVT::Other, Chains);
  1318. } else if (I.getNumOperands() != 0) {
  1319. SmallVector<EVT, 4> ValueVTs;
  1320. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
  1321. unsigned NumValues = ValueVTs.size();
  1322. if (NumValues) {
  1323. SDValue RetOp = getValue(I.getOperand(0));
  1324. const Function *F = I.getParent()->getParent();
  1325. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  1326. if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
  1327. Attribute::SExt))
  1328. ExtendKind = ISD::SIGN_EXTEND;
  1329. else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
  1330. Attribute::ZExt))
  1331. ExtendKind = ISD::ZERO_EXTEND;
  1332. LLVMContext &Context = F->getContext();
  1333. bool RetInReg = F->getAttributes().hasAttribute(
  1334. AttributeList::ReturnIndex, Attribute::InReg);
  1335. for (unsigned j = 0; j != NumValues; ++j) {
  1336. EVT VT = ValueVTs[j];
  1337. if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
  1338. VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
  1339. unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, VT);
  1340. MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, VT);
  1341. SmallVector<SDValue, 4> Parts(NumParts);
  1342. getCopyToParts(DAG, getCurSDLoc(),
  1343. SDValue(RetOp.getNode(), RetOp.getResNo() + j),
  1344. &Parts[0], NumParts, PartVT, &I, ExtendKind, true);
  1345. // 'inreg' on function refers to return value
  1346. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1347. if (RetInReg)
  1348. Flags.setInReg();
  1349. // Propagate extension type if any
  1350. if (ExtendKind == ISD::SIGN_EXTEND)
  1351. Flags.setSExt();
  1352. else if (ExtendKind == ISD::ZERO_EXTEND)
  1353. Flags.setZExt();
  1354. for (unsigned i = 0; i < NumParts; ++i) {
  1355. Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
  1356. VT, /*isfixed=*/true, 0, 0));
  1357. OutVals.push_back(Parts[i]);
  1358. }
  1359. }
  1360. }
  1361. }
  1362. // Push in swifterror virtual register as the last element of Outs. This makes
  1363. // sure swifterror virtual register will be returned in the swifterror
  1364. // physical register.
  1365. const Function *F = I.getParent()->getParent();
  1366. if (TLI.supportSwiftError() &&
  1367. F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
  1368. assert(FuncInfo.SwiftErrorArg && "Need a swift error argument");
  1369. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1370. Flags.setSwiftError();
  1371. Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
  1372. EVT(TLI.getPointerTy(DL)) /*argvt*/,
  1373. true /*isfixed*/, 1 /*origidx*/,
  1374. 0 /*partOffs*/));
  1375. // Create SDNode for the swifterror virtual register.
  1376. OutVals.push_back(
  1377. DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt(
  1378. &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first,
  1379. EVT(TLI.getPointerTy(DL))));
  1380. }
  1381. bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
  1382. CallingConv::ID CallConv =
  1383. DAG.getMachineFunction().getFunction().getCallingConv();
  1384. Chain = DAG.getTargetLoweringInfo().LowerReturn(
  1385. Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
  1386. // Verify that the target's LowerReturn behaved as expected.
  1387. assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
  1388. "LowerReturn didn't return a valid chain!");
  1389. // Update the DAG with the new chain value resulting from return lowering.
  1390. DAG.setRoot(Chain);
  1391. }
  1392. /// CopyToExportRegsIfNeeded - If the given value has virtual registers
  1393. /// created for it, emit nodes to copy the value into the virtual
  1394. /// registers.
  1395. void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
  1396. // Skip empty types
  1397. if (V->getType()->isEmptyTy())
  1398. return;
  1399. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  1400. if (VMI != FuncInfo.ValueMap.end()) {
  1401. assert(!V->use_empty() && "Unused value assigned virtual registers!");
  1402. CopyValueToVirtualRegister(V, VMI->second);
  1403. }
  1404. }
  1405. /// ExportFromCurrentBlock - If this condition isn't known to be exported from
  1406. /// the current basic block, add it to ValueMap now so that we'll get a
  1407. /// CopyTo/FromReg.
  1408. void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
  1409. // No need to export constants.
  1410. if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
  1411. // Already exported?
  1412. if (FuncInfo.isExportedInst(V)) return;
  1413. unsigned Reg = FuncInfo.InitializeRegForValue(V);
  1414. CopyValueToVirtualRegister(V, Reg);
  1415. }
  1416. bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
  1417. const BasicBlock *FromBB) {
  1418. // The operands of the setcc have to be in this block. We don't know
  1419. // how to export them from some other block.
  1420. if (const Instruction *VI = dyn_cast<Instruction>(V)) {
  1421. // Can export from current BB.
  1422. if (VI->getParent() == FromBB)
  1423. return true;
  1424. // Is already exported, noop.
  1425. return FuncInfo.isExportedInst(V);
  1426. }
  1427. // If this is an argument, we can export it if the BB is the entry block or
  1428. // if it is already exported.
  1429. if (isa<Argument>(V)) {
  1430. if (FromBB == &FromBB->getParent()->getEntryBlock())
  1431. return true;
  1432. // Otherwise, can only export this if it is already exported.
  1433. return FuncInfo.isExportedInst(V);
  1434. }
  1435. // Otherwise, constants can always be exported.
  1436. return true;
  1437. }
  1438. /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
  1439. BranchProbability
  1440. SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
  1441. const MachineBasicBlock *Dst) const {
  1442. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1443. const BasicBlock *SrcBB = Src->getBasicBlock();
  1444. const BasicBlock *DstBB = Dst->getBasicBlock();
  1445. if (!BPI) {
  1446. // If BPI is not available, set the default probability as 1 / N, where N is
  1447. // the number of successors.
  1448. auto SuccSize = std::max<uint32_t>(
  1449. std::distance(succ_begin(SrcBB), succ_end(SrcBB)), 1);
  1450. return BranchProbability(1, SuccSize);
  1451. }
  1452. return BPI->getEdgeProbability(SrcBB, DstBB);
  1453. }
  1454. void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
  1455. MachineBasicBlock *Dst,
  1456. BranchProbability Prob) {
  1457. if (!FuncInfo.BPI)
  1458. Src->addSuccessorWithoutProb(Dst);
  1459. else {
  1460. if (Prob.isUnknown())
  1461. Prob = getEdgeProbability(Src, Dst);
  1462. Src->addSuccessor(Dst, Prob);
  1463. }
  1464. }
  1465. static bool InBlock(const Value *V, const BasicBlock *BB) {
  1466. if (const Instruction *I = dyn_cast<Instruction>(V))
  1467. return I->getParent() == BB;
  1468. return true;
  1469. }
  1470. /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
  1471. /// This function emits a branch and is used at the leaves of an OR or an
  1472. /// AND operator tree.
  1473. void
  1474. SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
  1475. MachineBasicBlock *TBB,
  1476. MachineBasicBlock *FBB,
  1477. MachineBasicBlock *CurBB,
  1478. MachineBasicBlock *SwitchBB,
  1479. BranchProbability TProb,
  1480. BranchProbability FProb,
  1481. bool InvertCond) {
  1482. const BasicBlock *BB = CurBB->getBasicBlock();
  1483. // If the leaf of the tree is a comparison, merge the condition into
  1484. // the caseblock.
  1485. if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
  1486. // The operands of the cmp have to be in this block. We don't know
  1487. // how to export them from some other block. If this is the first block
  1488. // of the sequence, no exporting is needed.
  1489. if (CurBB == SwitchBB ||
  1490. (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
  1491. isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
  1492. ISD::CondCode Condition;
  1493. if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
  1494. ICmpInst::Predicate Pred =
  1495. InvertCond ? IC->getInversePredicate() : IC->getPredicate();
  1496. Condition = getICmpCondCode(Pred);
  1497. } else {
  1498. const FCmpInst *FC = cast<FCmpInst>(Cond);
  1499. FCmpInst::Predicate Pred =
  1500. InvertCond ? FC->getInversePredicate() : FC->getPredicate();
  1501. Condition = getFCmpCondCode(Pred);
  1502. if (TM.Options.NoNaNsFPMath)
  1503. Condition = getFCmpCodeWithoutNaN(Condition);
  1504. }
  1505. CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
  1506. TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
  1507. SwitchCases.push_back(CB);
  1508. return;
  1509. }
  1510. }
  1511. // Create a CaseBlock record representing this branch.
  1512. ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
  1513. CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
  1514. nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
  1515. SwitchCases.push_back(CB);
  1516. }
  1517. /// FindMergedConditions - If Cond is an expression like
  1518. void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
  1519. MachineBasicBlock *TBB,
  1520. MachineBasicBlock *FBB,
  1521. MachineBasicBlock *CurBB,
  1522. MachineBasicBlock *SwitchBB,
  1523. Instruction::BinaryOps Opc,
  1524. BranchProbability TProb,
  1525. BranchProbability FProb,
  1526. bool InvertCond) {
  1527. // Skip over not part of the tree and remember to invert op and operands at
  1528. // next level.
  1529. if (BinaryOperator::isNot(Cond) && Cond->hasOneUse()) {
  1530. const Value *CondOp = BinaryOperator::getNotArgument(Cond);
  1531. if (InBlock(CondOp, CurBB->getBasicBlock())) {
  1532. FindMergedConditions(CondOp, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
  1533. !InvertCond);
  1534. return;
  1535. }
  1536. }
  1537. const Instruction *BOp = dyn_cast<Instruction>(Cond);
  1538. // Compute the effective opcode for Cond, taking into account whether it needs
  1539. // to be inverted, e.g.
  1540. // and (not (or A, B)), C
  1541. // gets lowered as
  1542. // and (and (not A, not B), C)
  1543. unsigned BOpc = 0;
  1544. if (BOp) {
  1545. BOpc = BOp->getOpcode();
  1546. if (InvertCond) {
  1547. if (BOpc == Instruction::And)
  1548. BOpc = Instruction::Or;
  1549. else if (BOpc == Instruction::Or)
  1550. BOpc = Instruction::And;
  1551. }
  1552. }
  1553. // If this node is not part of the or/and tree, emit it as a branch.
  1554. if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
  1555. BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
  1556. BOp->getParent() != CurBB->getBasicBlock() ||
  1557. !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
  1558. !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
  1559. EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
  1560. TProb, FProb, InvertCond);
  1561. return;
  1562. }
  1563. // Create TmpBB after CurBB.
  1564. MachineFunction::iterator BBI(CurBB);
  1565. MachineFunction &MF = DAG.getMachineFunction();
  1566. MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
  1567. CurBB->getParent()->insert(++BBI, TmpBB);
  1568. if (Opc == Instruction::Or) {
  1569. // Codegen X | Y as:
  1570. // BB1:
  1571. // jmp_if_X TBB
  1572. // jmp TmpBB
  1573. // TmpBB:
  1574. // jmp_if_Y TBB
  1575. // jmp FBB
  1576. //
  1577. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1578. // The requirement is that
  1579. // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
  1580. // = TrueProb for original BB.
  1581. // Assuming the original probabilities are A and B, one choice is to set
  1582. // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
  1583. // A/(1+B) and 2B/(1+B). This choice assumes that
  1584. // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
  1585. // Another choice is to assume TrueProb for BB1 equals to TrueProb for
  1586. // TmpBB, but the math is more complicated.
  1587. auto NewTrueProb = TProb / 2;
  1588. auto NewFalseProb = TProb / 2 + FProb;
  1589. // Emit the LHS condition.
  1590. FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
  1591. NewTrueProb, NewFalseProb, InvertCond);
  1592. // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
  1593. SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
  1594. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  1595. // Emit the RHS condition into TmpBB.
  1596. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
  1597. Probs[0], Probs[1], InvertCond);
  1598. } else {
  1599. assert(Opc == Instruction::And && "Unknown merge op!");
  1600. // Codegen X & Y as:
  1601. // BB1:
  1602. // jmp_if_X TmpBB
  1603. // jmp FBB
  1604. // TmpBB:
  1605. // jmp_if_Y TBB
  1606. // jmp FBB
  1607. //
  1608. // This requires creation of TmpBB after CurBB.
  1609. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1610. // The requirement is that
  1611. // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
  1612. // = FalseProb for original BB.
  1613. // Assuming the original probabilities are A and B, one choice is to set
  1614. // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
  1615. // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
  1616. // TrueProb for BB1 * FalseProb for TmpBB.
  1617. auto NewTrueProb = TProb + FProb / 2;
  1618. auto NewFalseProb = FProb / 2;
  1619. // Emit the LHS condition.
  1620. FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
  1621. NewTrueProb, NewFalseProb, InvertCond);
  1622. // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
  1623. SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
  1624. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  1625. // Emit the RHS condition into TmpBB.
  1626. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
  1627. Probs[0], Probs[1], InvertCond);
  1628. }
  1629. }
  1630. /// If the set of cases should be emitted as a series of branches, return true.
  1631. /// If we should emit this as a bunch of and/or'd together conditions, return
  1632. /// false.
  1633. bool
  1634. SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
  1635. if (Cases.size() != 2) return true;
  1636. // If this is two comparisons of the same values or'd or and'd together, they
  1637. // will get folded into a single comparison, so don't emit two blocks.
  1638. if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
  1639. Cases[0].CmpRHS == Cases[1].CmpRHS) ||
  1640. (Cases[0].CmpRHS == Cases[1].CmpLHS &&
  1641. Cases[0].CmpLHS == Cases[1].CmpRHS)) {
  1642. return false;
  1643. }
  1644. // Handle: (X != null) | (Y != null) --> (X|Y) != 0
  1645. // Handle: (X == null) & (Y == null) --> (X|Y) == 0
  1646. if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
  1647. Cases[0].CC == Cases[1].CC &&
  1648. isa<Constant>(Cases[0].CmpRHS) &&
  1649. cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
  1650. if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
  1651. return false;
  1652. if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
  1653. return false;
  1654. }
  1655. return true;
  1656. }
  1657. void SelectionDAGBuilder::visitBr(const BranchInst &I) {
  1658. MachineBasicBlock *BrMBB = FuncInfo.MBB;
  1659. // Update machine-CFG edges.
  1660. MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
  1661. if (I.isUnconditional()) {
  1662. // Update machine-CFG edges.
  1663. BrMBB->addSuccessor(Succ0MBB);
  1664. // If this is not a fall-through branch or optimizations are switched off,
  1665. // emit the branch.
  1666. if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
  1667. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  1668. MVT::Other, getControlRoot(),
  1669. DAG.getBasicBlock(Succ0MBB)));
  1670. return;
  1671. }
  1672. // If this condition is one of the special cases we handle, do special stuff
  1673. // now.
  1674. const Value *CondVal = I.getCondition();
  1675. MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
  1676. // If this is a series of conditions that are or'd or and'd together, emit
  1677. // this as a sequence of branches instead of setcc's with and/or operations.
  1678. // As long as jumps are not expensive, this should improve performance.
  1679. // For example, instead of something like:
  1680. // cmp A, B
  1681. // C = seteq
  1682. // cmp D, E
  1683. // F = setle
  1684. // or C, F
  1685. // jnz foo
  1686. // Emit:
  1687. // cmp A, B
  1688. // je foo
  1689. // cmp D, E
  1690. // jle foo
  1691. if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
  1692. Instruction::BinaryOps Opcode = BOp->getOpcode();
  1693. if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
  1694. !I.getMetadata(LLVMContext::MD_unpredictable) &&
  1695. (Opcode == Instruction::And || Opcode == Instruction::Or)) {
  1696. FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
  1697. Opcode,
  1698. getEdgeProbability(BrMBB, Succ0MBB),
  1699. getEdgeProbability(BrMBB, Succ1MBB),
  1700. /*InvertCond=*/false);
  1701. // If the compares in later blocks need to use values not currently
  1702. // exported from this block, export them now. This block should always
  1703. // be the first entry.
  1704. assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
  1705. // Allow some cases to be rejected.
  1706. if (ShouldEmitAsBranches(SwitchCases)) {
  1707. for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
  1708. ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
  1709. ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
  1710. }
  1711. // Emit the branch for this block.
  1712. visitSwitchCase(SwitchCases[0], BrMBB);
  1713. SwitchCases.erase(SwitchCases.begin());
  1714. return;
  1715. }
  1716. // Okay, we decided not to do this, remove any inserted MBB's and clear
  1717. // SwitchCases.
  1718. for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
  1719. FuncInfo.MF->erase(SwitchCases[i].ThisBB);
  1720. SwitchCases.clear();
  1721. }
  1722. }
  1723. // Create a CaseBlock record representing this branch.
  1724. CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
  1725. nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
  1726. // Use visitSwitchCase to actually insert the fast branch sequence for this
  1727. // cond branch.
  1728. visitSwitchCase(CB, BrMBB);
  1729. }
  1730. /// visitSwitchCase - Emits the necessary code to represent a single node in
  1731. /// the binary search tree resulting from lowering a switch instruction.
  1732. void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
  1733. MachineBasicBlock *SwitchBB) {
  1734. SDValue Cond;
  1735. SDValue CondLHS = getValue(CB.CmpLHS);
  1736. SDLoc dl = CB.DL;
  1737. // Build the setcc now.
  1738. if (!CB.CmpMHS) {
  1739. // Fold "(X == true)" to X and "(X == false)" to !X to
  1740. // handle common cases produced by branch lowering.
  1741. if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
  1742. CB.CC == ISD::SETEQ)
  1743. Cond = CondLHS;
  1744. else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
  1745. CB.CC == ISD::SETEQ) {
  1746. SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
  1747. Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
  1748. } else
  1749. Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
  1750. } else {
  1751. assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
  1752. const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
  1753. const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
  1754. SDValue CmpOp = getValue(CB.CmpMHS);
  1755. EVT VT = CmpOp.getValueType();
  1756. if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
  1757. Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
  1758. ISD::SETLE);
  1759. } else {
  1760. SDValue SUB = DAG.getNode(ISD::SUB, dl,
  1761. VT, CmpOp, DAG.getConstant(Low, dl, VT));
  1762. Cond = DAG.getSetCC(dl, MVT::i1, SUB,
  1763. DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
  1764. }
  1765. }
  1766. // Update successor info
  1767. addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
  1768. // TrueBB and FalseBB are always different unless the incoming IR is
  1769. // degenerate. This only happens when running llc on weird IR.
  1770. if (CB.TrueBB != CB.FalseBB)
  1771. addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
  1772. SwitchBB->normalizeSuccProbs();
  1773. // If the lhs block is the next block, invert the condition so that we can
  1774. // fall through to the lhs instead of the rhs block.
  1775. if (CB.TrueBB == NextBlock(SwitchBB)) {
  1776. std::swap(CB.TrueBB, CB.FalseBB);
  1777. SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
  1778. Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
  1779. }
  1780. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  1781. MVT::Other, getControlRoot(), Cond,
  1782. DAG.getBasicBlock(CB.TrueBB));
  1783. // Insert the false branch. Do this even if it's a fall through branch,
  1784. // this makes it easier to do DAG optimizations which require inverting
  1785. // the branch condition.
  1786. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  1787. DAG.getBasicBlock(CB.FalseBB));
  1788. DAG.setRoot(BrCond);
  1789. }
  1790. /// visitJumpTable - Emit JumpTable node in the current MBB
  1791. void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
  1792. // Emit the code for the jump table
  1793. assert(JT.Reg != -1U && "Should lower JT Header first!");
  1794. EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
  1795. SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
  1796. JT.Reg, PTy);
  1797. SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
  1798. SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
  1799. MVT::Other, Index.getValue(1),
  1800. Table, Index);
  1801. DAG.setRoot(BrJumpTable);
  1802. }
  1803. /// visitJumpTableHeader - This function emits necessary code to produce index
  1804. /// in the JumpTable from switch case.
  1805. void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
  1806. JumpTableHeader &JTH,
  1807. MachineBasicBlock *SwitchBB) {
  1808. SDLoc dl = getCurSDLoc();
  1809. // Subtract the lowest switch case value from the value being switched on and
  1810. // conditional branch to default mbb if the result is greater than the
  1811. // difference between smallest and largest cases.
  1812. SDValue SwitchOp = getValue(JTH.SValue);
  1813. EVT VT = SwitchOp.getValueType();
  1814. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
  1815. DAG.getConstant(JTH.First, dl, VT));
  1816. // The SDNode we just created, which holds the value being switched on minus
  1817. // the smallest case value, needs to be copied to a virtual register so it
  1818. // can be used as an index into the jump table in a subsequent basic block.
  1819. // This value may be smaller or larger than the target's pointer type, and
  1820. // therefore require extension or truncating.
  1821. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1822. SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
  1823. unsigned JumpTableReg =
  1824. FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
  1825. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
  1826. JumpTableReg, SwitchOp);
  1827. JT.Reg = JumpTableReg;
  1828. // Emit the range check for the jump table, and branch to the default block
  1829. // for the switch statement if the value being switched on exceeds the largest
  1830. // case in the switch.
  1831. SDValue CMP = DAG.getSetCC(
  1832. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  1833. Sub.getValueType()),
  1834. Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
  1835. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  1836. MVT::Other, CopyTo, CMP,
  1837. DAG.getBasicBlock(JT.Default));
  1838. // Avoid emitting unnecessary branches to the next block.
  1839. if (JT.MBB != NextBlock(SwitchBB))
  1840. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  1841. DAG.getBasicBlock(JT.MBB));
  1842. DAG.setRoot(BrCond);
  1843. }
  1844. /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
  1845. /// variable if there exists one.
  1846. static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
  1847. SDValue &Chain) {
  1848. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1849. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  1850. MachineFunction &MF = DAG.getMachineFunction();
  1851. Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
  1852. MachineSDNode *Node =
  1853. DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
  1854. if (Global) {
  1855. MachinePointerInfo MPInfo(Global);
  1856. MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
  1857. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
  1858. MachineMemOperand::MODereferenceable;
  1859. *MemRefs = MF.getMachineMemOperand(MPInfo, Flags, PtrTy.getSizeInBits() / 8,
  1860. DAG.getEVTAlignment(PtrTy));
  1861. Node->setMemRefs(MemRefs, MemRefs + 1);
  1862. }
  1863. return SDValue(Node, 0);
  1864. }
  1865. /// Codegen a new tail for a stack protector check ParentMBB which has had its
  1866. /// tail spliced into a stack protector check success bb.
  1867. ///
  1868. /// For a high level explanation of how this fits into the stack protector
  1869. /// generation see the comment on the declaration of class
  1870. /// StackProtectorDescriptor.
  1871. void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
  1872. MachineBasicBlock *ParentBB) {
  1873. // First create the loads to the guard/stack slot for the comparison.
  1874. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1875. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  1876. MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
  1877. int FI = MFI.getStackProtectorIndex();
  1878. SDValue Guard;
  1879. SDLoc dl = getCurSDLoc();
  1880. SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
  1881. const Module &M = *ParentBB->getParent()->getFunction().getParent();
  1882. unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
  1883. // Generate code to load the content of the guard slot.
  1884. SDValue GuardVal = DAG.getLoad(
  1885. PtrTy, dl, DAG.getEntryNode(), StackSlotPtr,
  1886. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
  1887. MachineMemOperand::MOVolatile);
  1888. if (TLI.useStackGuardXorFP())
  1889. GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
  1890. // Retrieve guard check function, nullptr if instrumentation is inlined.
  1891. if (const Value *GuardCheck = TLI.getSSPStackGuardCheck(M)) {
  1892. // The target provides a guard check function to validate the guard value.
  1893. // Generate a call to that function with the content of the guard slot as
  1894. // argument.
  1895. auto *Fn = cast<Function>(GuardCheck);
  1896. FunctionType *FnTy = Fn->getFunctionType();
  1897. assert(FnTy->getNumParams() == 1 && "Invalid function signature");
  1898. TargetLowering::ArgListTy Args;
  1899. TargetLowering::ArgListEntry Entry;
  1900. Entry.Node = GuardVal;
  1901. Entry.Ty = FnTy->getParamType(0);
  1902. if (Fn->hasAttribute(1, Attribute::AttrKind::InReg))
  1903. Entry.IsInReg = true;
  1904. Args.push_back(Entry);
  1905. TargetLowering::CallLoweringInfo CLI(DAG);
  1906. CLI.setDebugLoc(getCurSDLoc())
  1907. .setChain(DAG.getEntryNode())
  1908. .setCallee(Fn->getCallingConv(), FnTy->getReturnType(),
  1909. getValue(GuardCheck), std::move(Args));
  1910. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  1911. DAG.setRoot(Result.second);
  1912. return;
  1913. }
  1914. // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
  1915. // Otherwise, emit a volatile load to retrieve the stack guard value.
  1916. SDValue Chain = DAG.getEntryNode();
  1917. if (TLI.useLoadStackGuardNode()) {
  1918. Guard = getLoadStackGuard(DAG, dl, Chain);
  1919. } else {
  1920. const Value *IRGuard = TLI.getSDagStackGuard(M);
  1921. SDValue GuardPtr = getValue(IRGuard);
  1922. Guard =
  1923. DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0),
  1924. Align, MachineMemOperand::MOVolatile);
  1925. }
  1926. // Perform the comparison via a subtract/getsetcc.
  1927. EVT VT = Guard.getValueType();
  1928. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
  1929. SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
  1930. *DAG.getContext(),
  1931. Sub.getValueType()),
  1932. Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
  1933. // If the sub is not 0, then we know the guard/stackslot do not equal, so
  1934. // branch to failure MBB.
  1935. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  1936. MVT::Other, GuardVal.getOperand(0),
  1937. Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
  1938. // Otherwise branch to success MBB.
  1939. SDValue Br = DAG.getNode(ISD::BR, dl,
  1940. MVT::Other, BrCond,
  1941. DAG.getBasicBlock(SPD.getSuccessMBB()));
  1942. DAG.setRoot(Br);
  1943. }
  1944. /// Codegen the failure basic block for a stack protector check.
  1945. ///
  1946. /// A failure stack protector machine basic block consists simply of a call to
  1947. /// __stack_chk_fail().
  1948. ///
  1949. /// For a high level explanation of how this fits into the stack protector
  1950. /// generation see the comment on the declaration of class
  1951. /// StackProtectorDescriptor.
  1952. void
  1953. SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
  1954. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1955. SDValue Chain =
  1956. TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
  1957. None, false, getCurSDLoc(), false, false).second;
  1958. DAG.setRoot(Chain);
  1959. }
  1960. /// visitBitTestHeader - This function emits necessary code to produce value
  1961. /// suitable for "bit tests"
  1962. void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
  1963. MachineBasicBlock *SwitchBB) {
  1964. SDLoc dl = getCurSDLoc();
  1965. // Subtract the minimum value
  1966. SDValue SwitchOp = getValue(B.SValue);
  1967. EVT VT = SwitchOp.getValueType();
  1968. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
  1969. DAG.getConstant(B.First, dl, VT));
  1970. // Check range
  1971. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1972. SDValue RangeCmp = DAG.getSetCC(
  1973. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  1974. Sub.getValueType()),
  1975. Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
  1976. // Determine the type of the test operands.
  1977. bool UsePtrType = false;
  1978. if (!TLI.isTypeLegal(VT))
  1979. UsePtrType = true;
  1980. else {
  1981. for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
  1982. if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
  1983. // Switch table case range are encoded into series of masks.
  1984. // Just use pointer type, it's guaranteed to fit.
  1985. UsePtrType = true;
  1986. break;
  1987. }
  1988. }
  1989. if (UsePtrType) {
  1990. VT = TLI.getPointerTy(DAG.getDataLayout());
  1991. Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
  1992. }
  1993. B.RegVT = VT.getSimpleVT();
  1994. B.Reg = FuncInfo.CreateReg(B.RegVT);
  1995. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
  1996. MachineBasicBlock* MBB = B.Cases[0].ThisBB;
  1997. addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
  1998. addSuccessorWithProb(SwitchBB, MBB, B.Prob);
  1999. SwitchBB->normalizeSuccProbs();
  2000. SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
  2001. MVT::Other, CopyTo, RangeCmp,
  2002. DAG.getBasicBlock(B.Default));
  2003. // Avoid emitting unnecessary branches to the next block.
  2004. if (MBB != NextBlock(SwitchBB))
  2005. BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
  2006. DAG.getBasicBlock(MBB));
  2007. DAG.setRoot(BrRange);
  2008. }
  2009. /// visitBitTestCase - this function produces one "bit test"
  2010. void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
  2011. MachineBasicBlock* NextMBB,
  2012. BranchProbability BranchProbToNext,
  2013. unsigned Reg,
  2014. BitTestCase &B,
  2015. MachineBasicBlock *SwitchBB) {
  2016. SDLoc dl = getCurSDLoc();
  2017. MVT VT = BB.RegVT;
  2018. SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
  2019. SDValue Cmp;
  2020. unsigned PopCount = countPopulation(B.Mask);
  2021. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2022. if (PopCount == 1) {
  2023. // Testing for a single bit; just compare the shift count with what it
  2024. // would need to be to shift a 1 bit in that position.
  2025. Cmp = DAG.getSetCC(
  2026. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2027. ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
  2028. ISD::SETEQ);
  2029. } else if (PopCount == BB.Range) {
  2030. // There is only one zero bit in the range, test for it directly.
  2031. Cmp = DAG.getSetCC(
  2032. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2033. ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
  2034. ISD::SETNE);
  2035. } else {
  2036. // Make desired shift
  2037. SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
  2038. DAG.getConstant(1, dl, VT), ShiftOp);
  2039. // Emit bit tests and jumps
  2040. SDValue AndOp = DAG.getNode(ISD::AND, dl,
  2041. VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
  2042. Cmp = DAG.getSetCC(
  2043. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2044. AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
  2045. }
  2046. // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
  2047. addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
  2048. // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
  2049. addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
  2050. // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
  2051. // one as they are relative probabilities (and thus work more like weights),
  2052. // and hence we need to normalize them to let the sum of them become one.
  2053. SwitchBB->normalizeSuccProbs();
  2054. SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
  2055. MVT::Other, getControlRoot(),
  2056. Cmp, DAG.getBasicBlock(B.TargetBB));
  2057. // Avoid emitting unnecessary branches to the next block.
  2058. if (NextMBB != NextBlock(SwitchBB))
  2059. BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
  2060. DAG.getBasicBlock(NextMBB));
  2061. DAG.setRoot(BrAnd);
  2062. }
  2063. void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
  2064. MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
  2065. // Retrieve successors. Look through artificial IR level blocks like
  2066. // catchswitch for successors.
  2067. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
  2068. const BasicBlock *EHPadBB = I.getSuccessor(1);
  2069. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  2070. // have to do anything here to lower funclet bundles.
  2071. assert(!I.hasOperandBundlesOtherThan(
  2072. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  2073. "Cannot lower invokes with arbitrary operand bundles yet!");
  2074. const Value *Callee(I.getCalledValue());
  2075. const Function *Fn = dyn_cast<Function>(Callee);
  2076. if (isa<InlineAsm>(Callee))
  2077. visitInlineAsm(&I);
  2078. else if (Fn && Fn->isIntrinsic()) {
  2079. switch (Fn->getIntrinsicID()) {
  2080. default:
  2081. llvm_unreachable("Cannot invoke this intrinsic");
  2082. case Intrinsic::donothing:
  2083. // Ignore invokes to @llvm.donothing: jump directly to the next BB.
  2084. break;
  2085. case Intrinsic::experimental_patchpoint_void:
  2086. case Intrinsic::experimental_patchpoint_i64:
  2087. visitPatchpoint(&I, EHPadBB);
  2088. break;
  2089. case Intrinsic::experimental_gc_statepoint:
  2090. LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
  2091. break;
  2092. }
  2093. } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
  2094. // Currently we do not lower any intrinsic calls with deopt operand bundles.
  2095. // Eventually we will support lowering the @llvm.experimental.deoptimize
  2096. // intrinsic, and right now there are no plans to support other intrinsics
  2097. // with deopt state.
  2098. LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
  2099. } else {
  2100. LowerCallTo(&I, getValue(Callee), false, EHPadBB);
  2101. }
  2102. // If the value of the invoke is used outside of its defining block, make it
  2103. // available as a virtual register.
  2104. // We already took care of the exported value for the statepoint instruction
  2105. // during call to the LowerStatepoint.
  2106. if (!isStatepoint(I)) {
  2107. CopyToExportRegsIfNeeded(&I);
  2108. }
  2109. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  2110. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  2111. BranchProbability EHPadBBProb =
  2112. BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
  2113. : BranchProbability::getZero();
  2114. findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
  2115. // Update successor info.
  2116. addSuccessorWithProb(InvokeMBB, Return);
  2117. for (auto &UnwindDest : UnwindDests) {
  2118. UnwindDest.first->setIsEHPad();
  2119. addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
  2120. }
  2121. InvokeMBB->normalizeSuccProbs();
  2122. // Drop into normal successor.
  2123. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  2124. MVT::Other, getControlRoot(),
  2125. DAG.getBasicBlock(Return)));
  2126. }
  2127. void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
  2128. llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
  2129. }
  2130. void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
  2131. assert(FuncInfo.MBB->isEHPad() &&
  2132. "Call to landingpad not in landing pad!");
  2133. MachineBasicBlock *MBB = FuncInfo.MBB;
  2134. addLandingPadInfo(LP, *MBB);
  2135. // If there aren't registers to copy the values into (e.g., during SjLj
  2136. // exceptions), then don't bother to create these DAG nodes.
  2137. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2138. const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
  2139. if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
  2140. TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
  2141. return;
  2142. // If landingpad's return type is token type, we don't create DAG nodes
  2143. // for its exception pointer and selector value. The extraction of exception
  2144. // pointer or selector value from token type landingpads is not currently
  2145. // supported.
  2146. if (LP.getType()->isTokenTy())
  2147. return;
  2148. SmallVector<EVT, 2> ValueVTs;
  2149. SDLoc dl = getCurSDLoc();
  2150. ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
  2151. assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
  2152. // Get the two live-in registers as SDValues. The physregs have already been
  2153. // copied into virtual registers.
  2154. SDValue Ops[2];
  2155. if (FuncInfo.ExceptionPointerVirtReg) {
  2156. Ops[0] = DAG.getZExtOrTrunc(
  2157. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2158. FuncInfo.ExceptionPointerVirtReg,
  2159. TLI.getPointerTy(DAG.getDataLayout())),
  2160. dl, ValueVTs[0]);
  2161. } else {
  2162. Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
  2163. }
  2164. Ops[1] = DAG.getZExtOrTrunc(
  2165. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2166. FuncInfo.ExceptionSelectorVirtReg,
  2167. TLI.getPointerTy(DAG.getDataLayout())),
  2168. dl, ValueVTs[1]);
  2169. // Merge into one.
  2170. SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
  2171. DAG.getVTList(ValueVTs), Ops);
  2172. setValue(&LP, Res);
  2173. }
  2174. void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
  2175. #ifndef NDEBUG
  2176. for (const CaseCluster &CC : Clusters)
  2177. assert(CC.Low == CC.High && "Input clusters must be single-case");
  2178. #endif
  2179. std::sort(Clusters.begin(), Clusters.end(),
  2180. [](const CaseCluster &a, const CaseCluster &b) {
  2181. return a.Low->getValue().slt(b.Low->getValue());
  2182. });
  2183. // Merge adjacent clusters with the same destination.
  2184. const unsigned N = Clusters.size();
  2185. unsigned DstIndex = 0;
  2186. for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
  2187. CaseCluster &CC = Clusters[SrcIndex];
  2188. const ConstantInt *CaseVal = CC.Low;
  2189. MachineBasicBlock *Succ = CC.MBB;
  2190. if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
  2191. (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
  2192. // If this case has the same successor and is a neighbour, merge it into
  2193. // the previous cluster.
  2194. Clusters[DstIndex - 1].High = CaseVal;
  2195. Clusters[DstIndex - 1].Prob += CC.Prob;
  2196. } else {
  2197. std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
  2198. sizeof(Clusters[SrcIndex]));
  2199. }
  2200. }
  2201. Clusters.resize(DstIndex);
  2202. }
  2203. void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
  2204. MachineBasicBlock *Last) {
  2205. // Update JTCases.
  2206. for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
  2207. if (JTCases[i].first.HeaderBB == First)
  2208. JTCases[i].first.HeaderBB = Last;
  2209. // Update BitTestCases.
  2210. for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
  2211. if (BitTestCases[i].Parent == First)
  2212. BitTestCases[i].Parent = Last;
  2213. }
  2214. void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
  2215. MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
  2216. // Update machine-CFG edges with unique successors.
  2217. SmallSet<BasicBlock*, 32> Done;
  2218. for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
  2219. BasicBlock *BB = I.getSuccessor(i);
  2220. bool Inserted = Done.insert(BB).second;
  2221. if (!Inserted)
  2222. continue;
  2223. MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
  2224. addSuccessorWithProb(IndirectBrMBB, Succ);
  2225. }
  2226. IndirectBrMBB->normalizeSuccProbs();
  2227. DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
  2228. MVT::Other, getControlRoot(),
  2229. getValue(I.getAddress())));
  2230. }
  2231. void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
  2232. if (DAG.getTarget().Options.TrapUnreachable)
  2233. DAG.setRoot(
  2234. DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
  2235. }
  2236. void SelectionDAGBuilder::visitFSub(const User &I) {
  2237. // -0.0 - X --> fneg
  2238. Type *Ty = I.getType();
  2239. if (isa<Constant>(I.getOperand(0)) &&
  2240. I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
  2241. SDValue Op2 = getValue(I.getOperand(1));
  2242. setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
  2243. Op2.getValueType(), Op2));
  2244. return;
  2245. }
  2246. visitBinary(I, ISD::FSUB);
  2247. }
  2248. /// Checks if the given instruction performs a vector reduction, in which case
  2249. /// we have the freedom to alter the elements in the result as long as the
  2250. /// reduction of them stays unchanged.
  2251. static bool isVectorReductionOp(const User *I) {
  2252. const Instruction *Inst = dyn_cast<Instruction>(I);
  2253. if (!Inst || !Inst->getType()->isVectorTy())
  2254. return false;
  2255. auto OpCode = Inst->getOpcode();
  2256. switch (OpCode) {
  2257. case Instruction::Add:
  2258. case Instruction::Mul:
  2259. case Instruction::And:
  2260. case Instruction::Or:
  2261. case Instruction::Xor:
  2262. break;
  2263. case Instruction::FAdd:
  2264. case Instruction::FMul:
  2265. if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
  2266. if (FPOp->getFastMathFlags().isFast())
  2267. break;
  2268. LLVM_FALLTHROUGH;
  2269. default:
  2270. return false;
  2271. }
  2272. unsigned ElemNum = Inst->getType()->getVectorNumElements();
  2273. unsigned ElemNumToReduce = ElemNum;
  2274. // Do DFS search on the def-use chain from the given instruction. We only
  2275. // allow four kinds of operations during the search until we reach the
  2276. // instruction that extracts the first element from the vector:
  2277. //
  2278. // 1. The reduction operation of the same opcode as the given instruction.
  2279. //
  2280. // 2. PHI node.
  2281. //
  2282. // 3. ShuffleVector instruction together with a reduction operation that
  2283. // does a partial reduction.
  2284. //
  2285. // 4. ExtractElement that extracts the first element from the vector, and we
  2286. // stop searching the def-use chain here.
  2287. //
  2288. // 3 & 4 above perform a reduction on all elements of the vector. We push defs
  2289. // from 1-3 to the stack to continue the DFS. The given instruction is not
  2290. // a reduction operation if we meet any other instructions other than those
  2291. // listed above.
  2292. SmallVector<const User *, 16> UsersToVisit{Inst};
  2293. SmallPtrSet<const User *, 16> Visited;
  2294. bool ReduxExtracted = false;
  2295. while (!UsersToVisit.empty()) {
  2296. auto User = UsersToVisit.back();
  2297. UsersToVisit.pop_back();
  2298. if (!Visited.insert(User).second)
  2299. continue;
  2300. for (const auto &U : User->users()) {
  2301. auto Inst = dyn_cast<Instruction>(U);
  2302. if (!Inst)
  2303. return false;
  2304. if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
  2305. if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
  2306. if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
  2307. return false;
  2308. UsersToVisit.push_back(U);
  2309. } else if (const ShuffleVectorInst *ShufInst =
  2310. dyn_cast<ShuffleVectorInst>(U)) {
  2311. // Detect the following pattern: A ShuffleVector instruction together
  2312. // with a reduction that do partial reduction on the first and second
  2313. // ElemNumToReduce / 2 elements, and store the result in
  2314. // ElemNumToReduce / 2 elements in another vector.
  2315. unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
  2316. if (ResultElements < ElemNum)
  2317. return false;
  2318. if (ElemNumToReduce == 1)
  2319. return false;
  2320. if (!isa<UndefValue>(U->getOperand(1)))
  2321. return false;
  2322. for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
  2323. if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
  2324. return false;
  2325. for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
  2326. if (ShufInst->getMaskValue(i) != -1)
  2327. return false;
  2328. // There is only one user of this ShuffleVector instruction, which
  2329. // must be a reduction operation.
  2330. if (!U->hasOneUse())
  2331. return false;
  2332. auto U2 = dyn_cast<Instruction>(*U->user_begin());
  2333. if (!U2 || U2->getOpcode() != OpCode)
  2334. return false;
  2335. // Check operands of the reduction operation.
  2336. if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
  2337. (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
  2338. UsersToVisit.push_back(U2);
  2339. ElemNumToReduce /= 2;
  2340. } else
  2341. return false;
  2342. } else if (isa<ExtractElementInst>(U)) {
  2343. // At this moment we should have reduced all elements in the vector.
  2344. if (ElemNumToReduce != 1)
  2345. return false;
  2346. const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
  2347. if (!Val || Val->getZExtValue() != 0)
  2348. return false;
  2349. ReduxExtracted = true;
  2350. } else
  2351. return false;
  2352. }
  2353. }
  2354. return ReduxExtracted;
  2355. }
  2356. void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
  2357. SDValue Op1 = getValue(I.getOperand(0));
  2358. SDValue Op2 = getValue(I.getOperand(1));
  2359. bool nuw = false;
  2360. bool nsw = false;
  2361. bool exact = false;
  2362. bool vec_redux = false;
  2363. FastMathFlags FMF;
  2364. if (const OverflowingBinaryOperator *OFBinOp =
  2365. dyn_cast<const OverflowingBinaryOperator>(&I)) {
  2366. nuw = OFBinOp->hasNoUnsignedWrap();
  2367. nsw = OFBinOp->hasNoSignedWrap();
  2368. }
  2369. if (const PossiblyExactOperator *ExactOp =
  2370. dyn_cast<const PossiblyExactOperator>(&I))
  2371. exact = ExactOp->isExact();
  2372. if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(&I))
  2373. FMF = FPOp->getFastMathFlags();
  2374. if (isVectorReductionOp(&I)) {
  2375. vec_redux = true;
  2376. DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
  2377. }
  2378. SDNodeFlags Flags;
  2379. Flags.setExact(exact);
  2380. Flags.setNoSignedWrap(nsw);
  2381. Flags.setNoUnsignedWrap(nuw);
  2382. Flags.setVectorReduction(vec_redux);
  2383. Flags.setAllowReciprocal(FMF.allowReciprocal());
  2384. Flags.setAllowContract(FMF.allowContract());
  2385. Flags.setNoInfs(FMF.noInfs());
  2386. Flags.setNoNaNs(FMF.noNaNs());
  2387. Flags.setNoSignedZeros(FMF.noSignedZeros());
  2388. Flags.setUnsafeAlgebra(FMF.isFast());
  2389. SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(),
  2390. Op1, Op2, Flags);
  2391. setValue(&I, BinNodeValue);
  2392. }
  2393. void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
  2394. SDValue Op1 = getValue(I.getOperand(0));
  2395. SDValue Op2 = getValue(I.getOperand(1));
  2396. EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
  2397. Op2.getValueType(), DAG.getDataLayout());
  2398. // Coerce the shift amount to the right type if we can.
  2399. if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
  2400. unsigned ShiftSize = ShiftTy.getSizeInBits();
  2401. unsigned Op2Size = Op2.getValueSizeInBits();
  2402. SDLoc DL = getCurSDLoc();
  2403. // If the operand is smaller than the shift count type, promote it.
  2404. if (ShiftSize > Op2Size)
  2405. Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
  2406. // If the operand is larger than the shift count type but the shift
  2407. // count type has enough bits to represent any shift value, truncate
  2408. // it now. This is a common case and it exposes the truncate to
  2409. // optimization early.
  2410. else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
  2411. Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
  2412. // Otherwise we'll need to temporarily settle for some other convenient
  2413. // type. Type legalization will make adjustments once the shiftee is split.
  2414. else
  2415. Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
  2416. }
  2417. bool nuw = false;
  2418. bool nsw = false;
  2419. bool exact = false;
  2420. if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
  2421. if (const OverflowingBinaryOperator *OFBinOp =
  2422. dyn_cast<const OverflowingBinaryOperator>(&I)) {
  2423. nuw = OFBinOp->hasNoUnsignedWrap();
  2424. nsw = OFBinOp->hasNoSignedWrap();
  2425. }
  2426. if (const PossiblyExactOperator *ExactOp =
  2427. dyn_cast<const PossiblyExactOperator>(&I))
  2428. exact = ExactOp->isExact();
  2429. }
  2430. SDNodeFlags Flags;
  2431. Flags.setExact(exact);
  2432. Flags.setNoSignedWrap(nsw);
  2433. Flags.setNoUnsignedWrap(nuw);
  2434. SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
  2435. Flags);
  2436. setValue(&I, Res);
  2437. }
  2438. void SelectionDAGBuilder::visitSDiv(const User &I) {
  2439. SDValue Op1 = getValue(I.getOperand(0));
  2440. SDValue Op2 = getValue(I.getOperand(1));
  2441. SDNodeFlags Flags;
  2442. Flags.setExact(isa<PossiblyExactOperator>(&I) &&
  2443. cast<PossiblyExactOperator>(&I)->isExact());
  2444. setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
  2445. Op2, Flags));
  2446. }
  2447. void SelectionDAGBuilder::visitICmp(const User &I) {
  2448. ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
  2449. if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
  2450. predicate = IC->getPredicate();
  2451. else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
  2452. predicate = ICmpInst::Predicate(IC->getPredicate());
  2453. SDValue Op1 = getValue(I.getOperand(0));
  2454. SDValue Op2 = getValue(I.getOperand(1));
  2455. ISD::CondCode Opcode = getICmpCondCode(predicate);
  2456. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2457. I.getType());
  2458. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
  2459. }
  2460. void SelectionDAGBuilder::visitFCmp(const User &I) {
  2461. FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
  2462. if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
  2463. predicate = FC->getPredicate();
  2464. else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
  2465. predicate = FCmpInst::Predicate(FC->getPredicate());
  2466. SDValue Op1 = getValue(I.getOperand(0));
  2467. SDValue Op2 = getValue(I.getOperand(1));
  2468. ISD::CondCode Condition = getFCmpCondCode(predicate);
  2469. // FIXME: Fcmp instructions have fast-math-flags in IR, so we should use them.
  2470. // FIXME: We should propagate the fast-math-flags to the DAG node itself for
  2471. // further optimization, but currently FMF is only applicable to binary nodes.
  2472. if (TM.Options.NoNaNsFPMath)
  2473. Condition = getFCmpCodeWithoutNaN(Condition);
  2474. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2475. I.getType());
  2476. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
  2477. }
  2478. // Check if the condition of the select has one use or two users that are both
  2479. // selects with the same condition.
  2480. static bool hasOnlySelectUsers(const Value *Cond) {
  2481. return llvm::all_of(Cond->users(), [](const Value *V) {
  2482. return isa<SelectInst>(V);
  2483. });
  2484. }
  2485. void SelectionDAGBuilder::visitSelect(const User &I) {
  2486. SmallVector<EVT, 4> ValueVTs;
  2487. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
  2488. ValueVTs);
  2489. unsigned NumValues = ValueVTs.size();
  2490. if (NumValues == 0) return;
  2491. SmallVector<SDValue, 4> Values(NumValues);
  2492. SDValue Cond = getValue(I.getOperand(0));
  2493. SDValue LHSVal = getValue(I.getOperand(1));
  2494. SDValue RHSVal = getValue(I.getOperand(2));
  2495. auto BaseOps = {Cond};
  2496. ISD::NodeType OpCode = Cond.getValueType().isVector() ?
  2497. ISD::VSELECT : ISD::SELECT;
  2498. // Min/max matching is only viable if all output VTs are the same.
  2499. if (std::equal(ValueVTs.begin(), ValueVTs.end(), ValueVTs.begin())) {
  2500. EVT VT = ValueVTs[0];
  2501. LLVMContext &Ctx = *DAG.getContext();
  2502. auto &TLI = DAG.getTargetLoweringInfo();
  2503. // We care about the legality of the operation after it has been type
  2504. // legalized.
  2505. while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
  2506. VT != TLI.getTypeToTransformTo(Ctx, VT))
  2507. VT = TLI.getTypeToTransformTo(Ctx, VT);
  2508. // If the vselect is legal, assume we want to leave this as a vector setcc +
  2509. // vselect. Otherwise, if this is going to be scalarized, we want to see if
  2510. // min/max is legal on the scalar type.
  2511. bool UseScalarMinMax = VT.isVector() &&
  2512. !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
  2513. Value *LHS, *RHS;
  2514. auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
  2515. ISD::NodeType Opc = ISD::DELETED_NODE;
  2516. switch (SPR.Flavor) {
  2517. case SPF_UMAX: Opc = ISD::UMAX; break;
  2518. case SPF_UMIN: Opc = ISD::UMIN; break;
  2519. case SPF_SMAX: Opc = ISD::SMAX; break;
  2520. case SPF_SMIN: Opc = ISD::SMIN; break;
  2521. case SPF_FMINNUM:
  2522. switch (SPR.NaNBehavior) {
  2523. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2524. case SPNB_RETURNS_NAN: Opc = ISD::FMINNAN; break;
  2525. case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
  2526. case SPNB_RETURNS_ANY: {
  2527. if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
  2528. Opc = ISD::FMINNUM;
  2529. else if (TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT))
  2530. Opc = ISD::FMINNAN;
  2531. else if (UseScalarMinMax)
  2532. Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
  2533. ISD::FMINNUM : ISD::FMINNAN;
  2534. break;
  2535. }
  2536. }
  2537. break;
  2538. case SPF_FMAXNUM:
  2539. switch (SPR.NaNBehavior) {
  2540. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2541. case SPNB_RETURNS_NAN: Opc = ISD::FMAXNAN; break;
  2542. case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
  2543. case SPNB_RETURNS_ANY:
  2544. if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
  2545. Opc = ISD::FMAXNUM;
  2546. else if (TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT))
  2547. Opc = ISD::FMAXNAN;
  2548. else if (UseScalarMinMax)
  2549. Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
  2550. ISD::FMAXNUM : ISD::FMAXNAN;
  2551. break;
  2552. }
  2553. break;
  2554. default: break;
  2555. }
  2556. if (Opc != ISD::DELETED_NODE &&
  2557. (TLI.isOperationLegalOrCustom(Opc, VT) ||
  2558. (UseScalarMinMax &&
  2559. TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
  2560. // If the underlying comparison instruction is used by any other
  2561. // instruction, the consumed instructions won't be destroyed, so it is
  2562. // not profitable to convert to a min/max.
  2563. hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
  2564. OpCode = Opc;
  2565. LHSVal = getValue(LHS);
  2566. RHSVal = getValue(RHS);
  2567. BaseOps = {};
  2568. }
  2569. }
  2570. for (unsigned i = 0; i != NumValues; ++i) {
  2571. SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
  2572. Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
  2573. Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
  2574. Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
  2575. LHSVal.getNode()->getValueType(LHSVal.getResNo()+i),
  2576. Ops);
  2577. }
  2578. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2579. DAG.getVTList(ValueVTs), Values));
  2580. }
  2581. void SelectionDAGBuilder::visitTrunc(const User &I) {
  2582. // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
  2583. SDValue N = getValue(I.getOperand(0));
  2584. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2585. I.getType());
  2586. setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
  2587. }
  2588. void SelectionDAGBuilder::visitZExt(const User &I) {
  2589. // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2590. // ZExt also can't be a cast to bool for same reason. So, nothing much to do
  2591. SDValue N = getValue(I.getOperand(0));
  2592. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2593. I.getType());
  2594. setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
  2595. }
  2596. void SelectionDAGBuilder::visitSExt(const User &I) {
  2597. // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2598. // SExt also can't be a cast to bool for same reason. So, nothing much to do
  2599. SDValue N = getValue(I.getOperand(0));
  2600. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2601. I.getType());
  2602. setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
  2603. }
  2604. void SelectionDAGBuilder::visitFPTrunc(const User &I) {
  2605. // FPTrunc is never a no-op cast, no need to check
  2606. SDValue N = getValue(I.getOperand(0));
  2607. SDLoc dl = getCurSDLoc();
  2608. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2609. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  2610. setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
  2611. DAG.getTargetConstant(
  2612. 0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
  2613. }
  2614. void SelectionDAGBuilder::visitFPExt(const User &I) {
  2615. // FPExt is never a no-op cast, no need to check
  2616. SDValue N = getValue(I.getOperand(0));
  2617. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2618. I.getType());
  2619. setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
  2620. }
  2621. void SelectionDAGBuilder::visitFPToUI(const User &I) {
  2622. // FPToUI is never a no-op cast, no need to check
  2623. SDValue N = getValue(I.getOperand(0));
  2624. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2625. I.getType());
  2626. setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
  2627. }
  2628. void SelectionDAGBuilder::visitFPToSI(const User &I) {
  2629. // FPToSI is never a no-op cast, no need to check
  2630. SDValue N = getValue(I.getOperand(0));
  2631. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2632. I.getType());
  2633. setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
  2634. }
  2635. void SelectionDAGBuilder::visitUIToFP(const User &I) {
  2636. // UIToFP is never a no-op cast, no need to check
  2637. SDValue N = getValue(I.getOperand(0));
  2638. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2639. I.getType());
  2640. setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
  2641. }
  2642. void SelectionDAGBuilder::visitSIToFP(const User &I) {
  2643. // SIToFP is never a no-op cast, no need to check
  2644. SDValue N = getValue(I.getOperand(0));
  2645. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2646. I.getType());
  2647. setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
  2648. }
  2649. void SelectionDAGBuilder::visitPtrToInt(const User &I) {
  2650. // What to do depends on the size of the integer and the size of the pointer.
  2651. // We can either truncate, zero extend, or no-op, accordingly.
  2652. SDValue N = getValue(I.getOperand(0));
  2653. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2654. I.getType());
  2655. setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
  2656. }
  2657. void SelectionDAGBuilder::visitIntToPtr(const User &I) {
  2658. // What to do depends on the size of the integer and the size of the pointer.
  2659. // We can either truncate, zero extend, or no-op, accordingly.
  2660. SDValue N = getValue(I.getOperand(0));
  2661. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2662. I.getType());
  2663. setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
  2664. }
  2665. void SelectionDAGBuilder::visitBitCast(const User &I) {
  2666. SDValue N = getValue(I.getOperand(0));
  2667. SDLoc dl = getCurSDLoc();
  2668. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2669. I.getType());
  2670. // BitCast assures us that source and destination are the same size so this is
  2671. // either a BITCAST or a no-op.
  2672. if (DestVT != N.getValueType())
  2673. setValue(&I, DAG.getNode(ISD::BITCAST, dl,
  2674. DestVT, N)); // convert types.
  2675. // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
  2676. // might fold any kind of constant expression to an integer constant and that
  2677. // is not what we are looking for. Only recognize a bitcast of a genuine
  2678. // constant integer as an opaque constant.
  2679. else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
  2680. setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
  2681. /*isOpaque*/true));
  2682. else
  2683. setValue(&I, N); // noop cast.
  2684. }
  2685. void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
  2686. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2687. const Value *SV = I.getOperand(0);
  2688. SDValue N = getValue(SV);
  2689. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  2690. unsigned SrcAS = SV->getType()->getPointerAddressSpace();
  2691. unsigned DestAS = I.getType()->getPointerAddressSpace();
  2692. if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
  2693. N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
  2694. setValue(&I, N);
  2695. }
  2696. void SelectionDAGBuilder::visitInsertElement(const User &I) {
  2697. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2698. SDValue InVec = getValue(I.getOperand(0));
  2699. SDValue InVal = getValue(I.getOperand(1));
  2700. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
  2701. TLI.getVectorIdxTy(DAG.getDataLayout()));
  2702. setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
  2703. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  2704. InVec, InVal, InIdx));
  2705. }
  2706. void SelectionDAGBuilder::visitExtractElement(const User &I) {
  2707. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2708. SDValue InVec = getValue(I.getOperand(0));
  2709. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
  2710. TLI.getVectorIdxTy(DAG.getDataLayout()));
  2711. setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
  2712. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  2713. InVec, InIdx));
  2714. }
  2715. void SelectionDAGBuilder::visitShuffleVector(const User &I) {
  2716. SDValue Src1 = getValue(I.getOperand(0));
  2717. SDValue Src2 = getValue(I.getOperand(1));
  2718. SDLoc DL = getCurSDLoc();
  2719. SmallVector<int, 8> Mask;
  2720. ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
  2721. unsigned MaskNumElts = Mask.size();
  2722. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2723. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  2724. EVT SrcVT = Src1.getValueType();
  2725. unsigned SrcNumElts = SrcVT.getVectorNumElements();
  2726. if (SrcNumElts == MaskNumElts) {
  2727. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
  2728. return;
  2729. }
  2730. // Normalize the shuffle vector since mask and vector length don't match.
  2731. if (SrcNumElts < MaskNumElts) {
  2732. // Mask is longer than the source vectors. We can use concatenate vector to
  2733. // make the mask and vectors lengths match.
  2734. if (MaskNumElts % SrcNumElts == 0) {
  2735. // Mask length is a multiple of the source vector length.
  2736. // Check if the shuffle is some kind of concatenation of the input
  2737. // vectors.
  2738. unsigned NumConcat = MaskNumElts / SrcNumElts;
  2739. bool IsConcat = true;
  2740. SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
  2741. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2742. int Idx = Mask[i];
  2743. if (Idx < 0)
  2744. continue;
  2745. // Ensure the indices in each SrcVT sized piece are sequential and that
  2746. // the same source is used for the whole piece.
  2747. if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
  2748. (ConcatSrcs[i / SrcNumElts] >= 0 &&
  2749. ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
  2750. IsConcat = false;
  2751. break;
  2752. }
  2753. // Remember which source this index came from.
  2754. ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
  2755. }
  2756. // The shuffle is concatenating multiple vectors together. Just emit
  2757. // a CONCAT_VECTORS operation.
  2758. if (IsConcat) {
  2759. SmallVector<SDValue, 8> ConcatOps;
  2760. for (auto Src : ConcatSrcs) {
  2761. if (Src < 0)
  2762. ConcatOps.push_back(DAG.getUNDEF(SrcVT));
  2763. else if (Src == 0)
  2764. ConcatOps.push_back(Src1);
  2765. else
  2766. ConcatOps.push_back(Src2);
  2767. }
  2768. setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
  2769. return;
  2770. }
  2771. }
  2772. unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
  2773. unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
  2774. EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
  2775. PaddedMaskNumElts);
  2776. // Pad both vectors with undefs to make them the same length as the mask.
  2777. SDValue UndefVal = DAG.getUNDEF(SrcVT);
  2778. SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
  2779. SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
  2780. MOps1[0] = Src1;
  2781. MOps2[0] = Src2;
  2782. Src1 = Src1.isUndef()
  2783. ? DAG.getUNDEF(PaddedVT)
  2784. : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
  2785. Src2 = Src2.isUndef()
  2786. ? DAG.getUNDEF(PaddedVT)
  2787. : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
  2788. // Readjust mask for new input vector length.
  2789. SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
  2790. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2791. int Idx = Mask[i];
  2792. if (Idx >= (int)SrcNumElts)
  2793. Idx -= SrcNumElts - PaddedMaskNumElts;
  2794. MappedOps[i] = Idx;
  2795. }
  2796. SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
  2797. // If the concatenated vector was padded, extract a subvector with the
  2798. // correct number of elements.
  2799. if (MaskNumElts != PaddedMaskNumElts)
  2800. Result = DAG.getNode(
  2801. ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
  2802. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  2803. setValue(&I, Result);
  2804. return;
  2805. }
  2806. if (SrcNumElts > MaskNumElts) {
  2807. // Analyze the access pattern of the vector to see if we can extract
  2808. // two subvectors and do the shuffle.
  2809. int StartIdx[2] = { -1, -1 }; // StartIdx to extract from
  2810. bool CanExtract = true;
  2811. for (int Idx : Mask) {
  2812. unsigned Input = 0;
  2813. if (Idx < 0)
  2814. continue;
  2815. if (Idx >= (int)SrcNumElts) {
  2816. Input = 1;
  2817. Idx -= SrcNumElts;
  2818. }
  2819. // If all the indices come from the same MaskNumElts sized portion of
  2820. // the sources we can use extract. Also make sure the extract wouldn't
  2821. // extract past the end of the source.
  2822. int NewStartIdx = alignDown(Idx, MaskNumElts);
  2823. if (NewStartIdx + MaskNumElts > SrcNumElts ||
  2824. (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
  2825. CanExtract = false;
  2826. // Make sure we always update StartIdx as we use it to track if all
  2827. // elements are undef.
  2828. StartIdx[Input] = NewStartIdx;
  2829. }
  2830. if (StartIdx[0] < 0 && StartIdx[1] < 0) {
  2831. setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
  2832. return;
  2833. }
  2834. if (CanExtract) {
  2835. // Extract appropriate subvector and generate a vector shuffle
  2836. for (unsigned Input = 0; Input < 2; ++Input) {
  2837. SDValue &Src = Input == 0 ? Src1 : Src2;
  2838. if (StartIdx[Input] < 0)
  2839. Src = DAG.getUNDEF(VT);
  2840. else {
  2841. Src = DAG.getNode(
  2842. ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
  2843. DAG.getConstant(StartIdx[Input], DL,
  2844. TLI.getVectorIdxTy(DAG.getDataLayout())));
  2845. }
  2846. }
  2847. // Calculate new mask.
  2848. SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
  2849. for (int &Idx : MappedOps) {
  2850. if (Idx >= (int)SrcNumElts)
  2851. Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
  2852. else if (Idx >= 0)
  2853. Idx -= StartIdx[0];
  2854. }
  2855. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
  2856. return;
  2857. }
  2858. }
  2859. // We can't use either concat vectors or extract subvectors so fall back to
  2860. // replacing the shuffle with extract and build vector.
  2861. // to insert and build vector.
  2862. EVT EltVT = VT.getVectorElementType();
  2863. EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
  2864. SmallVector<SDValue,8> Ops;
  2865. for (int Idx : Mask) {
  2866. SDValue Res;
  2867. if (Idx < 0) {
  2868. Res = DAG.getUNDEF(EltVT);
  2869. } else {
  2870. SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
  2871. if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
  2872. Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
  2873. EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
  2874. }
  2875. Ops.push_back(Res);
  2876. }
  2877. setValue(&I, DAG.getBuildVector(VT, DL, Ops));
  2878. }
  2879. void SelectionDAGBuilder::visitInsertValue(const User &I) {
  2880. ArrayRef<unsigned> Indices;
  2881. if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
  2882. Indices = IV->getIndices();
  2883. else
  2884. Indices = cast<ConstantExpr>(&I)->getIndices();
  2885. const Value *Op0 = I.getOperand(0);
  2886. const Value *Op1 = I.getOperand(1);
  2887. Type *AggTy = I.getType();
  2888. Type *ValTy = Op1->getType();
  2889. bool IntoUndef = isa<UndefValue>(Op0);
  2890. bool FromUndef = isa<UndefValue>(Op1);
  2891. unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
  2892. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2893. SmallVector<EVT, 4> AggValueVTs;
  2894. ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
  2895. SmallVector<EVT, 4> ValValueVTs;
  2896. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  2897. unsigned NumAggValues = AggValueVTs.size();
  2898. unsigned NumValValues = ValValueVTs.size();
  2899. SmallVector<SDValue, 4> Values(NumAggValues);
  2900. // Ignore an insertvalue that produces an empty object
  2901. if (!NumAggValues) {
  2902. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  2903. return;
  2904. }
  2905. SDValue Agg = getValue(Op0);
  2906. unsigned i = 0;
  2907. // Copy the beginning value(s) from the original aggregate.
  2908. for (; i != LinearIndex; ++i)
  2909. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2910. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2911. // Copy values from the inserted value(s).
  2912. if (NumValValues) {
  2913. SDValue Val = getValue(Op1);
  2914. for (; i != LinearIndex + NumValValues; ++i)
  2915. Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2916. SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
  2917. }
  2918. // Copy remaining value(s) from the original aggregate.
  2919. for (; i != NumAggValues; ++i)
  2920. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2921. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2922. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2923. DAG.getVTList(AggValueVTs), Values));
  2924. }
  2925. void SelectionDAGBuilder::visitExtractValue(const User &I) {
  2926. ArrayRef<unsigned> Indices;
  2927. if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
  2928. Indices = EV->getIndices();
  2929. else
  2930. Indices = cast<ConstantExpr>(&I)->getIndices();
  2931. const Value *Op0 = I.getOperand(0);
  2932. Type *AggTy = Op0->getType();
  2933. Type *ValTy = I.getType();
  2934. bool OutOfUndef = isa<UndefValue>(Op0);
  2935. unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
  2936. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2937. SmallVector<EVT, 4> ValValueVTs;
  2938. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  2939. unsigned NumValValues = ValValueVTs.size();
  2940. // Ignore a extractvalue that produces an empty object
  2941. if (!NumValValues) {
  2942. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  2943. return;
  2944. }
  2945. SmallVector<SDValue, 4> Values(NumValValues);
  2946. SDValue Agg = getValue(Op0);
  2947. // Copy out the selected value(s).
  2948. for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
  2949. Values[i - LinearIndex] =
  2950. OutOfUndef ?
  2951. DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
  2952. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2953. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2954. DAG.getVTList(ValValueVTs), Values));
  2955. }
  2956. void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
  2957. Value *Op0 = I.getOperand(0);
  2958. // Note that the pointer operand may be a vector of pointers. Take the scalar
  2959. // element which holds a pointer.
  2960. unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
  2961. SDValue N = getValue(Op0);
  2962. SDLoc dl = getCurSDLoc();
  2963. // Normalize Vector GEP - all scalar operands should be converted to the
  2964. // splat vector.
  2965. unsigned VectorWidth = I.getType()->isVectorTy() ?
  2966. cast<VectorType>(I.getType())->getVectorNumElements() : 0;
  2967. if (VectorWidth && !N.getValueType().isVector()) {
  2968. LLVMContext &Context = *DAG.getContext();
  2969. EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
  2970. N = DAG.getSplatBuildVector(VT, dl, N);
  2971. }
  2972. for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
  2973. GTI != E; ++GTI) {
  2974. const Value *Idx = GTI.getOperand();
  2975. if (StructType *StTy = GTI.getStructTypeOrNull()) {
  2976. unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
  2977. if (Field) {
  2978. // N = N + Offset
  2979. uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
  2980. // In an inbounds GEP with an offset that is nonnegative even when
  2981. // interpreted as signed, assume there is no unsigned overflow.
  2982. SDNodeFlags Flags;
  2983. if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
  2984. Flags.setNoUnsignedWrap(true);
  2985. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
  2986. DAG.getConstant(Offset, dl, N.getValueType()), Flags);
  2987. }
  2988. } else {
  2989. MVT PtrTy =
  2990. DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout(), AS);
  2991. unsigned PtrSize = PtrTy.getSizeInBits();
  2992. APInt ElementSize(PtrSize, DL->getTypeAllocSize(GTI.getIndexedType()));
  2993. // If this is a scalar constant or a splat vector of constants,
  2994. // handle it quickly.
  2995. const auto *CI = dyn_cast<ConstantInt>(Idx);
  2996. if (!CI && isa<ConstantDataVector>(Idx) &&
  2997. cast<ConstantDataVector>(Idx)->getSplatValue())
  2998. CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
  2999. if (CI) {
  3000. if (CI->isZero())
  3001. continue;
  3002. APInt Offs = ElementSize * CI->getValue().sextOrTrunc(PtrSize);
  3003. LLVMContext &Context = *DAG.getContext();
  3004. SDValue OffsVal = VectorWidth ?
  3005. DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, PtrTy, VectorWidth)) :
  3006. DAG.getConstant(Offs, dl, PtrTy);
  3007. // In an inbouds GEP with an offset that is nonnegative even when
  3008. // interpreted as signed, assume there is no unsigned overflow.
  3009. SDNodeFlags Flags;
  3010. if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
  3011. Flags.setNoUnsignedWrap(true);
  3012. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
  3013. continue;
  3014. }
  3015. // N = N + Idx * ElementSize;
  3016. SDValue IdxN = getValue(Idx);
  3017. if (!IdxN.getValueType().isVector() && VectorWidth) {
  3018. EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
  3019. IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
  3020. }
  3021. // If the index is smaller or larger than intptr_t, truncate or extend
  3022. // it.
  3023. IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
  3024. // If this is a multiply by a power of two, turn it into a shl
  3025. // immediately. This is a very common case.
  3026. if (ElementSize != 1) {
  3027. if (ElementSize.isPowerOf2()) {
  3028. unsigned Amt = ElementSize.logBase2();
  3029. IdxN = DAG.getNode(ISD::SHL, dl,
  3030. N.getValueType(), IdxN,
  3031. DAG.getConstant(Amt, dl, IdxN.getValueType()));
  3032. } else {
  3033. SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
  3034. IdxN = DAG.getNode(ISD::MUL, dl,
  3035. N.getValueType(), IdxN, Scale);
  3036. }
  3037. }
  3038. N = DAG.getNode(ISD::ADD, dl,
  3039. N.getValueType(), N, IdxN);
  3040. }
  3041. }
  3042. setValue(&I, N);
  3043. }
  3044. void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
  3045. // If this is a fixed sized alloca in the entry block of the function,
  3046. // allocate it statically on the stack.
  3047. if (FuncInfo.StaticAllocaMap.count(&I))
  3048. return; // getValue will auto-populate this.
  3049. SDLoc dl = getCurSDLoc();
  3050. Type *Ty = I.getAllocatedType();
  3051. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3052. auto &DL = DAG.getDataLayout();
  3053. uint64_t TySize = DL.getTypeAllocSize(Ty);
  3054. unsigned Align =
  3055. std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
  3056. SDValue AllocSize = getValue(I.getArraySize());
  3057. EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
  3058. if (AllocSize.getValueType() != IntPtr)
  3059. AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
  3060. AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
  3061. AllocSize,
  3062. DAG.getConstant(TySize, dl, IntPtr));
  3063. // Handle alignment. If the requested alignment is less than or equal to
  3064. // the stack alignment, ignore it. If the size is greater than or equal to
  3065. // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
  3066. unsigned StackAlign =
  3067. DAG.getSubtarget().getFrameLowering()->getStackAlignment();
  3068. if (Align <= StackAlign)
  3069. Align = 0;
  3070. // Round the size of the allocation up to the stack alignment size
  3071. // by add SA-1 to the size. This doesn't overflow because we're computing
  3072. // an address inside an alloca.
  3073. SDNodeFlags Flags;
  3074. Flags.setNoUnsignedWrap(true);
  3075. AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
  3076. DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
  3077. // Mask out the low bits for alignment purposes.
  3078. AllocSize =
  3079. DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
  3080. DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
  3081. SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
  3082. SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
  3083. SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
  3084. setValue(&I, DSA);
  3085. DAG.setRoot(DSA.getValue(1));
  3086. assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
  3087. }
  3088. void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
  3089. if (I.isAtomic())
  3090. return visitAtomicLoad(I);
  3091. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3092. const Value *SV = I.getOperand(0);
  3093. if (TLI.supportSwiftError()) {
  3094. // Swifterror values can come from either a function parameter with
  3095. // swifterror attribute or an alloca with swifterror attribute.
  3096. if (const Argument *Arg = dyn_cast<Argument>(SV)) {
  3097. if (Arg->hasSwiftErrorAttr())
  3098. return visitLoadFromSwiftError(I);
  3099. }
  3100. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
  3101. if (Alloca->isSwiftError())
  3102. return visitLoadFromSwiftError(I);
  3103. }
  3104. }
  3105. SDValue Ptr = getValue(SV);
  3106. Type *Ty = I.getType();
  3107. bool isVolatile = I.isVolatile();
  3108. bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
  3109. bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
  3110. bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout());
  3111. unsigned Alignment = I.getAlignment();
  3112. AAMDNodes AAInfo;
  3113. I.getAAMetadata(AAInfo);
  3114. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3115. SmallVector<EVT, 4> ValueVTs;
  3116. SmallVector<uint64_t, 4> Offsets;
  3117. ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets);
  3118. unsigned NumValues = ValueVTs.size();
  3119. if (NumValues == 0)
  3120. return;
  3121. SDValue Root;
  3122. bool ConstantMemory = false;
  3123. if (isVolatile || NumValues > MaxParallelChains)
  3124. // Serialize volatile loads with other side effects.
  3125. Root = getRoot();
  3126. else if (AA && AA->pointsToConstantMemory(MemoryLocation(
  3127. SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) {
  3128. // Do not serialize (non-volatile) loads of constant memory with anything.
  3129. Root = DAG.getEntryNode();
  3130. ConstantMemory = true;
  3131. } else {
  3132. // Do not serialize non-volatile loads against each other.
  3133. Root = DAG.getRoot();
  3134. }
  3135. SDLoc dl = getCurSDLoc();
  3136. if (isVolatile)
  3137. Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
  3138. // An aggregate load cannot wrap around the address space, so offsets to its
  3139. // parts don't wrap either.
  3140. SDNodeFlags Flags;
  3141. Flags.setNoUnsignedWrap(true);
  3142. SmallVector<SDValue, 4> Values(NumValues);
  3143. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3144. EVT PtrVT = Ptr.getValueType();
  3145. unsigned ChainI = 0;
  3146. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3147. // Serializing loads here may result in excessive register pressure, and
  3148. // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
  3149. // could recover a bit by hoisting nodes upward in the chain by recognizing
  3150. // they are side-effect free or do not alias. The optimizer should really
  3151. // avoid this case by converting large object/array copies to llvm.memcpy
  3152. // (MaxParallelChains should always remain as failsafe).
  3153. if (ChainI == MaxParallelChains) {
  3154. assert(PendingLoads.empty() && "PendingLoads must be serialized first");
  3155. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3156. makeArrayRef(Chains.data(), ChainI));
  3157. Root = Chain;
  3158. ChainI = 0;
  3159. }
  3160. SDValue A = DAG.getNode(ISD::ADD, dl,
  3161. PtrVT, Ptr,
  3162. DAG.getConstant(Offsets[i], dl, PtrVT),
  3163. Flags);
  3164. auto MMOFlags = MachineMemOperand::MONone;
  3165. if (isVolatile)
  3166. MMOFlags |= MachineMemOperand::MOVolatile;
  3167. if (isNonTemporal)
  3168. MMOFlags |= MachineMemOperand::MONonTemporal;
  3169. if (isInvariant)
  3170. MMOFlags |= MachineMemOperand::MOInvariant;
  3171. if (isDereferenceable)
  3172. MMOFlags |= MachineMemOperand::MODereferenceable;
  3173. MMOFlags |= TLI.getMMOFlags(I);
  3174. SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A,
  3175. MachinePointerInfo(SV, Offsets[i]), Alignment,
  3176. MMOFlags, AAInfo, Ranges);
  3177. Values[i] = L;
  3178. Chains[ChainI] = L.getValue(1);
  3179. }
  3180. if (!ConstantMemory) {
  3181. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3182. makeArrayRef(Chains.data(), ChainI));
  3183. if (isVolatile)
  3184. DAG.setRoot(Chain);
  3185. else
  3186. PendingLoads.push_back(Chain);
  3187. }
  3188. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
  3189. DAG.getVTList(ValueVTs), Values));
  3190. }
  3191. void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
  3192. assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
  3193. "call visitStoreToSwiftError when backend supports swifterror");
  3194. SmallVector<EVT, 4> ValueVTs;
  3195. SmallVector<uint64_t, 4> Offsets;
  3196. const Value *SrcV = I.getOperand(0);
  3197. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3198. SrcV->getType(), ValueVTs, &Offsets);
  3199. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3200. "expect a single EVT for swifterror");
  3201. SDValue Src = getValue(SrcV);
  3202. // Create a virtual register, then update the virtual register.
  3203. unsigned VReg; bool CreatedVReg;
  3204. std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I);
  3205. // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
  3206. // Chain can be getRoot or getControlRoot.
  3207. SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
  3208. SDValue(Src.getNode(), Src.getResNo()));
  3209. DAG.setRoot(CopyNode);
  3210. if (CreatedVReg)
  3211. FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg);
  3212. }
  3213. void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
  3214. assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
  3215. "call visitLoadFromSwiftError when backend supports swifterror");
  3216. assert(!I.isVolatile() &&
  3217. I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&
  3218. I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&
  3219. "Support volatile, non temporal, invariant for load_from_swift_error");
  3220. const Value *SV = I.getOperand(0);
  3221. Type *Ty = I.getType();
  3222. AAMDNodes AAInfo;
  3223. I.getAAMetadata(AAInfo);
  3224. assert((!AA || !AA->pointsToConstantMemory(MemoryLocation(
  3225. SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) &&
  3226. "load_from_swift_error should not be constant memory");
  3227. SmallVector<EVT, 4> ValueVTs;
  3228. SmallVector<uint64_t, 4> Offsets;
  3229. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
  3230. ValueVTs, &Offsets);
  3231. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3232. "expect a single EVT for swifterror");
  3233. // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
  3234. SDValue L = DAG.getCopyFromReg(
  3235. getRoot(), getCurSDLoc(),
  3236. FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first,
  3237. ValueVTs[0]);
  3238. setValue(&I, L);
  3239. }
  3240. void SelectionDAGBuilder::visitStore(const StoreInst &I) {
  3241. if (I.isAtomic())
  3242. return visitAtomicStore(I);
  3243. const Value *SrcV = I.getOperand(0);
  3244. const Value *PtrV = I.getOperand(1);
  3245. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3246. if (TLI.supportSwiftError()) {
  3247. // Swifterror values can come from either a function parameter with
  3248. // swifterror attribute or an alloca with swifterror attribute.
  3249. if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
  3250. if (Arg->hasSwiftErrorAttr())
  3251. return visitStoreToSwiftError(I);
  3252. }
  3253. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
  3254. if (Alloca->isSwiftError())
  3255. return visitStoreToSwiftError(I);
  3256. }
  3257. }
  3258. SmallVector<EVT, 4> ValueVTs;
  3259. SmallVector<uint64_t, 4> Offsets;
  3260. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3261. SrcV->getType(), ValueVTs, &Offsets);
  3262. unsigned NumValues = ValueVTs.size();
  3263. if (NumValues == 0)
  3264. return;
  3265. // Get the lowered operands. Note that we do this after
  3266. // checking if NumResults is zero, because with zero results
  3267. // the operands won't have values in the map.
  3268. SDValue Src = getValue(SrcV);
  3269. SDValue Ptr = getValue(PtrV);
  3270. SDValue Root = getRoot();
  3271. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3272. SDLoc dl = getCurSDLoc();
  3273. EVT PtrVT = Ptr.getValueType();
  3274. unsigned Alignment = I.getAlignment();
  3275. AAMDNodes AAInfo;
  3276. I.getAAMetadata(AAInfo);
  3277. auto MMOFlags = MachineMemOperand::MONone;
  3278. if (I.isVolatile())
  3279. MMOFlags |= MachineMemOperand::MOVolatile;
  3280. if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
  3281. MMOFlags |= MachineMemOperand::MONonTemporal;
  3282. MMOFlags |= TLI.getMMOFlags(I);
  3283. // An aggregate load cannot wrap around the address space, so offsets to its
  3284. // parts don't wrap either.
  3285. SDNodeFlags Flags;
  3286. Flags.setNoUnsignedWrap(true);
  3287. unsigned ChainI = 0;
  3288. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3289. // See visitLoad comments.
  3290. if (ChainI == MaxParallelChains) {
  3291. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3292. makeArrayRef(Chains.data(), ChainI));
  3293. Root = Chain;
  3294. ChainI = 0;
  3295. }
  3296. SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
  3297. DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
  3298. SDValue St = DAG.getStore(
  3299. Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add,
  3300. MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo);
  3301. Chains[ChainI] = St;
  3302. }
  3303. SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3304. makeArrayRef(Chains.data(), ChainI));
  3305. DAG.setRoot(StoreNode);
  3306. }
  3307. void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
  3308. bool IsCompressing) {
  3309. SDLoc sdl = getCurSDLoc();
  3310. auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3311. unsigned& Alignment) {
  3312. // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
  3313. Src0 = I.getArgOperand(0);
  3314. Ptr = I.getArgOperand(1);
  3315. Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
  3316. Mask = I.getArgOperand(3);
  3317. };
  3318. auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3319. unsigned& Alignment) {
  3320. // llvm.masked.compressstore.*(Src0, Ptr, Mask)
  3321. Src0 = I.getArgOperand(0);
  3322. Ptr = I.getArgOperand(1);
  3323. Mask = I.getArgOperand(2);
  3324. Alignment = 0;
  3325. };
  3326. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3327. unsigned Alignment;
  3328. if (IsCompressing)
  3329. getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3330. else
  3331. getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3332. SDValue Ptr = getValue(PtrOperand);
  3333. SDValue Src0 = getValue(Src0Operand);
  3334. SDValue Mask = getValue(MaskOperand);
  3335. EVT VT = Src0.getValueType();
  3336. if (!Alignment)
  3337. Alignment = DAG.getEVTAlignment(VT);
  3338. AAMDNodes AAInfo;
  3339. I.getAAMetadata(AAInfo);
  3340. MachineMemOperand *MMO =
  3341. DAG.getMachineFunction().
  3342. getMachineMemOperand(MachinePointerInfo(PtrOperand),
  3343. MachineMemOperand::MOStore, VT.getStoreSize(),
  3344. Alignment, AAInfo);
  3345. SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
  3346. MMO, false /* Truncating */,
  3347. IsCompressing);
  3348. DAG.setRoot(StoreNode);
  3349. setValue(&I, StoreNode);
  3350. }
  3351. // Get a uniform base for the Gather/Scatter intrinsic.
  3352. // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
  3353. // We try to represent it as a base pointer + vector of indices.
  3354. // Usually, the vector of pointers comes from a 'getelementptr' instruction.
  3355. // The first operand of the GEP may be a single pointer or a vector of pointers
  3356. // Example:
  3357. // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
  3358. // or
  3359. // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
  3360. // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
  3361. //
  3362. // When the first GEP operand is a single pointer - it is the uniform base we
  3363. // are looking for. If first operand of the GEP is a splat vector - we
  3364. // extract the splat value and use it as a uniform base.
  3365. // In all other cases the function returns 'false'.
  3366. static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index,
  3367. SelectionDAGBuilder* SDB) {
  3368. SelectionDAG& DAG = SDB->DAG;
  3369. LLVMContext &Context = *DAG.getContext();
  3370. assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
  3371. const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
  3372. if (!GEP)
  3373. return false;
  3374. const Value *GEPPtr = GEP->getPointerOperand();
  3375. if (!GEPPtr->getType()->isVectorTy())
  3376. Ptr = GEPPtr;
  3377. else if (!(Ptr = getSplatValue(GEPPtr)))
  3378. return false;
  3379. unsigned FinalIndex = GEP->getNumOperands() - 1;
  3380. Value *IndexVal = GEP->getOperand(FinalIndex);
  3381. // Ensure all the other indices are 0.
  3382. for (unsigned i = 1; i < FinalIndex; ++i) {
  3383. auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i));
  3384. if (!C || !C->isZero())
  3385. return false;
  3386. }
  3387. // The operands of the GEP may be defined in another basic block.
  3388. // In this case we'll not find nodes for the operands.
  3389. if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
  3390. return false;
  3391. Base = SDB->getValue(Ptr);
  3392. Index = SDB->getValue(IndexVal);
  3393. if (!Index.getValueType().isVector()) {
  3394. unsigned GEPWidth = GEP->getType()->getVectorNumElements();
  3395. EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
  3396. Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
  3397. }
  3398. return true;
  3399. }
  3400. void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
  3401. SDLoc sdl = getCurSDLoc();
  3402. // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
  3403. const Value *Ptr = I.getArgOperand(1);
  3404. SDValue Src0 = getValue(I.getArgOperand(0));
  3405. SDValue Mask = getValue(I.getArgOperand(3));
  3406. EVT VT = Src0.getValueType();
  3407. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
  3408. if (!Alignment)
  3409. Alignment = DAG.getEVTAlignment(VT);
  3410. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3411. AAMDNodes AAInfo;
  3412. I.getAAMetadata(AAInfo);
  3413. SDValue Base;
  3414. SDValue Index;
  3415. const Value *BasePtr = Ptr;
  3416. bool UniformBase = getUniformBase(BasePtr, Base, Index, this);
  3417. const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
  3418. MachineMemOperand *MMO = DAG.getMachineFunction().
  3419. getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
  3420. MachineMemOperand::MOStore, VT.getStoreSize(),
  3421. Alignment, AAInfo);
  3422. if (!UniformBase) {
  3423. Base = DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3424. Index = getValue(Ptr);
  3425. }
  3426. SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index };
  3427. SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
  3428. Ops, MMO);
  3429. DAG.setRoot(Scatter);
  3430. setValue(&I, Scatter);
  3431. }
  3432. void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
  3433. SDLoc sdl = getCurSDLoc();
  3434. auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3435. unsigned& Alignment) {
  3436. // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
  3437. Ptr = I.getArgOperand(0);
  3438. Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  3439. Mask = I.getArgOperand(2);
  3440. Src0 = I.getArgOperand(3);
  3441. };
  3442. auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3443. unsigned& Alignment) {
  3444. // @llvm.masked.expandload.*(Ptr, Mask, Src0)
  3445. Ptr = I.getArgOperand(0);
  3446. Alignment = 0;
  3447. Mask = I.getArgOperand(1);
  3448. Src0 = I.getArgOperand(2);
  3449. };
  3450. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3451. unsigned Alignment;
  3452. if (IsExpanding)
  3453. getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3454. else
  3455. getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3456. SDValue Ptr = getValue(PtrOperand);
  3457. SDValue Src0 = getValue(Src0Operand);
  3458. SDValue Mask = getValue(MaskOperand);
  3459. EVT VT = Src0.getValueType();
  3460. if (!Alignment)
  3461. Alignment = DAG.getEVTAlignment(VT);
  3462. AAMDNodes AAInfo;
  3463. I.getAAMetadata(AAInfo);
  3464. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3465. // Do not serialize masked loads of constant memory with anything.
  3466. bool AddToChain = !AA || !AA->pointsToConstantMemory(MemoryLocation(
  3467. PtrOperand, DAG.getDataLayout().getTypeStoreSize(I.getType()), AAInfo));
  3468. SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
  3469. MachineMemOperand *MMO =
  3470. DAG.getMachineFunction().
  3471. getMachineMemOperand(MachinePointerInfo(PtrOperand),
  3472. MachineMemOperand::MOLoad, VT.getStoreSize(),
  3473. Alignment, AAInfo, Ranges);
  3474. SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
  3475. ISD::NON_EXTLOAD, IsExpanding);
  3476. if (AddToChain) {
  3477. SDValue OutChain = Load.getValue(1);
  3478. DAG.setRoot(OutChain);
  3479. }
  3480. setValue(&I, Load);
  3481. }
  3482. void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
  3483. SDLoc sdl = getCurSDLoc();
  3484. // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
  3485. const Value *Ptr = I.getArgOperand(0);
  3486. SDValue Src0 = getValue(I.getArgOperand(3));
  3487. SDValue Mask = getValue(I.getArgOperand(2));
  3488. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3489. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3490. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
  3491. if (!Alignment)
  3492. Alignment = DAG.getEVTAlignment(VT);
  3493. AAMDNodes AAInfo;
  3494. I.getAAMetadata(AAInfo);
  3495. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3496. SDValue Root = DAG.getRoot();
  3497. SDValue Base;
  3498. SDValue Index;
  3499. const Value *BasePtr = Ptr;
  3500. bool UniformBase = getUniformBase(BasePtr, Base, Index, this);
  3501. bool ConstantMemory = false;
  3502. if (UniformBase &&
  3503. AA && AA->pointsToConstantMemory(MemoryLocation(
  3504. BasePtr, DAG.getDataLayout().getTypeStoreSize(I.getType()),
  3505. AAInfo))) {
  3506. // Do not serialize (non-volatile) loads of constant memory with anything.
  3507. Root = DAG.getEntryNode();
  3508. ConstantMemory = true;
  3509. }
  3510. MachineMemOperand *MMO =
  3511. DAG.getMachineFunction().
  3512. getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
  3513. MachineMemOperand::MOLoad, VT.getStoreSize(),
  3514. Alignment, AAInfo, Ranges);
  3515. if (!UniformBase) {
  3516. Base = DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3517. Index = getValue(Ptr);
  3518. }
  3519. SDValue Ops[] = { Root, Src0, Mask, Base, Index };
  3520. SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
  3521. Ops, MMO);
  3522. SDValue OutChain = Gather.getValue(1);
  3523. if (!ConstantMemory)
  3524. PendingLoads.push_back(OutChain);
  3525. setValue(&I, Gather);
  3526. }
  3527. void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
  3528. SDLoc dl = getCurSDLoc();
  3529. AtomicOrdering SuccessOrder = I.getSuccessOrdering();
  3530. AtomicOrdering FailureOrder = I.getFailureOrdering();
  3531. SyncScope::ID SSID = I.getSyncScopeID();
  3532. SDValue InChain = getRoot();
  3533. MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
  3534. SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
  3535. SDValue L = DAG.getAtomicCmpSwap(
  3536. ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
  3537. getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
  3538. getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
  3539. /*Alignment=*/ 0, SuccessOrder, FailureOrder, SSID);
  3540. SDValue OutChain = L.getValue(2);
  3541. setValue(&I, L);
  3542. DAG.setRoot(OutChain);
  3543. }
  3544. void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
  3545. SDLoc dl = getCurSDLoc();
  3546. ISD::NodeType NT;
  3547. switch (I.getOperation()) {
  3548. default: llvm_unreachable("Unknown atomicrmw operation");
  3549. case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
  3550. case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
  3551. case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
  3552. case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
  3553. case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
  3554. case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
  3555. case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
  3556. case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
  3557. case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
  3558. case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
  3559. case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
  3560. }
  3561. AtomicOrdering Order = I.getOrdering();
  3562. SyncScope::ID SSID = I.getSyncScopeID();
  3563. SDValue InChain = getRoot();
  3564. SDValue L =
  3565. DAG.getAtomic(NT, dl,
  3566. getValue(I.getValOperand()).getSimpleValueType(),
  3567. InChain,
  3568. getValue(I.getPointerOperand()),
  3569. getValue(I.getValOperand()),
  3570. I.getPointerOperand(),
  3571. /* Alignment=*/ 0, Order, SSID);
  3572. SDValue OutChain = L.getValue(1);
  3573. setValue(&I, L);
  3574. DAG.setRoot(OutChain);
  3575. }
  3576. void SelectionDAGBuilder::visitFence(const FenceInst &I) {
  3577. SDLoc dl = getCurSDLoc();
  3578. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3579. SDValue Ops[3];
  3580. Ops[0] = getRoot();
  3581. Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
  3582. TLI.getFenceOperandTy(DAG.getDataLayout()));
  3583. Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
  3584. TLI.getFenceOperandTy(DAG.getDataLayout()));
  3585. DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
  3586. }
  3587. void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
  3588. SDLoc dl = getCurSDLoc();
  3589. AtomicOrdering Order = I.getOrdering();
  3590. SyncScope::ID SSID = I.getSyncScopeID();
  3591. SDValue InChain = getRoot();
  3592. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3593. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3594. if (!TLI.supportsUnalignedAtomics() &&
  3595. I.getAlignment() < VT.getStoreSize())
  3596. report_fatal_error("Cannot generate unaligned atomic load");
  3597. MachineMemOperand *MMO =
  3598. DAG.getMachineFunction().
  3599. getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
  3600. MachineMemOperand::MOVolatile |
  3601. MachineMemOperand::MOLoad,
  3602. VT.getStoreSize(),
  3603. I.getAlignment() ? I.getAlignment() :
  3604. DAG.getEVTAlignment(VT),
  3605. AAMDNodes(), nullptr, SSID, Order);
  3606. InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
  3607. SDValue L =
  3608. DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
  3609. getValue(I.getPointerOperand()), MMO);
  3610. SDValue OutChain = L.getValue(1);
  3611. setValue(&I, L);
  3612. DAG.setRoot(OutChain);
  3613. }
  3614. void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
  3615. SDLoc dl = getCurSDLoc();
  3616. AtomicOrdering Order = I.getOrdering();
  3617. SyncScope::ID SSID = I.getSyncScopeID();
  3618. SDValue InChain = getRoot();
  3619. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3620. EVT VT =
  3621. TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
  3622. if (I.getAlignment() < VT.getStoreSize())
  3623. report_fatal_error("Cannot generate unaligned atomic store");
  3624. SDValue OutChain =
  3625. DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
  3626. InChain,
  3627. getValue(I.getPointerOperand()),
  3628. getValue(I.getValueOperand()),
  3629. I.getPointerOperand(), I.getAlignment(),
  3630. Order, SSID);
  3631. DAG.setRoot(OutChain);
  3632. }
  3633. /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
  3634. /// node.
  3635. void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
  3636. unsigned Intrinsic) {
  3637. // Ignore the callsite's attributes. A specific call site may be marked with
  3638. // readnone, but the lowering code will expect the chain based on the
  3639. // definition.
  3640. const Function *F = I.getCalledFunction();
  3641. bool HasChain = !F->doesNotAccessMemory();
  3642. bool OnlyLoad = HasChain && F->onlyReadsMemory();
  3643. // Build the operand list.
  3644. SmallVector<SDValue, 8> Ops;
  3645. if (HasChain) { // If this intrinsic has side-effects, chainify it.
  3646. if (OnlyLoad) {
  3647. // We don't need to serialize loads against other loads.
  3648. Ops.push_back(DAG.getRoot());
  3649. } else {
  3650. Ops.push_back(getRoot());
  3651. }
  3652. }
  3653. // Info is set by getTgtMemInstrinsic
  3654. TargetLowering::IntrinsicInfo Info;
  3655. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3656. bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
  3657. DAG.getMachineFunction(),
  3658. Intrinsic);
  3659. // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
  3660. if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
  3661. Info.opc == ISD::INTRINSIC_W_CHAIN)
  3662. Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
  3663. TLI.getPointerTy(DAG.getDataLayout())));
  3664. // Add all operands of the call to the operand list.
  3665. for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
  3666. SDValue Op = getValue(I.getArgOperand(i));
  3667. Ops.push_back(Op);
  3668. }
  3669. SmallVector<EVT, 4> ValueVTs;
  3670. ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
  3671. if (HasChain)
  3672. ValueVTs.push_back(MVT::Other);
  3673. SDVTList VTs = DAG.getVTList(ValueVTs);
  3674. // Create the node.
  3675. SDValue Result;
  3676. if (IsTgtIntrinsic) {
  3677. // This is target intrinsic that touches memory
  3678. Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs,
  3679. Ops, Info.memVT,
  3680. MachinePointerInfo(Info.ptrVal, Info.offset), Info.align,
  3681. Info.flags, Info.size);
  3682. } else if (!HasChain) {
  3683. Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
  3684. } else if (!I.getType()->isVoidTy()) {
  3685. Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
  3686. } else {
  3687. Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
  3688. }
  3689. if (HasChain) {
  3690. SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
  3691. if (OnlyLoad)
  3692. PendingLoads.push_back(Chain);
  3693. else
  3694. DAG.setRoot(Chain);
  3695. }
  3696. if (!I.getType()->isVoidTy()) {
  3697. if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
  3698. EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
  3699. Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
  3700. } else
  3701. Result = lowerRangeToAssertZExt(DAG, I, Result);
  3702. setValue(&I, Result);
  3703. }
  3704. }
  3705. /// GetSignificand - Get the significand and build it into a floating-point
  3706. /// number with exponent of 1:
  3707. ///
  3708. /// Op = (Op & 0x007fffff) | 0x3f800000;
  3709. ///
  3710. /// where Op is the hexadecimal representation of floating point value.
  3711. static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
  3712. SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  3713. DAG.getConstant(0x007fffff, dl, MVT::i32));
  3714. SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
  3715. DAG.getConstant(0x3f800000, dl, MVT::i32));
  3716. return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
  3717. }
  3718. /// GetExponent - Get the exponent:
  3719. ///
  3720. /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
  3721. ///
  3722. /// where Op is the hexadecimal representation of floating point value.
  3723. static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
  3724. const TargetLowering &TLI, const SDLoc &dl) {
  3725. SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  3726. DAG.getConstant(0x7f800000, dl, MVT::i32));
  3727. SDValue t1 = DAG.getNode(
  3728. ISD::SRL, dl, MVT::i32, t0,
  3729. DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
  3730. SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
  3731. DAG.getConstant(127, dl, MVT::i32));
  3732. return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
  3733. }
  3734. /// getF32Constant - Get 32-bit floating point constant.
  3735. static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
  3736. const SDLoc &dl) {
  3737. return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
  3738. MVT::f32);
  3739. }
  3740. static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
  3741. SelectionDAG &DAG) {
  3742. // TODO: What fast-math-flags should be set on the floating-point nodes?
  3743. // IntegerPartOfX = ((int32_t)(t0);
  3744. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
  3745. // FractionalPartOfX = t0 - (float)IntegerPartOfX;
  3746. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  3747. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
  3748. // IntegerPartOfX <<= 23;
  3749. IntegerPartOfX = DAG.getNode(
  3750. ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  3751. DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
  3752. DAG.getDataLayout())));
  3753. SDValue TwoToFractionalPartOfX;
  3754. if (LimitFloatPrecision <= 6) {
  3755. // For floating-point precision of 6:
  3756. //
  3757. // TwoToFractionalPartOfX =
  3758. // 0.997535578f +
  3759. // (0.735607626f + 0.252464424f * x) * x;
  3760. //
  3761. // error 0.0144103317, which is 6 bits
  3762. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3763. getF32Constant(DAG, 0x3e814304, dl));
  3764. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3765. getF32Constant(DAG, 0x3f3c50c8, dl));
  3766. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3767. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3768. getF32Constant(DAG, 0x3f7f5e7e, dl));
  3769. } else if (LimitFloatPrecision <= 12) {
  3770. // For floating-point precision of 12:
  3771. //
  3772. // TwoToFractionalPartOfX =
  3773. // 0.999892986f +
  3774. // (0.696457318f +
  3775. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  3776. //
  3777. // error 0.000107046256, which is 13 to 14 bits
  3778. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3779. getF32Constant(DAG, 0x3da235e3, dl));
  3780. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3781. getF32Constant(DAG, 0x3e65b8f3, dl));
  3782. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3783. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3784. getF32Constant(DAG, 0x3f324b07, dl));
  3785. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3786. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3787. getF32Constant(DAG, 0x3f7ff8fd, dl));
  3788. } else { // LimitFloatPrecision <= 18
  3789. // For floating-point precision of 18:
  3790. //
  3791. // TwoToFractionalPartOfX =
  3792. // 0.999999982f +
  3793. // (0.693148872f +
  3794. // (0.240227044f +
  3795. // (0.554906021e-1f +
  3796. // (0.961591928e-2f +
  3797. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  3798. // error 2.47208000*10^(-7), which is better than 18 bits
  3799. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3800. getF32Constant(DAG, 0x3924b03e, dl));
  3801. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3802. getF32Constant(DAG, 0x3ab24b87, dl));
  3803. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3804. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3805. getF32Constant(DAG, 0x3c1d8c17, dl));
  3806. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3807. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3808. getF32Constant(DAG, 0x3d634a1d, dl));
  3809. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3810. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3811. getF32Constant(DAG, 0x3e75fe14, dl));
  3812. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3813. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  3814. getF32Constant(DAG, 0x3f317234, dl));
  3815. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  3816. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  3817. getF32Constant(DAG, 0x3f800000, dl));
  3818. }
  3819. // Add the exponent into the result in integer domain.
  3820. SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
  3821. return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
  3822. DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
  3823. }
  3824. /// expandExp - Lower an exp intrinsic. Handles the special sequences for
  3825. /// limited-precision mode.
  3826. static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  3827. const TargetLowering &TLI) {
  3828. if (Op.getValueType() == MVT::f32 &&
  3829. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3830. // Put the exponent in the right bit position for later addition to the
  3831. // final result:
  3832. //
  3833. // #define LOG2OFe 1.4426950f
  3834. // t0 = Op * LOG2OFe
  3835. // TODO: What fast-math-flags should be set here?
  3836. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
  3837. getF32Constant(DAG, 0x3fb8aa3b, dl));
  3838. return getLimitedPrecisionExp2(t0, dl, DAG);
  3839. }
  3840. // No special expansion.
  3841. return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
  3842. }
  3843. /// expandLog - Lower a log intrinsic. Handles the special sequences for
  3844. /// limited-precision mode.
  3845. static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  3846. const TargetLowering &TLI) {
  3847. // TODO: What fast-math-flags should be set on the floating-point nodes?
  3848. if (Op.getValueType() == MVT::f32 &&
  3849. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3850. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  3851. // Scale the exponent by log(2) [0.69314718f].
  3852. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  3853. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  3854. getF32Constant(DAG, 0x3f317218, dl));
  3855. // Get the significand and build it into a floating-point number with
  3856. // exponent of 1.
  3857. SDValue X = GetSignificand(DAG, Op1, dl);
  3858. SDValue LogOfMantissa;
  3859. if (LimitFloatPrecision <= 6) {
  3860. // For floating-point precision of 6:
  3861. //
  3862. // LogofMantissa =
  3863. // -1.1609546f +
  3864. // (1.4034025f - 0.23903021f * x) * x;
  3865. //
  3866. // error 0.0034276066, which is better than 8 bits
  3867. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3868. getF32Constant(DAG, 0xbe74c456, dl));
  3869. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3870. getF32Constant(DAG, 0x3fb3a2b1, dl));
  3871. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3872. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3873. getF32Constant(DAG, 0x3f949a29, dl));
  3874. } else if (LimitFloatPrecision <= 12) {
  3875. // For floating-point precision of 12:
  3876. //
  3877. // LogOfMantissa =
  3878. // -1.7417939f +
  3879. // (2.8212026f +
  3880. // (-1.4699568f +
  3881. // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
  3882. //
  3883. // error 0.000061011436, which is 14 bits
  3884. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3885. getF32Constant(DAG, 0xbd67b6d6, dl));
  3886. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3887. getF32Constant(DAG, 0x3ee4f4b8, dl));
  3888. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3889. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3890. getF32Constant(DAG, 0x3fbc278b, dl));
  3891. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3892. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3893. getF32Constant(DAG, 0x40348e95, dl));
  3894. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3895. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3896. getF32Constant(DAG, 0x3fdef31a, dl));
  3897. } else { // LimitFloatPrecision <= 18
  3898. // For floating-point precision of 18:
  3899. //
  3900. // LogOfMantissa =
  3901. // -2.1072184f +
  3902. // (4.2372794f +
  3903. // (-3.7029485f +
  3904. // (2.2781945f +
  3905. // (-0.87823314f +
  3906. // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
  3907. //
  3908. // error 0.0000023660568, which is better than 18 bits
  3909. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3910. getF32Constant(DAG, 0xbc91e5ac, dl));
  3911. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3912. getF32Constant(DAG, 0x3e4350aa, dl));
  3913. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3914. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3915. getF32Constant(DAG, 0x3f60d3e3, dl));
  3916. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3917. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3918. getF32Constant(DAG, 0x4011cdf0, dl));
  3919. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3920. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3921. getF32Constant(DAG, 0x406cfd1c, dl));
  3922. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3923. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3924. getF32Constant(DAG, 0x408797cb, dl));
  3925. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3926. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  3927. getF32Constant(DAG, 0x4006dcab, dl));
  3928. }
  3929. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
  3930. }
  3931. // No special expansion.
  3932. return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
  3933. }
  3934. /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
  3935. /// limited-precision mode.
  3936. static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  3937. const TargetLowering &TLI) {
  3938. // TODO: What fast-math-flags should be set on the floating-point nodes?
  3939. if (Op.getValueType() == MVT::f32 &&
  3940. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3941. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  3942. // Get the exponent.
  3943. SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
  3944. // Get the significand and build it into a floating-point number with
  3945. // exponent of 1.
  3946. SDValue X = GetSignificand(DAG, Op1, dl);
  3947. // Different possible minimax approximations of significand in
  3948. // floating-point for various degrees of accuracy over [1,2].
  3949. SDValue Log2ofMantissa;
  3950. if (LimitFloatPrecision <= 6) {
  3951. // For floating-point precision of 6:
  3952. //
  3953. // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
  3954. //
  3955. // error 0.0049451742, which is more than 7 bits
  3956. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3957. getF32Constant(DAG, 0xbeb08fe0, dl));
  3958. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3959. getF32Constant(DAG, 0x40019463, dl));
  3960. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3961. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3962. getF32Constant(DAG, 0x3fd6633d, dl));
  3963. } else if (LimitFloatPrecision <= 12) {
  3964. // For floating-point precision of 12:
  3965. //
  3966. // Log2ofMantissa =
  3967. // -2.51285454f +
  3968. // (4.07009056f +
  3969. // (-2.12067489f +
  3970. // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
  3971. //
  3972. // error 0.0000876136000, which is better than 13 bits
  3973. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3974. getF32Constant(DAG, 0xbda7262e, dl));
  3975. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3976. getF32Constant(DAG, 0x3f25280b, dl));
  3977. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3978. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3979. getF32Constant(DAG, 0x4007b923, dl));
  3980. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3981. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3982. getF32Constant(DAG, 0x40823e2f, dl));
  3983. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3984. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3985. getF32Constant(DAG, 0x4020d29c, dl));
  3986. } else { // LimitFloatPrecision <= 18
  3987. // For floating-point precision of 18:
  3988. //
  3989. // Log2ofMantissa =
  3990. // -3.0400495f +
  3991. // (6.1129976f +
  3992. // (-5.3420409f +
  3993. // (3.2865683f +
  3994. // (-1.2669343f +
  3995. // (0.27515199f -
  3996. // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
  3997. //
  3998. // error 0.0000018516, which is better than 18 bits
  3999. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4000. getF32Constant(DAG, 0xbcd2769e, dl));
  4001. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4002. getF32Constant(DAG, 0x3e8ce0b9, dl));
  4003. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4004. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4005. getF32Constant(DAG, 0x3fa22ae7, dl));
  4006. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4007. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4008. getF32Constant(DAG, 0x40525723, dl));
  4009. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4010. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4011. getF32Constant(DAG, 0x40aaf200, dl));
  4012. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4013. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4014. getF32Constant(DAG, 0x40c39dad, dl));
  4015. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4016. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  4017. getF32Constant(DAG, 0x4042902c, dl));
  4018. }
  4019. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
  4020. }
  4021. // No special expansion.
  4022. return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
  4023. }
  4024. /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
  4025. /// limited-precision mode.
  4026. static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4027. const TargetLowering &TLI) {
  4028. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4029. if (Op.getValueType() == MVT::f32 &&
  4030. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4031. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4032. // Scale the exponent by log10(2) [0.30102999f].
  4033. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  4034. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  4035. getF32Constant(DAG, 0x3e9a209a, dl));
  4036. // Get the significand and build it into a floating-point number with
  4037. // exponent of 1.
  4038. SDValue X = GetSignificand(DAG, Op1, dl);
  4039. SDValue Log10ofMantissa;
  4040. if (LimitFloatPrecision <= 6) {
  4041. // For floating-point precision of 6:
  4042. //
  4043. // Log10ofMantissa =
  4044. // -0.50419619f +
  4045. // (0.60948995f - 0.10380950f * x) * x;
  4046. //
  4047. // error 0.0014886165, which is 6 bits
  4048. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4049. getF32Constant(DAG, 0xbdd49a13, dl));
  4050. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4051. getF32Constant(DAG, 0x3f1c0789, dl));
  4052. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4053. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4054. getF32Constant(DAG, 0x3f011300, dl));
  4055. } else if (LimitFloatPrecision <= 12) {
  4056. // For floating-point precision of 12:
  4057. //
  4058. // Log10ofMantissa =
  4059. // -0.64831180f +
  4060. // (0.91751397f +
  4061. // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
  4062. //
  4063. // error 0.00019228036, which is better than 12 bits
  4064. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4065. getF32Constant(DAG, 0x3d431f31, dl));
  4066. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  4067. getF32Constant(DAG, 0x3ea21fb2, dl));
  4068. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4069. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4070. getF32Constant(DAG, 0x3f6ae232, dl));
  4071. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4072. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  4073. getF32Constant(DAG, 0x3f25f7c3, dl));
  4074. } else { // LimitFloatPrecision <= 18
  4075. // For floating-point precision of 18:
  4076. //
  4077. // Log10ofMantissa =
  4078. // -0.84299375f +
  4079. // (1.5327582f +
  4080. // (-1.0688956f +
  4081. // (0.49102474f +
  4082. // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
  4083. //
  4084. // error 0.0000037995730, which is better than 18 bits
  4085. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4086. getF32Constant(DAG, 0x3c5d51ce, dl));
  4087. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  4088. getF32Constant(DAG, 0x3e00685a, dl));
  4089. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4090. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4091. getF32Constant(DAG, 0x3efb6798, dl));
  4092. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4093. SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  4094. getF32Constant(DAG, 0x3f88d192, dl));
  4095. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4096. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4097. getF32Constant(DAG, 0x3fc4316c, dl));
  4098. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4099. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
  4100. getF32Constant(DAG, 0x3f57ce70, dl));
  4101. }
  4102. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
  4103. }
  4104. // No special expansion.
  4105. return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
  4106. }
  4107. /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
  4108. /// limited-precision mode.
  4109. static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4110. const TargetLowering &TLI) {
  4111. if (Op.getValueType() == MVT::f32 &&
  4112. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
  4113. return getLimitedPrecisionExp2(Op, dl, DAG);
  4114. // No special expansion.
  4115. return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
  4116. }
  4117. /// visitPow - Lower a pow intrinsic. Handles the special sequences for
  4118. /// limited-precision mode with x == 10.0f.
  4119. static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
  4120. SelectionDAG &DAG, const TargetLowering &TLI) {
  4121. bool IsExp10 = false;
  4122. if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
  4123. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4124. if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
  4125. APFloat Ten(10.0f);
  4126. IsExp10 = LHSC->isExactlyValue(Ten);
  4127. }
  4128. }
  4129. // TODO: What fast-math-flags should be set on the FMUL node?
  4130. if (IsExp10) {
  4131. // Put the exponent in the right bit position for later addition to the
  4132. // final result:
  4133. //
  4134. // #define LOG2OF10 3.3219281f
  4135. // t0 = Op * LOG2OF10;
  4136. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
  4137. getF32Constant(DAG, 0x40549a78, dl));
  4138. return getLimitedPrecisionExp2(t0, dl, DAG);
  4139. }
  4140. // No special expansion.
  4141. return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
  4142. }
  4143. /// ExpandPowI - Expand a llvm.powi intrinsic.
  4144. static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
  4145. SelectionDAG &DAG) {
  4146. // If RHS is a constant, we can expand this out to a multiplication tree,
  4147. // otherwise we end up lowering to a call to __powidf2 (for example). When
  4148. // optimizing for size, we only want to do this if the expansion would produce
  4149. // a small number of multiplies, otherwise we do the full expansion.
  4150. if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
  4151. // Get the exponent as a positive value.
  4152. unsigned Val = RHSC->getSExtValue();
  4153. if ((int)Val < 0) Val = -Val;
  4154. // powi(x, 0) -> 1.0
  4155. if (Val == 0)
  4156. return DAG.getConstantFP(1.0, DL, LHS.getValueType());
  4157. const Function &F = DAG.getMachineFunction().getFunction();
  4158. if (!F.optForSize() ||
  4159. // If optimizing for size, don't insert too many multiplies.
  4160. // This inserts up to 5 multiplies.
  4161. countPopulation(Val) + Log2_32(Val) < 7) {
  4162. // We use the simple binary decomposition method to generate the multiply
  4163. // sequence. There are more optimal ways to do this (for example,
  4164. // powi(x,15) generates one more multiply than it should), but this has
  4165. // the benefit of being both really simple and much better than a libcall.
  4166. SDValue Res; // Logically starts equal to 1.0
  4167. SDValue CurSquare = LHS;
  4168. // TODO: Intrinsics should have fast-math-flags that propagate to these
  4169. // nodes.
  4170. while (Val) {
  4171. if (Val & 1) {
  4172. if (Res.getNode())
  4173. Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
  4174. else
  4175. Res = CurSquare; // 1.0*CurSquare.
  4176. }
  4177. CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
  4178. CurSquare, CurSquare);
  4179. Val >>= 1;
  4180. }
  4181. // If the original was negative, invert the result, producing 1/(x*x*x).
  4182. if (RHSC->getSExtValue() < 0)
  4183. Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
  4184. DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
  4185. return Res;
  4186. }
  4187. }
  4188. // Otherwise, expand to a libcall.
  4189. return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
  4190. }
  4191. // getUnderlyingArgReg - Find underlying register used for a truncated or
  4192. // bitcasted argument.
  4193. static unsigned getUnderlyingArgReg(const SDValue &N) {
  4194. switch (N.getOpcode()) {
  4195. case ISD::CopyFromReg:
  4196. return cast<RegisterSDNode>(N.getOperand(1))->getReg();
  4197. case ISD::BITCAST:
  4198. case ISD::AssertZext:
  4199. case ISD::AssertSext:
  4200. case ISD::TRUNCATE:
  4201. return getUnderlyingArgReg(N.getOperand(0));
  4202. default:
  4203. return 0;
  4204. }
  4205. }
  4206. /// If the DbgValueInst is a dbg_value of a function argument, create the
  4207. /// corresponding DBG_VALUE machine instruction for it now. At the end of
  4208. /// instruction selection, they will be inserted to the entry BB.
  4209. bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
  4210. const Value *V, DILocalVariable *Variable, DIExpression *Expr,
  4211. DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
  4212. const Argument *Arg = dyn_cast<Argument>(V);
  4213. if (!Arg)
  4214. return false;
  4215. MachineFunction &MF = DAG.getMachineFunction();
  4216. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  4217. bool IsIndirect = false;
  4218. Optional<MachineOperand> Op;
  4219. // Some arguments' frame index is recorded during argument lowering.
  4220. int FI = FuncInfo.getArgumentFrameIndex(Arg);
  4221. if (FI != std::numeric_limits<int>::max())
  4222. Op = MachineOperand::CreateFI(FI);
  4223. if (!Op && N.getNode()) {
  4224. unsigned Reg = getUnderlyingArgReg(N);
  4225. if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
  4226. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  4227. unsigned PR = RegInfo.getLiveInPhysReg(Reg);
  4228. if (PR)
  4229. Reg = PR;
  4230. }
  4231. if (Reg) {
  4232. Op = MachineOperand::CreateReg(Reg, false);
  4233. IsIndirect = IsDbgDeclare;
  4234. }
  4235. }
  4236. if (!Op && N.getNode())
  4237. // Check if frame index is available.
  4238. if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
  4239. if (FrameIndexSDNode *FINode =
  4240. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  4241. Op = MachineOperand::CreateFI(FINode->getIndex());
  4242. if (!Op) {
  4243. // Check if ValueMap has reg number.
  4244. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  4245. if (VMI != FuncInfo.ValueMap.end()) {
  4246. const auto &TLI = DAG.getTargetLoweringInfo();
  4247. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
  4248. V->getType(), isABIRegCopy(V));
  4249. unsigned NumRegs =
  4250. std::accumulate(RFV.RegCount.begin(), RFV.RegCount.end(), 0);
  4251. if (NumRegs > 1) {
  4252. unsigned I = 0;
  4253. unsigned Offset = 0;
  4254. auto RegisterVT = RFV.RegVTs.begin();
  4255. for (auto RegCount : RFV.RegCount) {
  4256. unsigned RegisterSize = (RegisterVT++)->getSizeInBits();
  4257. for (unsigned E = I + RegCount; I != E; ++I) {
  4258. // The vregs are guaranteed to be allocated in sequence.
  4259. Op = MachineOperand::CreateReg(VMI->second + I, false);
  4260. auto FragmentExpr = DIExpression::createFragmentExpression(
  4261. Expr, Offset, RegisterSize);
  4262. if (!FragmentExpr)
  4263. continue;
  4264. FuncInfo.ArgDbgValues.push_back(
  4265. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
  4266. Op->getReg(), Variable, *FragmentExpr));
  4267. Offset += RegisterSize;
  4268. }
  4269. }
  4270. return true;
  4271. }
  4272. Op = MachineOperand::CreateReg(VMI->second, false);
  4273. IsIndirect = IsDbgDeclare;
  4274. }
  4275. }
  4276. if (!Op)
  4277. return false;
  4278. assert(Variable->isValidLocationForIntrinsic(DL) &&
  4279. "Expected inlined-at fields to agree");
  4280. if (Op->isReg())
  4281. FuncInfo.ArgDbgValues.push_back(
  4282. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
  4283. Op->getReg(), Variable, Expr));
  4284. else
  4285. FuncInfo.ArgDbgValues.push_back(
  4286. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE))
  4287. .add(*Op)
  4288. .addImm(0)
  4289. .addMetadata(Variable)
  4290. .addMetadata(Expr));
  4291. return true;
  4292. }
  4293. /// Return the appropriate SDDbgValue based on N.
  4294. SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
  4295. DILocalVariable *Variable,
  4296. DIExpression *Expr,
  4297. const DebugLoc &dl,
  4298. unsigned DbgSDNodeOrder) {
  4299. if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
  4300. // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
  4301. // stack slot locations as such instead of as indirectly addressed
  4302. // locations.
  4303. return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), dl,
  4304. DbgSDNodeOrder);
  4305. }
  4306. return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), false, dl,
  4307. DbgSDNodeOrder);
  4308. }
  4309. // VisualStudio defines setjmp as _setjmp
  4310. #if defined(_MSC_VER) && defined(setjmp) && \
  4311. !defined(setjmp_undefined_for_msvc)
  4312. # pragma push_macro("setjmp")
  4313. # undef setjmp
  4314. # define setjmp_undefined_for_msvc
  4315. #endif
  4316. /// Lower the call to the specified intrinsic function. If we want to emit this
  4317. /// as a call to a named external function, return the name. Otherwise, lower it
  4318. /// and return null.
  4319. const char *
  4320. SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
  4321. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4322. SDLoc sdl = getCurSDLoc();
  4323. DebugLoc dl = getCurDebugLoc();
  4324. SDValue Res;
  4325. switch (Intrinsic) {
  4326. default:
  4327. // By default, turn this into a target intrinsic node.
  4328. visitTargetIntrinsic(I, Intrinsic);
  4329. return nullptr;
  4330. case Intrinsic::vastart: visitVAStart(I); return nullptr;
  4331. case Intrinsic::vaend: visitVAEnd(I); return nullptr;
  4332. case Intrinsic::vacopy: visitVACopy(I); return nullptr;
  4333. case Intrinsic::returnaddress:
  4334. setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
  4335. TLI.getPointerTy(DAG.getDataLayout()),
  4336. getValue(I.getArgOperand(0))));
  4337. return nullptr;
  4338. case Intrinsic::addressofreturnaddress:
  4339. setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
  4340. TLI.getPointerTy(DAG.getDataLayout())));
  4341. return nullptr;
  4342. case Intrinsic::frameaddress:
  4343. setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
  4344. TLI.getPointerTy(DAG.getDataLayout()),
  4345. getValue(I.getArgOperand(0))));
  4346. return nullptr;
  4347. case Intrinsic::read_register: {
  4348. Value *Reg = I.getArgOperand(0);
  4349. SDValue Chain = getRoot();
  4350. SDValue RegName =
  4351. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  4352. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4353. Res = DAG.getNode(ISD::READ_REGISTER, sdl,
  4354. DAG.getVTList(VT, MVT::Other), Chain, RegName);
  4355. setValue(&I, Res);
  4356. DAG.setRoot(Res.getValue(1));
  4357. return nullptr;
  4358. }
  4359. case Intrinsic::write_register: {
  4360. Value *Reg = I.getArgOperand(0);
  4361. Value *RegValue = I.getArgOperand(1);
  4362. SDValue Chain = getRoot();
  4363. SDValue RegName =
  4364. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  4365. DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
  4366. RegName, getValue(RegValue)));
  4367. return nullptr;
  4368. }
  4369. case Intrinsic::setjmp:
  4370. return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
  4371. case Intrinsic::longjmp:
  4372. return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
  4373. case Intrinsic::memcpy: {
  4374. SDValue Op1 = getValue(I.getArgOperand(0));
  4375. SDValue Op2 = getValue(I.getArgOperand(1));
  4376. SDValue Op3 = getValue(I.getArgOperand(2));
  4377. unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
  4378. if (!Align)
  4379. Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment.
  4380. bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
  4381. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4382. SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4383. false, isTC,
  4384. MachinePointerInfo(I.getArgOperand(0)),
  4385. MachinePointerInfo(I.getArgOperand(1)));
  4386. updateDAGForMaybeTailCall(MC);
  4387. return nullptr;
  4388. }
  4389. case Intrinsic::memset: {
  4390. SDValue Op1 = getValue(I.getArgOperand(0));
  4391. SDValue Op2 = getValue(I.getArgOperand(1));
  4392. SDValue Op3 = getValue(I.getArgOperand(2));
  4393. unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
  4394. if (!Align)
  4395. Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment.
  4396. bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
  4397. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4398. SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4399. isTC, MachinePointerInfo(I.getArgOperand(0)));
  4400. updateDAGForMaybeTailCall(MS);
  4401. return nullptr;
  4402. }
  4403. case Intrinsic::memmove: {
  4404. SDValue Op1 = getValue(I.getArgOperand(0));
  4405. SDValue Op2 = getValue(I.getArgOperand(1));
  4406. SDValue Op3 = getValue(I.getArgOperand(2));
  4407. unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
  4408. if (!Align)
  4409. Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment.
  4410. bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
  4411. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4412. SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4413. isTC, MachinePointerInfo(I.getArgOperand(0)),
  4414. MachinePointerInfo(I.getArgOperand(1)));
  4415. updateDAGForMaybeTailCall(MM);
  4416. return nullptr;
  4417. }
  4418. case Intrinsic::memcpy_element_unordered_atomic: {
  4419. const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
  4420. SDValue Dst = getValue(MI.getRawDest());
  4421. SDValue Src = getValue(MI.getRawSource());
  4422. SDValue Length = getValue(MI.getLength());
  4423. // Emit a library call.
  4424. TargetLowering::ArgListTy Args;
  4425. TargetLowering::ArgListEntry Entry;
  4426. Entry.Ty = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
  4427. Entry.Node = Dst;
  4428. Args.push_back(Entry);
  4429. Entry.Node = Src;
  4430. Args.push_back(Entry);
  4431. Entry.Ty = MI.getLength()->getType();
  4432. Entry.Node = Length;
  4433. Args.push_back(Entry);
  4434. uint64_t ElementSizeConstant = MI.getElementSizeInBytes();
  4435. RTLIB::Libcall LibraryCall =
  4436. RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElementSizeConstant);
  4437. if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
  4438. report_fatal_error("Unsupported element size");
  4439. TargetLowering::CallLoweringInfo CLI(DAG);
  4440. CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
  4441. TLI.getLibcallCallingConv(LibraryCall),
  4442. Type::getVoidTy(*DAG.getContext()),
  4443. DAG.getExternalSymbol(TLI.getLibcallName(LibraryCall),
  4444. TLI.getPointerTy(DAG.getDataLayout())),
  4445. std::move(Args));
  4446. std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
  4447. DAG.setRoot(CallResult.second);
  4448. return nullptr;
  4449. }
  4450. case Intrinsic::memmove_element_unordered_atomic: {
  4451. auto &MI = cast<AtomicMemMoveInst>(I);
  4452. SDValue Dst = getValue(MI.getRawDest());
  4453. SDValue Src = getValue(MI.getRawSource());
  4454. SDValue Length = getValue(MI.getLength());
  4455. // Emit a library call.
  4456. TargetLowering::ArgListTy Args;
  4457. TargetLowering::ArgListEntry Entry;
  4458. Entry.Ty = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
  4459. Entry.Node = Dst;
  4460. Args.push_back(Entry);
  4461. Entry.Node = Src;
  4462. Args.push_back(Entry);
  4463. Entry.Ty = MI.getLength()->getType();
  4464. Entry.Node = Length;
  4465. Args.push_back(Entry);
  4466. uint64_t ElementSizeConstant = MI.getElementSizeInBytes();
  4467. RTLIB::Libcall LibraryCall =
  4468. RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElementSizeConstant);
  4469. if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
  4470. report_fatal_error("Unsupported element size");
  4471. TargetLowering::CallLoweringInfo CLI(DAG);
  4472. CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
  4473. TLI.getLibcallCallingConv(LibraryCall),
  4474. Type::getVoidTy(*DAG.getContext()),
  4475. DAG.getExternalSymbol(TLI.getLibcallName(LibraryCall),
  4476. TLI.getPointerTy(DAG.getDataLayout())),
  4477. std::move(Args));
  4478. std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
  4479. DAG.setRoot(CallResult.second);
  4480. return nullptr;
  4481. }
  4482. case Intrinsic::memset_element_unordered_atomic: {
  4483. auto &MI = cast<AtomicMemSetInst>(I);
  4484. SDValue Dst = getValue(MI.getRawDest());
  4485. SDValue Val = getValue(MI.getValue());
  4486. SDValue Length = getValue(MI.getLength());
  4487. // Emit a library call.
  4488. TargetLowering::ArgListTy Args;
  4489. TargetLowering::ArgListEntry Entry;
  4490. Entry.Ty = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
  4491. Entry.Node = Dst;
  4492. Args.push_back(Entry);
  4493. Entry.Ty = Type::getInt8Ty(*DAG.getContext());
  4494. Entry.Node = Val;
  4495. Args.push_back(Entry);
  4496. Entry.Ty = MI.getLength()->getType();
  4497. Entry.Node = Length;
  4498. Args.push_back(Entry);
  4499. uint64_t ElementSizeConstant = MI.getElementSizeInBytes();
  4500. RTLIB::Libcall LibraryCall =
  4501. RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElementSizeConstant);
  4502. if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
  4503. report_fatal_error("Unsupported element size");
  4504. TargetLowering::CallLoweringInfo CLI(DAG);
  4505. CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
  4506. TLI.getLibcallCallingConv(LibraryCall),
  4507. Type::getVoidTy(*DAG.getContext()),
  4508. DAG.getExternalSymbol(TLI.getLibcallName(LibraryCall),
  4509. TLI.getPointerTy(DAG.getDataLayout())),
  4510. std::move(Args));
  4511. std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
  4512. DAG.setRoot(CallResult.second);
  4513. return nullptr;
  4514. }
  4515. case Intrinsic::dbg_addr:
  4516. case Intrinsic::dbg_declare: {
  4517. const DbgInfoIntrinsic &DI = cast<DbgInfoIntrinsic>(I);
  4518. DILocalVariable *Variable = DI.getVariable();
  4519. DIExpression *Expression = DI.getExpression();
  4520. assert(Variable && "Missing variable");
  4521. // Check if address has undef value.
  4522. const Value *Address = DI.getVariableLocation();
  4523. if (!Address || isa<UndefValue>(Address) ||
  4524. (Address->use_empty() && !isa<Argument>(Address))) {
  4525. DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  4526. return nullptr;
  4527. }
  4528. bool isParameter = Variable->isParameter() || isa<Argument>(Address);
  4529. // Check if this variable can be described by a frame index, typically
  4530. // either as a static alloca or a byval parameter.
  4531. int FI = std::numeric_limits<int>::max();
  4532. if (const auto *AI =
  4533. dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
  4534. if (AI->isStaticAlloca()) {
  4535. auto I = FuncInfo.StaticAllocaMap.find(AI);
  4536. if (I != FuncInfo.StaticAllocaMap.end())
  4537. FI = I->second;
  4538. }
  4539. } else if (const auto *Arg = dyn_cast<Argument>(
  4540. Address->stripInBoundsConstantOffsets())) {
  4541. FI = FuncInfo.getArgumentFrameIndex(Arg);
  4542. }
  4543. // llvm.dbg.addr is control dependent and always generates indirect
  4544. // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
  4545. // the MachineFunction variable table.
  4546. if (FI != std::numeric_limits<int>::max()) {
  4547. if (Intrinsic == Intrinsic::dbg_addr)
  4548. DAG.AddDbgValue(DAG.getFrameIndexDbgValue(Variable, Expression, FI, dl,
  4549. SDNodeOrder),
  4550. getRoot().getNode(), isParameter);
  4551. return nullptr;
  4552. }
  4553. SDValue &N = NodeMap[Address];
  4554. if (!N.getNode() && isa<Argument>(Address))
  4555. // Check unused arguments map.
  4556. N = UnusedArgNodeMap[Address];
  4557. SDDbgValue *SDV;
  4558. if (N.getNode()) {
  4559. if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
  4560. Address = BCI->getOperand(0);
  4561. // Parameters are handled specially.
  4562. auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
  4563. if (isParameter && FINode) {
  4564. // Byval parameter. We have a frame index at this point.
  4565. SDV = DAG.getFrameIndexDbgValue(Variable, Expression,
  4566. FINode->getIndex(), dl, SDNodeOrder);
  4567. } else if (isa<Argument>(Address)) {
  4568. // Address is an argument, so try to emit its dbg value using
  4569. // virtual register info from the FuncInfo.ValueMap.
  4570. EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
  4571. return nullptr;
  4572. } else {
  4573. SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
  4574. true, dl, SDNodeOrder);
  4575. }
  4576. DAG.AddDbgValue(SDV, N.getNode(), isParameter);
  4577. } else {
  4578. // If Address is an argument then try to emit its dbg value using
  4579. // virtual register info from the FuncInfo.ValueMap.
  4580. if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
  4581. N)) {
  4582. DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  4583. }
  4584. }
  4585. return nullptr;
  4586. }
  4587. case Intrinsic::dbg_value: {
  4588. const DbgValueInst &DI = cast<DbgValueInst>(I);
  4589. assert(DI.getVariable() && "Missing variable");
  4590. DILocalVariable *Variable = DI.getVariable();
  4591. DIExpression *Expression = DI.getExpression();
  4592. const Value *V = DI.getValue();
  4593. if (!V)
  4594. return nullptr;
  4595. SDDbgValue *SDV;
  4596. if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
  4597. SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder);
  4598. DAG.AddDbgValue(SDV, nullptr, false);
  4599. return nullptr;
  4600. }
  4601. // Do not use getValue() in here; we don't want to generate code at
  4602. // this point if it hasn't been done yet.
  4603. SDValue N = NodeMap[V];
  4604. if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
  4605. N = UnusedArgNodeMap[V];
  4606. if (N.getNode()) {
  4607. if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N))
  4608. return nullptr;
  4609. SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder);
  4610. DAG.AddDbgValue(SDV, N.getNode(), false);
  4611. return nullptr;
  4612. }
  4613. if (!V->use_empty() ) {
  4614. // Do not call getValue(V) yet, as we don't want to generate code.
  4615. // Remember it for later.
  4616. DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
  4617. DanglingDebugInfoMap[V] = DDI;
  4618. return nullptr;
  4619. }
  4620. DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n");
  4621. DEBUG(dbgs() << " Last seen at:\n " << *V << "\n");
  4622. return nullptr;
  4623. }
  4624. case Intrinsic::eh_typeid_for: {
  4625. // Find the type id for the given typeinfo.
  4626. GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
  4627. unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
  4628. Res = DAG.getConstant(TypeID, sdl, MVT::i32);
  4629. setValue(&I, Res);
  4630. return nullptr;
  4631. }
  4632. case Intrinsic::eh_return_i32:
  4633. case Intrinsic::eh_return_i64:
  4634. DAG.getMachineFunction().setCallsEHReturn(true);
  4635. DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
  4636. MVT::Other,
  4637. getControlRoot(),
  4638. getValue(I.getArgOperand(0)),
  4639. getValue(I.getArgOperand(1))));
  4640. return nullptr;
  4641. case Intrinsic::eh_unwind_init:
  4642. DAG.getMachineFunction().setCallsUnwindInit(true);
  4643. return nullptr;
  4644. case Intrinsic::eh_dwarf_cfa:
  4645. setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
  4646. TLI.getPointerTy(DAG.getDataLayout()),
  4647. getValue(I.getArgOperand(0))));
  4648. return nullptr;
  4649. case Intrinsic::eh_sjlj_callsite: {
  4650. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  4651. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
  4652. assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
  4653. assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
  4654. MMI.setCurrentCallSite(CI->getZExtValue());
  4655. return nullptr;
  4656. }
  4657. case Intrinsic::eh_sjlj_functioncontext: {
  4658. // Get and store the index of the function context.
  4659. MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
  4660. AllocaInst *FnCtx =
  4661. cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
  4662. int FI = FuncInfo.StaticAllocaMap[FnCtx];
  4663. MFI.setFunctionContextIndex(FI);
  4664. return nullptr;
  4665. }
  4666. case Intrinsic::eh_sjlj_setjmp: {
  4667. SDValue Ops[2];
  4668. Ops[0] = getRoot();
  4669. Ops[1] = getValue(I.getArgOperand(0));
  4670. SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
  4671. DAG.getVTList(MVT::i32, MVT::Other), Ops);
  4672. setValue(&I, Op.getValue(0));
  4673. DAG.setRoot(Op.getValue(1));
  4674. return nullptr;
  4675. }
  4676. case Intrinsic::eh_sjlj_longjmp:
  4677. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
  4678. getRoot(), getValue(I.getArgOperand(0))));
  4679. return nullptr;
  4680. case Intrinsic::eh_sjlj_setup_dispatch:
  4681. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
  4682. getRoot()));
  4683. return nullptr;
  4684. case Intrinsic::masked_gather:
  4685. visitMaskedGather(I);
  4686. return nullptr;
  4687. case Intrinsic::masked_load:
  4688. visitMaskedLoad(I);
  4689. return nullptr;
  4690. case Intrinsic::masked_scatter:
  4691. visitMaskedScatter(I);
  4692. return nullptr;
  4693. case Intrinsic::masked_store:
  4694. visitMaskedStore(I);
  4695. return nullptr;
  4696. case Intrinsic::masked_expandload:
  4697. visitMaskedLoad(I, true /* IsExpanding */);
  4698. return nullptr;
  4699. case Intrinsic::masked_compressstore:
  4700. visitMaskedStore(I, true /* IsCompressing */);
  4701. return nullptr;
  4702. case Intrinsic::x86_mmx_pslli_w:
  4703. case Intrinsic::x86_mmx_pslli_d:
  4704. case Intrinsic::x86_mmx_pslli_q:
  4705. case Intrinsic::x86_mmx_psrli_w:
  4706. case Intrinsic::x86_mmx_psrli_d:
  4707. case Intrinsic::x86_mmx_psrli_q:
  4708. case Intrinsic::x86_mmx_psrai_w:
  4709. case Intrinsic::x86_mmx_psrai_d: {
  4710. SDValue ShAmt = getValue(I.getArgOperand(1));
  4711. if (isa<ConstantSDNode>(ShAmt)) {
  4712. visitTargetIntrinsic(I, Intrinsic);
  4713. return nullptr;
  4714. }
  4715. unsigned NewIntrinsic = 0;
  4716. EVT ShAmtVT = MVT::v2i32;
  4717. switch (Intrinsic) {
  4718. case Intrinsic::x86_mmx_pslli_w:
  4719. NewIntrinsic = Intrinsic::x86_mmx_psll_w;
  4720. break;
  4721. case Intrinsic::x86_mmx_pslli_d:
  4722. NewIntrinsic = Intrinsic::x86_mmx_psll_d;
  4723. break;
  4724. case Intrinsic::x86_mmx_pslli_q:
  4725. NewIntrinsic = Intrinsic::x86_mmx_psll_q;
  4726. break;
  4727. case Intrinsic::x86_mmx_psrli_w:
  4728. NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
  4729. break;
  4730. case Intrinsic::x86_mmx_psrli_d:
  4731. NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
  4732. break;
  4733. case Intrinsic::x86_mmx_psrli_q:
  4734. NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
  4735. break;
  4736. case Intrinsic::x86_mmx_psrai_w:
  4737. NewIntrinsic = Intrinsic::x86_mmx_psra_w;
  4738. break;
  4739. case Intrinsic::x86_mmx_psrai_d:
  4740. NewIntrinsic = Intrinsic::x86_mmx_psra_d;
  4741. break;
  4742. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  4743. }
  4744. // The vector shift intrinsics with scalars uses 32b shift amounts but
  4745. // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
  4746. // to be zero.
  4747. // We must do this early because v2i32 is not a legal type.
  4748. SDValue ShOps[2];
  4749. ShOps[0] = ShAmt;
  4750. ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
  4751. ShAmt = DAG.getBuildVector(ShAmtVT, sdl, ShOps);
  4752. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4753. ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
  4754. Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
  4755. DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
  4756. getValue(I.getArgOperand(0)), ShAmt);
  4757. setValue(&I, Res);
  4758. return nullptr;
  4759. }
  4760. case Intrinsic::powi:
  4761. setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
  4762. getValue(I.getArgOperand(1)), DAG));
  4763. return nullptr;
  4764. case Intrinsic::log:
  4765. setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  4766. return nullptr;
  4767. case Intrinsic::log2:
  4768. setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  4769. return nullptr;
  4770. case Intrinsic::log10:
  4771. setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  4772. return nullptr;
  4773. case Intrinsic::exp:
  4774. setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  4775. return nullptr;
  4776. case Intrinsic::exp2:
  4777. setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  4778. return nullptr;
  4779. case Intrinsic::pow:
  4780. setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
  4781. getValue(I.getArgOperand(1)), DAG, TLI));
  4782. return nullptr;
  4783. case Intrinsic::sqrt:
  4784. case Intrinsic::fabs:
  4785. case Intrinsic::sin:
  4786. case Intrinsic::cos:
  4787. case Intrinsic::floor:
  4788. case Intrinsic::ceil:
  4789. case Intrinsic::trunc:
  4790. case Intrinsic::rint:
  4791. case Intrinsic::nearbyint:
  4792. case Intrinsic::round:
  4793. case Intrinsic::canonicalize: {
  4794. unsigned Opcode;
  4795. switch (Intrinsic) {
  4796. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  4797. case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
  4798. case Intrinsic::fabs: Opcode = ISD::FABS; break;
  4799. case Intrinsic::sin: Opcode = ISD::FSIN; break;
  4800. case Intrinsic::cos: Opcode = ISD::FCOS; break;
  4801. case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
  4802. case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
  4803. case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
  4804. case Intrinsic::rint: Opcode = ISD::FRINT; break;
  4805. case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
  4806. case Intrinsic::round: Opcode = ISD::FROUND; break;
  4807. case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
  4808. }
  4809. setValue(&I, DAG.getNode(Opcode, sdl,
  4810. getValue(I.getArgOperand(0)).getValueType(),
  4811. getValue(I.getArgOperand(0))));
  4812. return nullptr;
  4813. }
  4814. case Intrinsic::minnum: {
  4815. auto VT = getValue(I.getArgOperand(0)).getValueType();
  4816. unsigned Opc =
  4817. I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT)
  4818. ? ISD::FMINNAN
  4819. : ISD::FMINNUM;
  4820. setValue(&I, DAG.getNode(Opc, sdl, VT,
  4821. getValue(I.getArgOperand(0)),
  4822. getValue(I.getArgOperand(1))));
  4823. return nullptr;
  4824. }
  4825. case Intrinsic::maxnum: {
  4826. auto VT = getValue(I.getArgOperand(0)).getValueType();
  4827. unsigned Opc =
  4828. I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT)
  4829. ? ISD::FMAXNAN
  4830. : ISD::FMAXNUM;
  4831. setValue(&I, DAG.getNode(Opc, sdl, VT,
  4832. getValue(I.getArgOperand(0)),
  4833. getValue(I.getArgOperand(1))));
  4834. return nullptr;
  4835. }
  4836. case Intrinsic::copysign:
  4837. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
  4838. getValue(I.getArgOperand(0)).getValueType(),
  4839. getValue(I.getArgOperand(0)),
  4840. getValue(I.getArgOperand(1))));
  4841. return nullptr;
  4842. case Intrinsic::fma:
  4843. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  4844. getValue(I.getArgOperand(0)).getValueType(),
  4845. getValue(I.getArgOperand(0)),
  4846. getValue(I.getArgOperand(1)),
  4847. getValue(I.getArgOperand(2))));
  4848. return nullptr;
  4849. case Intrinsic::experimental_constrained_fadd:
  4850. case Intrinsic::experimental_constrained_fsub:
  4851. case Intrinsic::experimental_constrained_fmul:
  4852. case Intrinsic::experimental_constrained_fdiv:
  4853. case Intrinsic::experimental_constrained_frem:
  4854. case Intrinsic::experimental_constrained_fma:
  4855. case Intrinsic::experimental_constrained_sqrt:
  4856. case Intrinsic::experimental_constrained_pow:
  4857. case Intrinsic::experimental_constrained_powi:
  4858. case Intrinsic::experimental_constrained_sin:
  4859. case Intrinsic::experimental_constrained_cos:
  4860. case Intrinsic::experimental_constrained_exp:
  4861. case Intrinsic::experimental_constrained_exp2:
  4862. case Intrinsic::experimental_constrained_log:
  4863. case Intrinsic::experimental_constrained_log10:
  4864. case Intrinsic::experimental_constrained_log2:
  4865. case Intrinsic::experimental_constrained_rint:
  4866. case Intrinsic::experimental_constrained_nearbyint:
  4867. visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
  4868. return nullptr;
  4869. case Intrinsic::fmuladd: {
  4870. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4871. if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
  4872. TLI.isFMAFasterThanFMulAndFAdd(VT)) {
  4873. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  4874. getValue(I.getArgOperand(0)).getValueType(),
  4875. getValue(I.getArgOperand(0)),
  4876. getValue(I.getArgOperand(1)),
  4877. getValue(I.getArgOperand(2))));
  4878. } else {
  4879. // TODO: Intrinsic calls should have fast-math-flags.
  4880. SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
  4881. getValue(I.getArgOperand(0)).getValueType(),
  4882. getValue(I.getArgOperand(0)),
  4883. getValue(I.getArgOperand(1)));
  4884. SDValue Add = DAG.getNode(ISD::FADD, sdl,
  4885. getValue(I.getArgOperand(0)).getValueType(),
  4886. Mul,
  4887. getValue(I.getArgOperand(2)));
  4888. setValue(&I, Add);
  4889. }
  4890. return nullptr;
  4891. }
  4892. case Intrinsic::convert_to_fp16:
  4893. setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
  4894. DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
  4895. getValue(I.getArgOperand(0)),
  4896. DAG.getTargetConstant(0, sdl,
  4897. MVT::i32))));
  4898. return nullptr;
  4899. case Intrinsic::convert_from_fp16:
  4900. setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
  4901. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  4902. DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
  4903. getValue(I.getArgOperand(0)))));
  4904. return nullptr;
  4905. case Intrinsic::pcmarker: {
  4906. SDValue Tmp = getValue(I.getArgOperand(0));
  4907. DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
  4908. return nullptr;
  4909. }
  4910. case Intrinsic::readcyclecounter: {
  4911. SDValue Op = getRoot();
  4912. Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
  4913. DAG.getVTList(MVT::i64, MVT::Other), Op);
  4914. setValue(&I, Res);
  4915. DAG.setRoot(Res.getValue(1));
  4916. return nullptr;
  4917. }
  4918. case Intrinsic::bitreverse:
  4919. setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
  4920. getValue(I.getArgOperand(0)).getValueType(),
  4921. getValue(I.getArgOperand(0))));
  4922. return nullptr;
  4923. case Intrinsic::bswap:
  4924. setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
  4925. getValue(I.getArgOperand(0)).getValueType(),
  4926. getValue(I.getArgOperand(0))));
  4927. return nullptr;
  4928. case Intrinsic::cttz: {
  4929. SDValue Arg = getValue(I.getArgOperand(0));
  4930. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  4931. EVT Ty = Arg.getValueType();
  4932. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
  4933. sdl, Ty, Arg));
  4934. return nullptr;
  4935. }
  4936. case Intrinsic::ctlz: {
  4937. SDValue Arg = getValue(I.getArgOperand(0));
  4938. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  4939. EVT Ty = Arg.getValueType();
  4940. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
  4941. sdl, Ty, Arg));
  4942. return nullptr;
  4943. }
  4944. case Intrinsic::ctpop: {
  4945. SDValue Arg = getValue(I.getArgOperand(0));
  4946. EVT Ty = Arg.getValueType();
  4947. setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
  4948. return nullptr;
  4949. }
  4950. case Intrinsic::stacksave: {
  4951. SDValue Op = getRoot();
  4952. Res = DAG.getNode(
  4953. ISD::STACKSAVE, sdl,
  4954. DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
  4955. setValue(&I, Res);
  4956. DAG.setRoot(Res.getValue(1));
  4957. return nullptr;
  4958. }
  4959. case Intrinsic::stackrestore:
  4960. Res = getValue(I.getArgOperand(0));
  4961. DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
  4962. return nullptr;
  4963. case Intrinsic::get_dynamic_area_offset: {
  4964. SDValue Op = getRoot();
  4965. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  4966. EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4967. // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
  4968. // target.
  4969. if (PtrTy != ResTy)
  4970. report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
  4971. " intrinsic!");
  4972. Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
  4973. Op);
  4974. DAG.setRoot(Op);
  4975. setValue(&I, Res);
  4976. return nullptr;
  4977. }
  4978. case Intrinsic::stackguard: {
  4979. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  4980. MachineFunction &MF = DAG.getMachineFunction();
  4981. const Module &M = *MF.getFunction().getParent();
  4982. SDValue Chain = getRoot();
  4983. if (TLI.useLoadStackGuardNode()) {
  4984. Res = getLoadStackGuard(DAG, sdl, Chain);
  4985. } else {
  4986. const Value *Global = TLI.getSDagStackGuard(M);
  4987. unsigned Align = DL->getPrefTypeAlignment(Global->getType());
  4988. Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
  4989. MachinePointerInfo(Global, 0), Align,
  4990. MachineMemOperand::MOVolatile);
  4991. }
  4992. if (TLI.useStackGuardXorFP())
  4993. Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
  4994. DAG.setRoot(Chain);
  4995. setValue(&I, Res);
  4996. return nullptr;
  4997. }
  4998. case Intrinsic::stackprotector: {
  4999. // Emit code into the DAG to store the stack guard onto the stack.
  5000. MachineFunction &MF = DAG.getMachineFunction();
  5001. MachineFrameInfo &MFI = MF.getFrameInfo();
  5002. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5003. SDValue Src, Chain = getRoot();
  5004. if (TLI.useLoadStackGuardNode())
  5005. Src = getLoadStackGuard(DAG, sdl, Chain);
  5006. else
  5007. Src = getValue(I.getArgOperand(0)); // The guard's value.
  5008. AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
  5009. int FI = FuncInfo.StaticAllocaMap[Slot];
  5010. MFI.setStackProtectorIndex(FI);
  5011. SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
  5012. // Store the stack protector onto the stack.
  5013. Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
  5014. DAG.getMachineFunction(), FI),
  5015. /* Alignment = */ 0, MachineMemOperand::MOVolatile);
  5016. setValue(&I, Res);
  5017. DAG.setRoot(Res);
  5018. return nullptr;
  5019. }
  5020. case Intrinsic::objectsize: {
  5021. // If we don't know by now, we're never going to know.
  5022. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
  5023. assert(CI && "Non-constant type in __builtin_object_size?");
  5024. SDValue Arg = getValue(I.getCalledValue());
  5025. EVT Ty = Arg.getValueType();
  5026. if (CI->isZero())
  5027. Res = DAG.getConstant(-1ULL, sdl, Ty);
  5028. else
  5029. Res = DAG.getConstant(0, sdl, Ty);
  5030. setValue(&I, Res);
  5031. return nullptr;
  5032. }
  5033. case Intrinsic::annotation:
  5034. case Intrinsic::ptr_annotation:
  5035. case Intrinsic::invariant_group_barrier:
  5036. // Drop the intrinsic, but forward the value
  5037. setValue(&I, getValue(I.getOperand(0)));
  5038. return nullptr;
  5039. case Intrinsic::assume:
  5040. case Intrinsic::var_annotation:
  5041. case Intrinsic::sideeffect:
  5042. // Discard annotate attributes, assumptions, and artificial side-effects.
  5043. return nullptr;
  5044. case Intrinsic::codeview_annotation: {
  5045. // Emit a label associated with this metadata.
  5046. MachineFunction &MF = DAG.getMachineFunction();
  5047. MCSymbol *Label =
  5048. MF.getMMI().getContext().createTempSymbol("annotation", true);
  5049. Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
  5050. MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
  5051. Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
  5052. DAG.setRoot(Res);
  5053. return nullptr;
  5054. }
  5055. case Intrinsic::init_trampoline: {
  5056. const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
  5057. SDValue Ops[6];
  5058. Ops[0] = getRoot();
  5059. Ops[1] = getValue(I.getArgOperand(0));
  5060. Ops[2] = getValue(I.getArgOperand(1));
  5061. Ops[3] = getValue(I.getArgOperand(2));
  5062. Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
  5063. Ops[5] = DAG.getSrcValue(F);
  5064. Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
  5065. DAG.setRoot(Res);
  5066. return nullptr;
  5067. }
  5068. case Intrinsic::adjust_trampoline:
  5069. setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
  5070. TLI.getPointerTy(DAG.getDataLayout()),
  5071. getValue(I.getArgOperand(0))));
  5072. return nullptr;
  5073. case Intrinsic::gcroot: {
  5074. assert(DAG.getMachineFunction().getFunction().hasGC() &&
  5075. "only valid in functions with gc specified, enforced by Verifier");
  5076. assert(GFI && "implied by previous");
  5077. const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
  5078. const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
  5079. FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
  5080. GFI->addStackRoot(FI->getIndex(), TypeMap);
  5081. return nullptr;
  5082. }
  5083. case Intrinsic::gcread:
  5084. case Intrinsic::gcwrite:
  5085. llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
  5086. case Intrinsic::flt_rounds:
  5087. setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
  5088. return nullptr;
  5089. case Intrinsic::expect:
  5090. // Just replace __builtin_expect(exp, c) with EXP.
  5091. setValue(&I, getValue(I.getArgOperand(0)));
  5092. return nullptr;
  5093. case Intrinsic::debugtrap:
  5094. case Intrinsic::trap: {
  5095. StringRef TrapFuncName =
  5096. I.getAttributes()
  5097. .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
  5098. .getValueAsString();
  5099. if (TrapFuncName.empty()) {
  5100. ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
  5101. ISD::TRAP : ISD::DEBUGTRAP;
  5102. DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
  5103. return nullptr;
  5104. }
  5105. TargetLowering::ArgListTy Args;
  5106. TargetLowering::CallLoweringInfo CLI(DAG);
  5107. CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
  5108. CallingConv::C, I.getType(),
  5109. DAG.getExternalSymbol(TrapFuncName.data(),
  5110. TLI.getPointerTy(DAG.getDataLayout())),
  5111. std::move(Args));
  5112. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  5113. DAG.setRoot(Result.second);
  5114. return nullptr;
  5115. }
  5116. case Intrinsic::uadd_with_overflow:
  5117. case Intrinsic::sadd_with_overflow:
  5118. case Intrinsic::usub_with_overflow:
  5119. case Intrinsic::ssub_with_overflow:
  5120. case Intrinsic::umul_with_overflow:
  5121. case Intrinsic::smul_with_overflow: {
  5122. ISD::NodeType Op;
  5123. switch (Intrinsic) {
  5124. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5125. case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
  5126. case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
  5127. case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
  5128. case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
  5129. case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
  5130. case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
  5131. }
  5132. SDValue Op1 = getValue(I.getArgOperand(0));
  5133. SDValue Op2 = getValue(I.getArgOperand(1));
  5134. SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
  5135. setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
  5136. return nullptr;
  5137. }
  5138. case Intrinsic::prefetch: {
  5139. SDValue Ops[5];
  5140. unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  5141. auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
  5142. Ops[0] = getRoot();
  5143. Ops[1] = getValue(I.getArgOperand(0));
  5144. Ops[2] = getValue(I.getArgOperand(1));
  5145. Ops[3] = getValue(I.getArgOperand(2));
  5146. Ops[4] = getValue(I.getArgOperand(3));
  5147. DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
  5148. DAG.getVTList(MVT::Other), Ops,
  5149. EVT::getIntegerVT(*Context, 8),
  5150. MachinePointerInfo(I.getArgOperand(0)),
  5151. 0, /* align */
  5152. Flags));
  5153. return nullptr;
  5154. }
  5155. case Intrinsic::lifetime_start:
  5156. case Intrinsic::lifetime_end: {
  5157. bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
  5158. // Stack coloring is not enabled in O0, discard region information.
  5159. if (TM.getOptLevel() == CodeGenOpt::None)
  5160. return nullptr;
  5161. SmallVector<Value *, 4> Allocas;
  5162. GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL);
  5163. for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
  5164. E = Allocas.end(); Object != E; ++Object) {
  5165. AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
  5166. // Could not find an Alloca.
  5167. if (!LifetimeObject)
  5168. continue;
  5169. // First check that the Alloca is static, otherwise it won't have a
  5170. // valid frame index.
  5171. auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
  5172. if (SI == FuncInfo.StaticAllocaMap.end())
  5173. return nullptr;
  5174. int FI = SI->second;
  5175. SDValue Ops[2];
  5176. Ops[0] = getRoot();
  5177. Ops[1] =
  5178. DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true);
  5179. unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
  5180. Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
  5181. DAG.setRoot(Res);
  5182. }
  5183. return nullptr;
  5184. }
  5185. case Intrinsic::invariant_start:
  5186. // Discard region information.
  5187. setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
  5188. return nullptr;
  5189. case Intrinsic::invariant_end:
  5190. // Discard region information.
  5191. return nullptr;
  5192. case Intrinsic::clear_cache:
  5193. return TLI.getClearCacheBuiltinName();
  5194. case Intrinsic::donothing:
  5195. // ignore
  5196. return nullptr;
  5197. case Intrinsic::experimental_stackmap:
  5198. visitStackmap(I);
  5199. return nullptr;
  5200. case Intrinsic::experimental_patchpoint_void:
  5201. case Intrinsic::experimental_patchpoint_i64:
  5202. visitPatchpoint(&I);
  5203. return nullptr;
  5204. case Intrinsic::experimental_gc_statepoint:
  5205. LowerStatepoint(ImmutableStatepoint(&I));
  5206. return nullptr;
  5207. case Intrinsic::experimental_gc_result:
  5208. visitGCResult(cast<GCResultInst>(I));
  5209. return nullptr;
  5210. case Intrinsic::experimental_gc_relocate:
  5211. visitGCRelocate(cast<GCRelocateInst>(I));
  5212. return nullptr;
  5213. case Intrinsic::instrprof_increment:
  5214. llvm_unreachable("instrprof failed to lower an increment");
  5215. case Intrinsic::instrprof_value_profile:
  5216. llvm_unreachable("instrprof failed to lower a value profiling call");
  5217. case Intrinsic::localescape: {
  5218. MachineFunction &MF = DAG.getMachineFunction();
  5219. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  5220. // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
  5221. // is the same on all targets.
  5222. for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
  5223. Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
  5224. if (isa<ConstantPointerNull>(Arg))
  5225. continue; // Skip null pointers. They represent a hole in index space.
  5226. AllocaInst *Slot = cast<AllocaInst>(Arg);
  5227. assert(FuncInfo.StaticAllocaMap.count(Slot) &&
  5228. "can only escape static allocas");
  5229. int FI = FuncInfo.StaticAllocaMap[Slot];
  5230. MCSymbol *FrameAllocSym =
  5231. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  5232. GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
  5233. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
  5234. TII->get(TargetOpcode::LOCAL_ESCAPE))
  5235. .addSym(FrameAllocSym)
  5236. .addFrameIndex(FI);
  5237. }
  5238. return nullptr;
  5239. }
  5240. case Intrinsic::localrecover: {
  5241. // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
  5242. MachineFunction &MF = DAG.getMachineFunction();
  5243. MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
  5244. // Get the symbol that defines the frame offset.
  5245. auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
  5246. auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
  5247. unsigned IdxVal =
  5248. unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
  5249. MCSymbol *FrameAllocSym =
  5250. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  5251. GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
  5252. // Create a MCSymbol for the label to avoid any target lowering
  5253. // that would make this PC relative.
  5254. SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
  5255. SDValue OffsetVal =
  5256. DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
  5257. // Add the offset to the FP.
  5258. Value *FP = I.getArgOperand(1);
  5259. SDValue FPVal = getValue(FP);
  5260. SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
  5261. setValue(&I, Add);
  5262. return nullptr;
  5263. }
  5264. case Intrinsic::eh_exceptionpointer:
  5265. case Intrinsic::eh_exceptioncode: {
  5266. // Get the exception pointer vreg, copy from it, and resize it to fit.
  5267. const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
  5268. MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
  5269. const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
  5270. unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
  5271. SDValue N =
  5272. DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
  5273. if (Intrinsic == Intrinsic::eh_exceptioncode)
  5274. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
  5275. setValue(&I, N);
  5276. return nullptr;
  5277. }
  5278. case Intrinsic::xray_customevent: {
  5279. // Here we want to make sure that the intrinsic behaves as if it has a
  5280. // specific calling convention, and only for x86_64.
  5281. // FIXME: Support other platforms later.
  5282. const auto &Triple = DAG.getTarget().getTargetTriple();
  5283. if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
  5284. return nullptr;
  5285. SDLoc DL = getCurSDLoc();
  5286. SmallVector<SDValue, 8> Ops;
  5287. // We want to say that we always want the arguments in registers.
  5288. SDValue LogEntryVal = getValue(I.getArgOperand(0));
  5289. SDValue StrSizeVal = getValue(I.getArgOperand(1));
  5290. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  5291. SDValue Chain = getRoot();
  5292. Ops.push_back(LogEntryVal);
  5293. Ops.push_back(StrSizeVal);
  5294. Ops.push_back(Chain);
  5295. // We need to enforce the calling convention for the callsite, so that
  5296. // argument ordering is enforced correctly, and that register allocation can
  5297. // see that some registers may be assumed clobbered and have to preserve
  5298. // them across calls to the intrinsic.
  5299. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
  5300. DL, NodeTys, Ops);
  5301. SDValue patchableNode = SDValue(MN, 0);
  5302. DAG.setRoot(patchableNode);
  5303. setValue(&I, patchableNode);
  5304. return nullptr;
  5305. }
  5306. case Intrinsic::experimental_deoptimize:
  5307. LowerDeoptimizeCall(&I);
  5308. return nullptr;
  5309. case Intrinsic::experimental_vector_reduce_fadd:
  5310. case Intrinsic::experimental_vector_reduce_fmul:
  5311. case Intrinsic::experimental_vector_reduce_add:
  5312. case Intrinsic::experimental_vector_reduce_mul:
  5313. case Intrinsic::experimental_vector_reduce_and:
  5314. case Intrinsic::experimental_vector_reduce_or:
  5315. case Intrinsic::experimental_vector_reduce_xor:
  5316. case Intrinsic::experimental_vector_reduce_smax:
  5317. case Intrinsic::experimental_vector_reduce_smin:
  5318. case Intrinsic::experimental_vector_reduce_umax:
  5319. case Intrinsic::experimental_vector_reduce_umin:
  5320. case Intrinsic::experimental_vector_reduce_fmax:
  5321. case Intrinsic::experimental_vector_reduce_fmin:
  5322. visitVectorReduce(I, Intrinsic);
  5323. return nullptr;
  5324. }
  5325. }
  5326. void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
  5327. const ConstrainedFPIntrinsic &FPI) {
  5328. SDLoc sdl = getCurSDLoc();
  5329. unsigned Opcode;
  5330. switch (FPI.getIntrinsicID()) {
  5331. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5332. case Intrinsic::experimental_constrained_fadd:
  5333. Opcode = ISD::STRICT_FADD;
  5334. break;
  5335. case Intrinsic::experimental_constrained_fsub:
  5336. Opcode = ISD::STRICT_FSUB;
  5337. break;
  5338. case Intrinsic::experimental_constrained_fmul:
  5339. Opcode = ISD::STRICT_FMUL;
  5340. break;
  5341. case Intrinsic::experimental_constrained_fdiv:
  5342. Opcode = ISD::STRICT_FDIV;
  5343. break;
  5344. case Intrinsic::experimental_constrained_frem:
  5345. Opcode = ISD::STRICT_FREM;
  5346. break;
  5347. case Intrinsic::experimental_constrained_fma:
  5348. Opcode = ISD::STRICT_FMA;
  5349. break;
  5350. case Intrinsic::experimental_constrained_sqrt:
  5351. Opcode = ISD::STRICT_FSQRT;
  5352. break;
  5353. case Intrinsic::experimental_constrained_pow:
  5354. Opcode = ISD::STRICT_FPOW;
  5355. break;
  5356. case Intrinsic::experimental_constrained_powi:
  5357. Opcode = ISD::STRICT_FPOWI;
  5358. break;
  5359. case Intrinsic::experimental_constrained_sin:
  5360. Opcode = ISD::STRICT_FSIN;
  5361. break;
  5362. case Intrinsic::experimental_constrained_cos:
  5363. Opcode = ISD::STRICT_FCOS;
  5364. break;
  5365. case Intrinsic::experimental_constrained_exp:
  5366. Opcode = ISD::STRICT_FEXP;
  5367. break;
  5368. case Intrinsic::experimental_constrained_exp2:
  5369. Opcode = ISD::STRICT_FEXP2;
  5370. break;
  5371. case Intrinsic::experimental_constrained_log:
  5372. Opcode = ISD::STRICT_FLOG;
  5373. break;
  5374. case Intrinsic::experimental_constrained_log10:
  5375. Opcode = ISD::STRICT_FLOG10;
  5376. break;
  5377. case Intrinsic::experimental_constrained_log2:
  5378. Opcode = ISD::STRICT_FLOG2;
  5379. break;
  5380. case Intrinsic::experimental_constrained_rint:
  5381. Opcode = ISD::STRICT_FRINT;
  5382. break;
  5383. case Intrinsic::experimental_constrained_nearbyint:
  5384. Opcode = ISD::STRICT_FNEARBYINT;
  5385. break;
  5386. }
  5387. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5388. SDValue Chain = getRoot();
  5389. SmallVector<EVT, 4> ValueVTs;
  5390. ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
  5391. ValueVTs.push_back(MVT::Other); // Out chain
  5392. SDVTList VTs = DAG.getVTList(ValueVTs);
  5393. SDValue Result;
  5394. if (FPI.isUnaryOp())
  5395. Result = DAG.getNode(Opcode, sdl, VTs,
  5396. { Chain, getValue(FPI.getArgOperand(0)) });
  5397. else if (FPI.isTernaryOp())
  5398. Result = DAG.getNode(Opcode, sdl, VTs,
  5399. { Chain, getValue(FPI.getArgOperand(0)),
  5400. getValue(FPI.getArgOperand(1)),
  5401. getValue(FPI.getArgOperand(2)) });
  5402. else
  5403. Result = DAG.getNode(Opcode, sdl, VTs,
  5404. { Chain, getValue(FPI.getArgOperand(0)),
  5405. getValue(FPI.getArgOperand(1)) });
  5406. assert(Result.getNode()->getNumValues() == 2);
  5407. SDValue OutChain = Result.getValue(1);
  5408. DAG.setRoot(OutChain);
  5409. SDValue FPResult = Result.getValue(0);
  5410. setValue(&FPI, FPResult);
  5411. }
  5412. std::pair<SDValue, SDValue>
  5413. SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
  5414. const BasicBlock *EHPadBB) {
  5415. MachineFunction &MF = DAG.getMachineFunction();
  5416. MachineModuleInfo &MMI = MF.getMMI();
  5417. MCSymbol *BeginLabel = nullptr;
  5418. if (EHPadBB) {
  5419. // Insert a label before the invoke call to mark the try range. This can be
  5420. // used to detect deletion of the invoke via the MachineModuleInfo.
  5421. BeginLabel = MMI.getContext().createTempSymbol();
  5422. // For SjLj, keep track of which landing pads go with which invokes
  5423. // so as to maintain the ordering of pads in the LSDA.
  5424. unsigned CallSiteIndex = MMI.getCurrentCallSite();
  5425. if (CallSiteIndex) {
  5426. MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
  5427. LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
  5428. // Now that the call site is handled, stop tracking it.
  5429. MMI.setCurrentCallSite(0);
  5430. }
  5431. // Both PendingLoads and PendingExports must be flushed here;
  5432. // this call might not return.
  5433. (void)getRoot();
  5434. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
  5435. CLI.setChain(getRoot());
  5436. }
  5437. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5438. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  5439. assert((CLI.IsTailCall || Result.second.getNode()) &&
  5440. "Non-null chain expected with non-tail call!");
  5441. assert((Result.second.getNode() || !Result.first.getNode()) &&
  5442. "Null value expected with tail call!");
  5443. if (!Result.second.getNode()) {
  5444. // As a special case, a null chain means that a tail call has been emitted
  5445. // and the DAG root is already updated.
  5446. HasTailCall = true;
  5447. // Since there's no actual continuation from this block, nothing can be
  5448. // relying on us setting vregs for them.
  5449. PendingExports.clear();
  5450. } else {
  5451. DAG.setRoot(Result.second);
  5452. }
  5453. if (EHPadBB) {
  5454. // Insert a label at the end of the invoke call to mark the try range. This
  5455. // can be used to detect deletion of the invoke via the MachineModuleInfo.
  5456. MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
  5457. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
  5458. // Inform MachineModuleInfo of range.
  5459. if (MF.hasEHFunclets()) {
  5460. assert(CLI.CS);
  5461. WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
  5462. EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
  5463. BeginLabel, EndLabel);
  5464. } else {
  5465. MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
  5466. }
  5467. }
  5468. return Result;
  5469. }
  5470. void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
  5471. bool isTailCall,
  5472. const BasicBlock *EHPadBB) {
  5473. auto &DL = DAG.getDataLayout();
  5474. FunctionType *FTy = CS.getFunctionType();
  5475. Type *RetTy = CS.getType();
  5476. TargetLowering::ArgListTy Args;
  5477. Args.reserve(CS.arg_size());
  5478. const Value *SwiftErrorVal = nullptr;
  5479. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5480. // We can't tail call inside a function with a swifterror argument. Lowering
  5481. // does not support this yet. It would have to move into the swifterror
  5482. // register before the call.
  5483. auto *Caller = CS.getInstruction()->getParent()->getParent();
  5484. if (TLI.supportSwiftError() &&
  5485. Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
  5486. isTailCall = false;
  5487. for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
  5488. i != e; ++i) {
  5489. TargetLowering::ArgListEntry Entry;
  5490. const Value *V = *i;
  5491. // Skip empty types
  5492. if (V->getType()->isEmptyTy())
  5493. continue;
  5494. SDValue ArgNode = getValue(V);
  5495. Entry.Node = ArgNode; Entry.Ty = V->getType();
  5496. Entry.setAttributes(&CS, i - CS.arg_begin());
  5497. // Use swifterror virtual register as input to the call.
  5498. if (Entry.IsSwiftError && TLI.supportSwiftError()) {
  5499. SwiftErrorVal = V;
  5500. // We find the virtual register for the actual swifterror argument.
  5501. // Instead of using the Value, we use the virtual register instead.
  5502. Entry.Node = DAG.getRegister(FuncInfo
  5503. .getOrCreateSwiftErrorVRegUseAt(
  5504. CS.getInstruction(), FuncInfo.MBB, V)
  5505. .first,
  5506. EVT(TLI.getPointerTy(DL)));
  5507. }
  5508. Args.push_back(Entry);
  5509. // If we have an explicit sret argument that is an Instruction, (i.e., it
  5510. // might point to function-local memory), we can't meaningfully tail-call.
  5511. if (Entry.IsSRet && isa<Instruction>(V))
  5512. isTailCall = false;
  5513. }
  5514. // Check if target-independent constraints permit a tail call here.
  5515. // Target-dependent constraints are checked within TLI->LowerCallTo.
  5516. if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
  5517. isTailCall = false;
  5518. // Disable tail calls if there is an swifterror argument. Targets have not
  5519. // been updated to support tail calls.
  5520. if (TLI.supportSwiftError() && SwiftErrorVal)
  5521. isTailCall = false;
  5522. TargetLowering::CallLoweringInfo CLI(DAG);
  5523. CLI.setDebugLoc(getCurSDLoc())
  5524. .setChain(getRoot())
  5525. .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
  5526. .setTailCall(isTailCall)
  5527. .setConvergent(CS.isConvergent());
  5528. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  5529. if (Result.first.getNode()) {
  5530. const Instruction *Inst = CS.getInstruction();
  5531. Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
  5532. setValue(Inst, Result.first);
  5533. }
  5534. // The last element of CLI.InVals has the SDValue for swifterror return.
  5535. // Here we copy it to a virtual register and update SwiftErrorMap for
  5536. // book-keeping.
  5537. if (SwiftErrorVal && TLI.supportSwiftError()) {
  5538. // Get the last element of InVals.
  5539. SDValue Src = CLI.InVals.back();
  5540. unsigned VReg; bool CreatedVReg;
  5541. std::tie(VReg, CreatedVReg) =
  5542. FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction());
  5543. SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
  5544. // We update the virtual register for the actual swifterror argument.
  5545. if (CreatedVReg)
  5546. FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg);
  5547. DAG.setRoot(CopyNode);
  5548. }
  5549. }
  5550. static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
  5551. SelectionDAGBuilder &Builder) {
  5552. // Check to see if this load can be trivially constant folded, e.g. if the
  5553. // input is from a string literal.
  5554. if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
  5555. // Cast pointer to the type we really want to load.
  5556. Type *LoadTy =
  5557. Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
  5558. if (LoadVT.isVector())
  5559. LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
  5560. LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
  5561. PointerType::getUnqual(LoadTy));
  5562. if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
  5563. const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
  5564. return Builder.getValue(LoadCst);
  5565. }
  5566. // Otherwise, we have to emit the load. If the pointer is to unfoldable but
  5567. // still constant memory, the input chain can be the entry node.
  5568. SDValue Root;
  5569. bool ConstantMemory = false;
  5570. // Do not serialize (non-volatile) loads of constant memory with anything.
  5571. if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
  5572. Root = Builder.DAG.getEntryNode();
  5573. ConstantMemory = true;
  5574. } else {
  5575. // Do not serialize non-volatile loads against each other.
  5576. Root = Builder.DAG.getRoot();
  5577. }
  5578. SDValue Ptr = Builder.getValue(PtrVal);
  5579. SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
  5580. Ptr, MachinePointerInfo(PtrVal),
  5581. /* Alignment = */ 1);
  5582. if (!ConstantMemory)
  5583. Builder.PendingLoads.push_back(LoadVal.getValue(1));
  5584. return LoadVal;
  5585. }
  5586. /// Record the value for an instruction that produces an integer result,
  5587. /// converting the type where necessary.
  5588. void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
  5589. SDValue Value,
  5590. bool IsSigned) {
  5591. EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  5592. I.getType(), true);
  5593. if (IsSigned)
  5594. Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
  5595. else
  5596. Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
  5597. setValue(&I, Value);
  5598. }
  5599. /// See if we can lower a memcmp call into an optimized form. If so, return
  5600. /// true and lower it. Otherwise return false, and it will be lowered like a
  5601. /// normal call.
  5602. /// The caller already checked that \p I calls the appropriate LibFunc with a
  5603. /// correct prototype.
  5604. bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
  5605. const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
  5606. const Value *Size = I.getArgOperand(2);
  5607. const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
  5608. if (CSize && CSize->getZExtValue() == 0) {
  5609. EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  5610. I.getType(), true);
  5611. setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
  5612. return true;
  5613. }
  5614. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  5615. std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
  5616. DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
  5617. getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
  5618. if (Res.first.getNode()) {
  5619. processIntegerCallValue(I, Res.first, true);
  5620. PendingLoads.push_back(Res.second);
  5621. return true;
  5622. }
  5623. // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
  5624. // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
  5625. if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
  5626. return false;
  5627. // If the target has a fast compare for the given size, it will return a
  5628. // preferred load type for that size. Require that the load VT is legal and
  5629. // that the target supports unaligned loads of that type. Otherwise, return
  5630. // INVALID.
  5631. auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
  5632. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5633. MVT LVT = TLI.hasFastEqualityCompare(NumBits);
  5634. if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
  5635. // TODO: Handle 5 byte compare as 4-byte + 1 byte.
  5636. // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
  5637. // TODO: Check alignment of src and dest ptrs.
  5638. unsigned DstAS = LHS->getType()->getPointerAddressSpace();
  5639. unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
  5640. if (!TLI.isTypeLegal(LVT) ||
  5641. !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
  5642. !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
  5643. LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
  5644. }
  5645. return LVT;
  5646. };
  5647. // This turns into unaligned loads. We only do this if the target natively
  5648. // supports the MVT we'll be loading or if it is small enough (<= 4) that
  5649. // we'll only produce a small number of byte loads.
  5650. MVT LoadVT;
  5651. unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
  5652. switch (NumBitsToCompare) {
  5653. default:
  5654. return false;
  5655. case 16:
  5656. LoadVT = MVT::i16;
  5657. break;
  5658. case 32:
  5659. LoadVT = MVT::i32;
  5660. break;
  5661. case 64:
  5662. case 128:
  5663. case 256:
  5664. LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
  5665. break;
  5666. }
  5667. if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
  5668. return false;
  5669. SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
  5670. SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
  5671. // Bitcast to a wide integer type if the loads are vectors.
  5672. if (LoadVT.isVector()) {
  5673. EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
  5674. LoadL = DAG.getBitcast(CmpVT, LoadL);
  5675. LoadR = DAG.getBitcast(CmpVT, LoadR);
  5676. }
  5677. SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
  5678. processIntegerCallValue(I, Cmp, false);
  5679. return true;
  5680. }
  5681. /// See if we can lower a memchr call into an optimized form. If so, return
  5682. /// true and lower it. Otherwise return false, and it will be lowered like a
  5683. /// normal call.
  5684. /// The caller already checked that \p I calls the appropriate LibFunc with a
  5685. /// correct prototype.
  5686. bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
  5687. const Value *Src = I.getArgOperand(0);
  5688. const Value *Char = I.getArgOperand(1);
  5689. const Value *Length = I.getArgOperand(2);
  5690. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  5691. std::pair<SDValue, SDValue> Res =
  5692. TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
  5693. getValue(Src), getValue(Char), getValue(Length),
  5694. MachinePointerInfo(Src));
  5695. if (Res.first.getNode()) {
  5696. setValue(&I, Res.first);
  5697. PendingLoads.push_back(Res.second);
  5698. return true;
  5699. }
  5700. return false;
  5701. }
  5702. /// See if we can lower a mempcpy call into an optimized form. If so, return
  5703. /// true and lower it. Otherwise return false, and it will be lowered like a
  5704. /// normal call.
  5705. /// The caller already checked that \p I calls the appropriate LibFunc with a
  5706. /// correct prototype.
  5707. bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
  5708. SDValue Dst = getValue(I.getArgOperand(0));
  5709. SDValue Src = getValue(I.getArgOperand(1));
  5710. SDValue Size = getValue(I.getArgOperand(2));
  5711. unsigned DstAlign = DAG.InferPtrAlignment(Dst);
  5712. unsigned SrcAlign = DAG.InferPtrAlignment(Src);
  5713. unsigned Align = std::min(DstAlign, SrcAlign);
  5714. if (Align == 0) // Alignment of one or both could not be inferred.
  5715. Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
  5716. bool isVol = false;
  5717. SDLoc sdl = getCurSDLoc();
  5718. // In the mempcpy context we need to pass in a false value for isTailCall
  5719. // because the return pointer needs to be adjusted by the size of
  5720. // the copied memory.
  5721. SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
  5722. false, /*isTailCall=*/false,
  5723. MachinePointerInfo(I.getArgOperand(0)),
  5724. MachinePointerInfo(I.getArgOperand(1)));
  5725. assert(MC.getNode() != nullptr &&
  5726. "** memcpy should not be lowered as TailCall in mempcpy context **");
  5727. DAG.setRoot(MC);
  5728. // Check if Size needs to be truncated or extended.
  5729. Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
  5730. // Adjust return pointer to point just past the last dst byte.
  5731. SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
  5732. Dst, Size);
  5733. setValue(&I, DstPlusSize);
  5734. return true;
  5735. }
  5736. /// See if we can lower a strcpy call into an optimized form. If so, return
  5737. /// true and lower it, otherwise return false and it will be lowered like a
  5738. /// normal call.
  5739. /// The caller already checked that \p I calls the appropriate LibFunc with a
  5740. /// correct prototype.
  5741. bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
  5742. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  5743. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  5744. std::pair<SDValue, SDValue> Res =
  5745. TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
  5746. getValue(Arg0), getValue(Arg1),
  5747. MachinePointerInfo(Arg0),
  5748. MachinePointerInfo(Arg1), isStpcpy);
  5749. if (Res.first.getNode()) {
  5750. setValue(&I, Res.first);
  5751. DAG.setRoot(Res.second);
  5752. return true;
  5753. }
  5754. return false;
  5755. }
  5756. /// See if we can lower a strcmp call into an optimized form. If so, return
  5757. /// true and lower it, otherwise return false and it will be lowered like a
  5758. /// normal call.
  5759. /// The caller already checked that \p I calls the appropriate LibFunc with a
  5760. /// correct prototype.
  5761. bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
  5762. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  5763. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  5764. std::pair<SDValue, SDValue> Res =
  5765. TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
  5766. getValue(Arg0), getValue(Arg1),
  5767. MachinePointerInfo(Arg0),
  5768. MachinePointerInfo(Arg1));
  5769. if (Res.first.getNode()) {
  5770. processIntegerCallValue(I, Res.first, true);
  5771. PendingLoads.push_back(Res.second);
  5772. return true;
  5773. }
  5774. return false;
  5775. }
  5776. /// See if we can lower a strlen call into an optimized form. If so, return
  5777. /// true and lower it, otherwise return false and it will be lowered like a
  5778. /// normal call.
  5779. /// The caller already checked that \p I calls the appropriate LibFunc with a
  5780. /// correct prototype.
  5781. bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
  5782. const Value *Arg0 = I.getArgOperand(0);
  5783. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  5784. std::pair<SDValue, SDValue> Res =
  5785. TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
  5786. getValue(Arg0), MachinePointerInfo(Arg0));
  5787. if (Res.first.getNode()) {
  5788. processIntegerCallValue(I, Res.first, false);
  5789. PendingLoads.push_back(Res.second);
  5790. return true;
  5791. }
  5792. return false;
  5793. }
  5794. /// See if we can lower a strnlen call into an optimized form. If so, return
  5795. /// true and lower it, otherwise return false and it will be lowered like a
  5796. /// normal call.
  5797. /// The caller already checked that \p I calls the appropriate LibFunc with a
  5798. /// correct prototype.
  5799. bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
  5800. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  5801. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  5802. std::pair<SDValue, SDValue> Res =
  5803. TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
  5804. getValue(Arg0), getValue(Arg1),
  5805. MachinePointerInfo(Arg0));
  5806. if (Res.first.getNode()) {
  5807. processIntegerCallValue(I, Res.first, false);
  5808. PendingLoads.push_back(Res.second);
  5809. return true;
  5810. }
  5811. return false;
  5812. }
  5813. /// See if we can lower a unary floating-point operation into an SDNode with
  5814. /// the specified Opcode. If so, return true and lower it, otherwise return
  5815. /// false and it will be lowered like a normal call.
  5816. /// The caller already checked that \p I calls the appropriate LibFunc with a
  5817. /// correct prototype.
  5818. bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
  5819. unsigned Opcode) {
  5820. // We already checked this call's prototype; verify it doesn't modify errno.
  5821. if (!I.onlyReadsMemory())
  5822. return false;
  5823. SDValue Tmp = getValue(I.getArgOperand(0));
  5824. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
  5825. return true;
  5826. }
  5827. /// See if we can lower a binary floating-point operation into an SDNode with
  5828. /// the specified Opcode. If so, return true and lower it. Otherwise return
  5829. /// false, and it will be lowered like a normal call.
  5830. /// The caller already checked that \p I calls the appropriate LibFunc with a
  5831. /// correct prototype.
  5832. bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
  5833. unsigned Opcode) {
  5834. // We already checked this call's prototype; verify it doesn't modify errno.
  5835. if (!I.onlyReadsMemory())
  5836. return false;
  5837. SDValue Tmp0 = getValue(I.getArgOperand(0));
  5838. SDValue Tmp1 = getValue(I.getArgOperand(1));
  5839. EVT VT = Tmp0.getValueType();
  5840. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
  5841. return true;
  5842. }
  5843. void SelectionDAGBuilder::visitCall(const CallInst &I) {
  5844. // Handle inline assembly differently.
  5845. if (isa<InlineAsm>(I.getCalledValue())) {
  5846. visitInlineAsm(&I);
  5847. return;
  5848. }
  5849. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  5850. computeUsesVAFloatArgument(I, MMI);
  5851. const char *RenameFn = nullptr;
  5852. if (Function *F = I.getCalledFunction()) {
  5853. if (F->isDeclaration()) {
  5854. if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
  5855. if (unsigned IID = II->getIntrinsicID(F)) {
  5856. RenameFn = visitIntrinsicCall(I, IID);
  5857. if (!RenameFn)
  5858. return;
  5859. }
  5860. }
  5861. if (Intrinsic::ID IID = F->getIntrinsicID()) {
  5862. RenameFn = visitIntrinsicCall(I, IID);
  5863. if (!RenameFn)
  5864. return;
  5865. }
  5866. }
  5867. // Check for well-known libc/libm calls. If the function is internal, it
  5868. // can't be a library call. Don't do the check if marked as nobuiltin for
  5869. // some reason or the call site requires strict floating point semantics.
  5870. LibFunc Func;
  5871. if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
  5872. F->hasName() && LibInfo->getLibFunc(*F, Func) &&
  5873. LibInfo->hasOptimizedCodeGen(Func)) {
  5874. switch (Func) {
  5875. default: break;
  5876. case LibFunc_copysign:
  5877. case LibFunc_copysignf:
  5878. case LibFunc_copysignl:
  5879. // We already checked this call's prototype; verify it doesn't modify
  5880. // errno.
  5881. if (I.onlyReadsMemory()) {
  5882. SDValue LHS = getValue(I.getArgOperand(0));
  5883. SDValue RHS = getValue(I.getArgOperand(1));
  5884. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
  5885. LHS.getValueType(), LHS, RHS));
  5886. return;
  5887. }
  5888. break;
  5889. case LibFunc_fabs:
  5890. case LibFunc_fabsf:
  5891. case LibFunc_fabsl:
  5892. if (visitUnaryFloatCall(I, ISD::FABS))
  5893. return;
  5894. break;
  5895. case LibFunc_fmin:
  5896. case LibFunc_fminf:
  5897. case LibFunc_fminl:
  5898. if (visitBinaryFloatCall(I, ISD::FMINNUM))
  5899. return;
  5900. break;
  5901. case LibFunc_fmax:
  5902. case LibFunc_fmaxf:
  5903. case LibFunc_fmaxl:
  5904. if (visitBinaryFloatCall(I, ISD::FMAXNUM))
  5905. return;
  5906. break;
  5907. case LibFunc_sin:
  5908. case LibFunc_sinf:
  5909. case LibFunc_sinl:
  5910. if (visitUnaryFloatCall(I, ISD::FSIN))
  5911. return;
  5912. break;
  5913. case LibFunc_cos:
  5914. case LibFunc_cosf:
  5915. case LibFunc_cosl:
  5916. if (visitUnaryFloatCall(I, ISD::FCOS))
  5917. return;
  5918. break;
  5919. case LibFunc_sqrt:
  5920. case LibFunc_sqrtf:
  5921. case LibFunc_sqrtl:
  5922. case LibFunc_sqrt_finite:
  5923. case LibFunc_sqrtf_finite:
  5924. case LibFunc_sqrtl_finite:
  5925. if (visitUnaryFloatCall(I, ISD::FSQRT))
  5926. return;
  5927. break;
  5928. case LibFunc_floor:
  5929. case LibFunc_floorf:
  5930. case LibFunc_floorl:
  5931. if (visitUnaryFloatCall(I, ISD::FFLOOR))
  5932. return;
  5933. break;
  5934. case LibFunc_nearbyint:
  5935. case LibFunc_nearbyintf:
  5936. case LibFunc_nearbyintl:
  5937. if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
  5938. return;
  5939. break;
  5940. case LibFunc_ceil:
  5941. case LibFunc_ceilf:
  5942. case LibFunc_ceill:
  5943. if (visitUnaryFloatCall(I, ISD::FCEIL))
  5944. return;
  5945. break;
  5946. case LibFunc_rint:
  5947. case LibFunc_rintf:
  5948. case LibFunc_rintl:
  5949. if (visitUnaryFloatCall(I, ISD::FRINT))
  5950. return;
  5951. break;
  5952. case LibFunc_round:
  5953. case LibFunc_roundf:
  5954. case LibFunc_roundl:
  5955. if (visitUnaryFloatCall(I, ISD::FROUND))
  5956. return;
  5957. break;
  5958. case LibFunc_trunc:
  5959. case LibFunc_truncf:
  5960. case LibFunc_truncl:
  5961. if (visitUnaryFloatCall(I, ISD::FTRUNC))
  5962. return;
  5963. break;
  5964. case LibFunc_log2:
  5965. case LibFunc_log2f:
  5966. case LibFunc_log2l:
  5967. if (visitUnaryFloatCall(I, ISD::FLOG2))
  5968. return;
  5969. break;
  5970. case LibFunc_exp2:
  5971. case LibFunc_exp2f:
  5972. case LibFunc_exp2l:
  5973. if (visitUnaryFloatCall(I, ISD::FEXP2))
  5974. return;
  5975. break;
  5976. case LibFunc_memcmp:
  5977. if (visitMemCmpCall(I))
  5978. return;
  5979. break;
  5980. case LibFunc_mempcpy:
  5981. if (visitMemPCpyCall(I))
  5982. return;
  5983. break;
  5984. case LibFunc_memchr:
  5985. if (visitMemChrCall(I))
  5986. return;
  5987. break;
  5988. case LibFunc_strcpy:
  5989. if (visitStrCpyCall(I, false))
  5990. return;
  5991. break;
  5992. case LibFunc_stpcpy:
  5993. if (visitStrCpyCall(I, true))
  5994. return;
  5995. break;
  5996. case LibFunc_strcmp:
  5997. if (visitStrCmpCall(I))
  5998. return;
  5999. break;
  6000. case LibFunc_strlen:
  6001. if (visitStrLenCall(I))
  6002. return;
  6003. break;
  6004. case LibFunc_strnlen:
  6005. if (visitStrNLenCall(I))
  6006. return;
  6007. break;
  6008. }
  6009. }
  6010. }
  6011. SDValue Callee;
  6012. if (!RenameFn)
  6013. Callee = getValue(I.getCalledValue());
  6014. else
  6015. Callee = DAG.getExternalSymbol(
  6016. RenameFn,
  6017. DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
  6018. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  6019. // have to do anything here to lower funclet bundles.
  6020. assert(!I.hasOperandBundlesOtherThan(
  6021. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  6022. "Cannot lower calls with arbitrary operand bundles!");
  6023. if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
  6024. LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
  6025. else
  6026. // Check if we can potentially perform a tail call. More detailed checking
  6027. // is be done within LowerCallTo, after more information about the call is
  6028. // known.
  6029. LowerCallTo(&I, Callee, I.isTailCall());
  6030. }
  6031. namespace {
  6032. /// AsmOperandInfo - This contains information for each constraint that we are
  6033. /// lowering.
  6034. class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
  6035. public:
  6036. /// CallOperand - If this is the result output operand or a clobber
  6037. /// this is null, otherwise it is the incoming operand to the CallInst.
  6038. /// This gets modified as the asm is processed.
  6039. SDValue CallOperand;
  6040. /// AssignedRegs - If this is a register or register class operand, this
  6041. /// contains the set of register corresponding to the operand.
  6042. RegsForValue AssignedRegs;
  6043. explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
  6044. : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
  6045. }
  6046. /// Whether or not this operand accesses memory
  6047. bool hasMemory(const TargetLowering &TLI) const {
  6048. // Indirect operand accesses access memory.
  6049. if (isIndirect)
  6050. return true;
  6051. for (const auto &Code : Codes)
  6052. if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
  6053. return true;
  6054. return false;
  6055. }
  6056. /// getCallOperandValEVT - Return the EVT of the Value* that this operand
  6057. /// corresponds to. If there is no Value* for this operand, it returns
  6058. /// MVT::Other.
  6059. EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
  6060. const DataLayout &DL) const {
  6061. if (!CallOperandVal) return MVT::Other;
  6062. if (isa<BasicBlock>(CallOperandVal))
  6063. return TLI.getPointerTy(DL);
  6064. llvm::Type *OpTy = CallOperandVal->getType();
  6065. // FIXME: code duplicated from TargetLowering::ParseConstraints().
  6066. // If this is an indirect operand, the operand is a pointer to the
  6067. // accessed type.
  6068. if (isIndirect) {
  6069. PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
  6070. if (!PtrTy)
  6071. report_fatal_error("Indirect operand for inline asm not a pointer!");
  6072. OpTy = PtrTy->getElementType();
  6073. }
  6074. // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
  6075. if (StructType *STy = dyn_cast<StructType>(OpTy))
  6076. if (STy->getNumElements() == 1)
  6077. OpTy = STy->getElementType(0);
  6078. // If OpTy is not a single value, it may be a struct/union that we
  6079. // can tile with integers.
  6080. if (!OpTy->isSingleValueType() && OpTy->isSized()) {
  6081. unsigned BitSize = DL.getTypeSizeInBits(OpTy);
  6082. switch (BitSize) {
  6083. default: break;
  6084. case 1:
  6085. case 8:
  6086. case 16:
  6087. case 32:
  6088. case 64:
  6089. case 128:
  6090. OpTy = IntegerType::get(Context, BitSize);
  6091. break;
  6092. }
  6093. }
  6094. return TLI.getValueType(DL, OpTy, true);
  6095. }
  6096. };
  6097. using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
  6098. } // end anonymous namespace
  6099. /// Make sure that the output operand \p OpInfo and its corresponding input
  6100. /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
  6101. /// out).
  6102. static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
  6103. SDISelAsmOperandInfo &MatchingOpInfo,
  6104. SelectionDAG &DAG) {
  6105. if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
  6106. return;
  6107. const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
  6108. const auto &TLI = DAG.getTargetLoweringInfo();
  6109. std::pair<unsigned, const TargetRegisterClass *> MatchRC =
  6110. TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
  6111. OpInfo.ConstraintVT);
  6112. std::pair<unsigned, const TargetRegisterClass *> InputRC =
  6113. TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
  6114. MatchingOpInfo.ConstraintVT);
  6115. if ((OpInfo.ConstraintVT.isInteger() !=
  6116. MatchingOpInfo.ConstraintVT.isInteger()) ||
  6117. (MatchRC.second != InputRC.second)) {
  6118. // FIXME: error out in a more elegant fashion
  6119. report_fatal_error("Unsupported asm: input constraint"
  6120. " with a matching output constraint of"
  6121. " incompatible type!");
  6122. }
  6123. MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
  6124. }
  6125. /// Get a direct memory input to behave well as an indirect operand.
  6126. /// This may introduce stores, hence the need for a \p Chain.
  6127. /// \return The (possibly updated) chain.
  6128. static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
  6129. SDISelAsmOperandInfo &OpInfo,
  6130. SelectionDAG &DAG) {
  6131. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6132. // If we don't have an indirect input, put it in the constpool if we can,
  6133. // otherwise spill it to a stack slot.
  6134. // TODO: This isn't quite right. We need to handle these according to
  6135. // the addressing mode that the constraint wants. Also, this may take
  6136. // an additional register for the computation and we don't want that
  6137. // either.
  6138. // If the operand is a float, integer, or vector constant, spill to a
  6139. // constant pool entry to get its address.
  6140. const Value *OpVal = OpInfo.CallOperandVal;
  6141. if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
  6142. isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
  6143. OpInfo.CallOperand = DAG.getConstantPool(
  6144. cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
  6145. return Chain;
  6146. }
  6147. // Otherwise, create a stack slot and emit a store to it before the asm.
  6148. Type *Ty = OpVal->getType();
  6149. auto &DL = DAG.getDataLayout();
  6150. uint64_t TySize = DL.getTypeAllocSize(Ty);
  6151. unsigned Align = DL.getPrefTypeAlignment(Ty);
  6152. MachineFunction &MF = DAG.getMachineFunction();
  6153. int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
  6154. SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
  6155. Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot,
  6156. MachinePointerInfo::getFixedStack(MF, SSFI));
  6157. OpInfo.CallOperand = StackSlot;
  6158. return Chain;
  6159. }
  6160. /// GetRegistersForValue - Assign registers (virtual or physical) for the
  6161. /// specified operand. We prefer to assign virtual registers, to allow the
  6162. /// register allocator to handle the assignment process. However, if the asm
  6163. /// uses features that we can't model on machineinstrs, we have SDISel do the
  6164. /// allocation. This produces generally horrible, but correct, code.
  6165. ///
  6166. /// OpInfo describes the operand.
  6167. static void GetRegistersForValue(SelectionDAG &DAG, const TargetLowering &TLI,
  6168. const SDLoc &DL,
  6169. SDISelAsmOperandInfo &OpInfo) {
  6170. LLVMContext &Context = *DAG.getContext();
  6171. MachineFunction &MF = DAG.getMachineFunction();
  6172. SmallVector<unsigned, 4> Regs;
  6173. const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
  6174. // If this is a constraint for a single physreg, or a constraint for a
  6175. // register class, find it.
  6176. std::pair<unsigned, const TargetRegisterClass *> PhysReg =
  6177. TLI.getRegForInlineAsmConstraint(&TRI, OpInfo.ConstraintCode,
  6178. OpInfo.ConstraintVT);
  6179. unsigned NumRegs = 1;
  6180. if (OpInfo.ConstraintVT != MVT::Other) {
  6181. // If this is a FP input in an integer register (or visa versa) insert a bit
  6182. // cast of the input value. More generally, handle any case where the input
  6183. // value disagrees with the register class we plan to stick this in.
  6184. if (OpInfo.Type == InlineAsm::isInput && PhysReg.second &&
  6185. !TRI.isTypeLegalForClass(*PhysReg.second, OpInfo.ConstraintVT)) {
  6186. // Try to convert to the first EVT that the reg class contains. If the
  6187. // types are identical size, use a bitcast to convert (e.g. two differing
  6188. // vector types).
  6189. MVT RegVT = *TRI.legalclasstypes_begin(*PhysReg.second);
  6190. if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
  6191. OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
  6192. RegVT, OpInfo.CallOperand);
  6193. OpInfo.ConstraintVT = RegVT;
  6194. } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
  6195. // If the input is a FP value and we want it in FP registers, do a
  6196. // bitcast to the corresponding integer type. This turns an f64 value
  6197. // into i64, which can be passed with two i32 values on a 32-bit
  6198. // machine.
  6199. RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
  6200. OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
  6201. RegVT, OpInfo.CallOperand);
  6202. OpInfo.ConstraintVT = RegVT;
  6203. }
  6204. }
  6205. NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
  6206. }
  6207. MVT RegVT;
  6208. EVT ValueVT = OpInfo.ConstraintVT;
  6209. // If this is a constraint for a specific physical register, like {r17},
  6210. // assign it now.
  6211. if (unsigned AssignedReg = PhysReg.first) {
  6212. const TargetRegisterClass *RC = PhysReg.second;
  6213. if (OpInfo.ConstraintVT == MVT::Other)
  6214. ValueVT = *TRI.legalclasstypes_begin(*RC);
  6215. // Get the actual register value type. This is important, because the user
  6216. // may have asked for (e.g.) the AX register in i32 type. We need to
  6217. // remember that AX is actually i16 to get the right extension.
  6218. RegVT = *TRI.legalclasstypes_begin(*RC);
  6219. // This is a explicit reference to a physical register.
  6220. Regs.push_back(AssignedReg);
  6221. // If this is an expanded reference, add the rest of the regs to Regs.
  6222. if (NumRegs != 1) {
  6223. TargetRegisterClass::iterator I = RC->begin();
  6224. for (; *I != AssignedReg; ++I)
  6225. assert(I != RC->end() && "Didn't find reg!");
  6226. // Already added the first reg.
  6227. --NumRegs; ++I;
  6228. for (; NumRegs; --NumRegs, ++I) {
  6229. assert(I != RC->end() && "Ran out of registers to allocate!");
  6230. Regs.push_back(*I);
  6231. }
  6232. }
  6233. OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
  6234. return;
  6235. }
  6236. // Otherwise, if this was a reference to an LLVM register class, create vregs
  6237. // for this reference.
  6238. if (const TargetRegisterClass *RC = PhysReg.second) {
  6239. RegVT = *TRI.legalclasstypes_begin(*RC);
  6240. if (OpInfo.ConstraintVT == MVT::Other)
  6241. ValueVT = RegVT;
  6242. // Create the appropriate number of virtual registers.
  6243. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  6244. for (; NumRegs; --NumRegs)
  6245. Regs.push_back(RegInfo.createVirtualRegister(RC));
  6246. OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
  6247. return;
  6248. }
  6249. // Otherwise, we couldn't allocate enough registers for this.
  6250. }
  6251. static unsigned
  6252. findMatchingInlineAsmOperand(unsigned OperandNo,
  6253. const std::vector<SDValue> &AsmNodeOperands) {
  6254. // Scan until we find the definition we already emitted of this operand.
  6255. unsigned CurOp = InlineAsm::Op_FirstOperand;
  6256. for (; OperandNo; --OperandNo) {
  6257. // Advance to the next operand.
  6258. unsigned OpFlag =
  6259. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  6260. assert((InlineAsm::isRegDefKind(OpFlag) ||
  6261. InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
  6262. InlineAsm::isMemKind(OpFlag)) &&
  6263. "Skipped past definitions?");
  6264. CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
  6265. }
  6266. return CurOp;
  6267. }
  6268. /// Fill \p Regs with \p NumRegs new virtual registers of type \p RegVT
  6269. /// \return true if it has succeeded, false otherwise
  6270. static bool createVirtualRegs(SmallVector<unsigned, 4> &Regs, unsigned NumRegs,
  6271. MVT RegVT, SelectionDAG &DAG) {
  6272. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6273. MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
  6274. for (unsigned i = 0, e = NumRegs; i != e; ++i) {
  6275. if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT))
  6276. Regs.push_back(RegInfo.createVirtualRegister(RC));
  6277. else
  6278. return false;
  6279. }
  6280. return true;
  6281. }
  6282. namespace {
  6283. class ExtraFlags {
  6284. unsigned Flags = 0;
  6285. public:
  6286. explicit ExtraFlags(ImmutableCallSite CS) {
  6287. const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  6288. if (IA->hasSideEffects())
  6289. Flags |= InlineAsm::Extra_HasSideEffects;
  6290. if (IA->isAlignStack())
  6291. Flags |= InlineAsm::Extra_IsAlignStack;
  6292. if (CS.isConvergent())
  6293. Flags |= InlineAsm::Extra_IsConvergent;
  6294. Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
  6295. }
  6296. void update(const TargetLowering::AsmOperandInfo &OpInfo) {
  6297. // Ideally, we would only check against memory constraints. However, the
  6298. // meaning of an Other constraint can be target-specific and we can't easily
  6299. // reason about it. Therefore, be conservative and set MayLoad/MayStore
  6300. // for Other constraints as well.
  6301. if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
  6302. OpInfo.ConstraintType == TargetLowering::C_Other) {
  6303. if (OpInfo.Type == InlineAsm::isInput)
  6304. Flags |= InlineAsm::Extra_MayLoad;
  6305. else if (OpInfo.Type == InlineAsm::isOutput)
  6306. Flags |= InlineAsm::Extra_MayStore;
  6307. else if (OpInfo.Type == InlineAsm::isClobber)
  6308. Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
  6309. }
  6310. }
  6311. unsigned get() const { return Flags; }
  6312. };
  6313. } // end anonymous namespace
  6314. /// visitInlineAsm - Handle a call to an InlineAsm object.
  6315. void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
  6316. const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  6317. /// ConstraintOperands - Information about all of the constraints.
  6318. SDISelAsmOperandInfoVector ConstraintOperands;
  6319. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6320. TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
  6321. DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
  6322. bool hasMemory = false;
  6323. // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
  6324. ExtraFlags ExtraInfo(CS);
  6325. unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
  6326. unsigned ResNo = 0; // ResNo - The result number of the next output.
  6327. for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
  6328. ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
  6329. SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
  6330. MVT OpVT = MVT::Other;
  6331. // Compute the value type for each operand.
  6332. if (OpInfo.Type == InlineAsm::isInput ||
  6333. (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
  6334. OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
  6335. // Process the call argument. BasicBlocks are labels, currently appearing
  6336. // only in asm's.
  6337. if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
  6338. OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
  6339. } else {
  6340. OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
  6341. }
  6342. OpVT =
  6343. OpInfo
  6344. .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
  6345. .getSimpleVT();
  6346. }
  6347. if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
  6348. // The return value of the call is this value. As such, there is no
  6349. // corresponding argument.
  6350. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  6351. if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
  6352. OpVT = TLI.getSimpleValueType(DAG.getDataLayout(),
  6353. STy->getElementType(ResNo));
  6354. } else {
  6355. assert(ResNo == 0 && "Asm only has one result!");
  6356. OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
  6357. }
  6358. ++ResNo;
  6359. }
  6360. OpInfo.ConstraintVT = OpVT;
  6361. if (!hasMemory)
  6362. hasMemory = OpInfo.hasMemory(TLI);
  6363. // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
  6364. // FIXME: Could we compute this on OpInfo rather than TargetConstraints[i]?
  6365. auto TargetConstraint = TargetConstraints[i];
  6366. // Compute the constraint code and ConstraintType to use.
  6367. TLI.ComputeConstraintToUse(TargetConstraint, SDValue());
  6368. ExtraInfo.update(TargetConstraint);
  6369. }
  6370. SDValue Chain, Flag;
  6371. // We won't need to flush pending loads if this asm doesn't touch
  6372. // memory and is nonvolatile.
  6373. if (hasMemory || IA->hasSideEffects())
  6374. Chain = getRoot();
  6375. else
  6376. Chain = DAG.getRoot();
  6377. // Second pass over the constraints: compute which constraint option to use
  6378. // and assign registers to constraints that want a specific physreg.
  6379. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  6380. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  6381. // If this is an output operand with a matching input operand, look up the
  6382. // matching input. If their types mismatch, e.g. one is an integer, the
  6383. // other is floating point, or their sizes are different, flag it as an
  6384. // error.
  6385. if (OpInfo.hasMatchingInput()) {
  6386. SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
  6387. patchMatchingInput(OpInfo, Input, DAG);
  6388. }
  6389. // Compute the constraint code and ConstraintType to use.
  6390. TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
  6391. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  6392. OpInfo.Type == InlineAsm::isClobber)
  6393. continue;
  6394. // If this is a memory input, and if the operand is not indirect, do what we
  6395. // need to to provide an address for the memory input.
  6396. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  6397. !OpInfo.isIndirect) {
  6398. assert((OpInfo.isMultipleAlternative ||
  6399. (OpInfo.Type == InlineAsm::isInput)) &&
  6400. "Can only indirectify direct input operands!");
  6401. // Memory operands really want the address of the value.
  6402. Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
  6403. // There is no longer a Value* corresponding to this operand.
  6404. OpInfo.CallOperandVal = nullptr;
  6405. // It is now an indirect operand.
  6406. OpInfo.isIndirect = true;
  6407. }
  6408. // If this constraint is for a specific register, allocate it before
  6409. // anything else.
  6410. if (OpInfo.ConstraintType == TargetLowering::C_Register)
  6411. GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
  6412. }
  6413. // Third pass - Loop over all of the operands, assigning virtual or physregs
  6414. // to register class operands.
  6415. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  6416. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  6417. // C_Register operands have already been allocated, Other/Memory don't need
  6418. // to be.
  6419. if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
  6420. GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
  6421. }
  6422. // AsmNodeOperands - The operands for the ISD::INLINEASM node.
  6423. std::vector<SDValue> AsmNodeOperands;
  6424. AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
  6425. AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
  6426. IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
  6427. // If we have a !srcloc metadata node associated with it, we want to attach
  6428. // this to the ultimately generated inline asm machineinstr. To do this, we
  6429. // pass in the third operand as this (potentially null) inline asm MDNode.
  6430. const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
  6431. AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
  6432. // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
  6433. // bits as operand 3.
  6434. AsmNodeOperands.push_back(DAG.getTargetConstant(
  6435. ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  6436. // Loop over all of the inputs, copying the operand values into the
  6437. // appropriate registers and processing the output regs.
  6438. RegsForValue RetValRegs;
  6439. // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
  6440. std::vector<std::pair<RegsForValue, Value *>> IndirectStoresToEmit;
  6441. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  6442. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  6443. switch (OpInfo.Type) {
  6444. case InlineAsm::isOutput:
  6445. if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
  6446. OpInfo.ConstraintType != TargetLowering::C_Register) {
  6447. // Memory output, or 'other' output (e.g. 'X' constraint).
  6448. assert(OpInfo.isIndirect && "Memory output must be indirect operand");
  6449. unsigned ConstraintID =
  6450. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  6451. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  6452. "Failed to convert memory constraint code to constraint id.");
  6453. // Add information to the INLINEASM node to know about this output.
  6454. unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  6455. OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
  6456. AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
  6457. MVT::i32));
  6458. AsmNodeOperands.push_back(OpInfo.CallOperand);
  6459. break;
  6460. }
  6461. // Otherwise, this is a register or register class output.
  6462. // Copy the output from the appropriate register. Find a register that
  6463. // we can use.
  6464. if (OpInfo.AssignedRegs.Regs.empty()) {
  6465. emitInlineAsmError(
  6466. CS, "couldn't allocate output register for constraint '" +
  6467. Twine(OpInfo.ConstraintCode) + "'");
  6468. return;
  6469. }
  6470. // If this is an indirect operand, store through the pointer after the
  6471. // asm.
  6472. if (OpInfo.isIndirect) {
  6473. IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
  6474. OpInfo.CallOperandVal));
  6475. } else {
  6476. // This is the result value of the call.
  6477. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  6478. // Concatenate this output onto the outputs list.
  6479. RetValRegs.append(OpInfo.AssignedRegs);
  6480. }
  6481. // Add information to the INLINEASM node to know that this register is
  6482. // set.
  6483. OpInfo.AssignedRegs
  6484. .AddInlineAsmOperands(OpInfo.isEarlyClobber
  6485. ? InlineAsm::Kind_RegDefEarlyClobber
  6486. : InlineAsm::Kind_RegDef,
  6487. false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
  6488. break;
  6489. case InlineAsm::isInput: {
  6490. SDValue InOperandVal = OpInfo.CallOperand;
  6491. if (OpInfo.isMatchingInputConstraint()) {
  6492. // If this is required to match an output register we have already set,
  6493. // just use its register.
  6494. auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
  6495. AsmNodeOperands);
  6496. unsigned OpFlag =
  6497. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  6498. if (InlineAsm::isRegDefKind(OpFlag) ||
  6499. InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
  6500. // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
  6501. if (OpInfo.isIndirect) {
  6502. // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
  6503. emitInlineAsmError(CS, "inline asm not supported yet:"
  6504. " don't know how to handle tied "
  6505. "indirect register inputs");
  6506. return;
  6507. }
  6508. MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
  6509. SmallVector<unsigned, 4> Regs;
  6510. if (!createVirtualRegs(Regs,
  6511. InlineAsm::getNumOperandRegisters(OpFlag),
  6512. RegVT, DAG)) {
  6513. emitInlineAsmError(CS, "inline asm error: This value type register "
  6514. "class is not natively supported!");
  6515. return;
  6516. }
  6517. RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
  6518. SDLoc dl = getCurSDLoc();
  6519. // Use the produced MatchedRegs object to
  6520. MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
  6521. CS.getInstruction());
  6522. MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
  6523. true, OpInfo.getMatchedOperand(), dl,
  6524. DAG, AsmNodeOperands);
  6525. break;
  6526. }
  6527. assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
  6528. assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
  6529. "Unexpected number of operands");
  6530. // Add information to the INLINEASM node to know about this input.
  6531. // See InlineAsm.h isUseOperandTiedToDef.
  6532. OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
  6533. OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
  6534. OpInfo.getMatchedOperand());
  6535. AsmNodeOperands.push_back(DAG.getTargetConstant(
  6536. OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  6537. AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
  6538. break;
  6539. }
  6540. // Treat indirect 'X' constraint as memory.
  6541. if (OpInfo.ConstraintType == TargetLowering::C_Other &&
  6542. OpInfo.isIndirect)
  6543. OpInfo.ConstraintType = TargetLowering::C_Memory;
  6544. if (OpInfo.ConstraintType == TargetLowering::C_Other) {
  6545. std::vector<SDValue> Ops;
  6546. TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
  6547. Ops, DAG);
  6548. if (Ops.empty()) {
  6549. emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
  6550. Twine(OpInfo.ConstraintCode) + "'");
  6551. return;
  6552. }
  6553. // Add information to the INLINEASM node to know about this input.
  6554. unsigned ResOpType =
  6555. InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
  6556. AsmNodeOperands.push_back(DAG.getTargetConstant(
  6557. ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  6558. AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
  6559. break;
  6560. }
  6561. if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
  6562. assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
  6563. assert(InOperandVal.getValueType() ==
  6564. TLI.getPointerTy(DAG.getDataLayout()) &&
  6565. "Memory operands expect pointer values");
  6566. unsigned ConstraintID =
  6567. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  6568. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  6569. "Failed to convert memory constraint code to constraint id.");
  6570. // Add information to the INLINEASM node to know about this input.
  6571. unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  6572. ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
  6573. AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
  6574. getCurSDLoc(),
  6575. MVT::i32));
  6576. AsmNodeOperands.push_back(InOperandVal);
  6577. break;
  6578. }
  6579. assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
  6580. OpInfo.ConstraintType == TargetLowering::C_Register) &&
  6581. "Unknown constraint type!");
  6582. // TODO: Support this.
  6583. if (OpInfo.isIndirect) {
  6584. emitInlineAsmError(
  6585. CS, "Don't know how to handle indirect register inputs yet "
  6586. "for constraint '" +
  6587. Twine(OpInfo.ConstraintCode) + "'");
  6588. return;
  6589. }
  6590. // Copy the input into the appropriate registers.
  6591. if (OpInfo.AssignedRegs.Regs.empty()) {
  6592. emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
  6593. Twine(OpInfo.ConstraintCode) + "'");
  6594. return;
  6595. }
  6596. SDLoc dl = getCurSDLoc();
  6597. OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
  6598. Chain, &Flag, CS.getInstruction());
  6599. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
  6600. dl, DAG, AsmNodeOperands);
  6601. break;
  6602. }
  6603. case InlineAsm::isClobber:
  6604. // Add the clobbered value to the operand list, so that the register
  6605. // allocator is aware that the physreg got clobbered.
  6606. if (!OpInfo.AssignedRegs.Regs.empty())
  6607. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
  6608. false, 0, getCurSDLoc(), DAG,
  6609. AsmNodeOperands);
  6610. break;
  6611. }
  6612. }
  6613. // Finish up input operands. Set the input chain and add the flag last.
  6614. AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
  6615. if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
  6616. Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
  6617. DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
  6618. Flag = Chain.getValue(1);
  6619. // If this asm returns a register value, copy the result from that register
  6620. // and set it as the value of the call.
  6621. if (!RetValRegs.Regs.empty()) {
  6622. SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
  6623. Chain, &Flag, CS.getInstruction());
  6624. // FIXME: Why don't we do this for inline asms with MRVs?
  6625. if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
  6626. EVT ResultType = TLI.getValueType(DAG.getDataLayout(), CS.getType());
  6627. // If any of the results of the inline asm is a vector, it may have the
  6628. // wrong width/num elts. This can happen for register classes that can
  6629. // contain multiple different value types. The preg or vreg allocated may
  6630. // not have the same VT as was expected. Convert it to the right type
  6631. // with bit_convert.
  6632. if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
  6633. Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
  6634. ResultType, Val);
  6635. } else if (ResultType != Val.getValueType() &&
  6636. ResultType.isInteger() && Val.getValueType().isInteger()) {
  6637. // If a result value was tied to an input value, the computed result may
  6638. // have a wider width than the expected result. Extract the relevant
  6639. // portion.
  6640. Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
  6641. }
  6642. assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
  6643. }
  6644. setValue(CS.getInstruction(), Val);
  6645. // Don't need to use this as a chain in this case.
  6646. if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
  6647. return;
  6648. }
  6649. std::vector<std::pair<SDValue, const Value *>> StoresToEmit;
  6650. // Process indirect outputs, first output all of the flagged copies out of
  6651. // physregs.
  6652. for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
  6653. RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
  6654. const Value *Ptr = IndirectStoresToEmit[i].second;
  6655. SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
  6656. Chain, &Flag, IA);
  6657. StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
  6658. }
  6659. // Emit the non-flagged stores from the physregs.
  6660. SmallVector<SDValue, 8> OutChains;
  6661. for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
  6662. SDValue Val = DAG.getStore(Chain, getCurSDLoc(), StoresToEmit[i].first,
  6663. getValue(StoresToEmit[i].second),
  6664. MachinePointerInfo(StoresToEmit[i].second));
  6665. OutChains.push_back(Val);
  6666. }
  6667. if (!OutChains.empty())
  6668. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
  6669. DAG.setRoot(Chain);
  6670. }
  6671. void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
  6672. const Twine &Message) {
  6673. LLVMContext &Ctx = *DAG.getContext();
  6674. Ctx.emitError(CS.getInstruction(), Message);
  6675. // Make sure we leave the DAG in a valid state
  6676. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6677. auto VT = TLI.getValueType(DAG.getDataLayout(), CS.getType());
  6678. setValue(CS.getInstruction(), DAG.getUNDEF(VT));
  6679. }
  6680. void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
  6681. DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
  6682. MVT::Other, getRoot(),
  6683. getValue(I.getArgOperand(0)),
  6684. DAG.getSrcValue(I.getArgOperand(0))));
  6685. }
  6686. void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
  6687. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6688. const DataLayout &DL = DAG.getDataLayout();
  6689. SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
  6690. getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
  6691. DAG.getSrcValue(I.getOperand(0)),
  6692. DL.getABITypeAlignment(I.getType()));
  6693. setValue(&I, V);
  6694. DAG.setRoot(V.getValue(1));
  6695. }
  6696. void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
  6697. DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
  6698. MVT::Other, getRoot(),
  6699. getValue(I.getArgOperand(0)),
  6700. DAG.getSrcValue(I.getArgOperand(0))));
  6701. }
  6702. void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
  6703. DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
  6704. MVT::Other, getRoot(),
  6705. getValue(I.getArgOperand(0)),
  6706. getValue(I.getArgOperand(1)),
  6707. DAG.getSrcValue(I.getArgOperand(0)),
  6708. DAG.getSrcValue(I.getArgOperand(1))));
  6709. }
  6710. SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
  6711. const Instruction &I,
  6712. SDValue Op) {
  6713. const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
  6714. if (!Range)
  6715. return Op;
  6716. ConstantRange CR = getConstantRangeFromMetadata(*Range);
  6717. if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet())
  6718. return Op;
  6719. APInt Lo = CR.getUnsignedMin();
  6720. if (!Lo.isMinValue())
  6721. return Op;
  6722. APInt Hi = CR.getUnsignedMax();
  6723. unsigned Bits = Hi.getActiveBits();
  6724. EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
  6725. SDLoc SL = getCurSDLoc();
  6726. SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
  6727. DAG.getValueType(SmallVT));
  6728. unsigned NumVals = Op.getNode()->getNumValues();
  6729. if (NumVals == 1)
  6730. return ZExt;
  6731. SmallVector<SDValue, 4> Ops;
  6732. Ops.push_back(ZExt);
  6733. for (unsigned I = 1; I != NumVals; ++I)
  6734. Ops.push_back(Op.getValue(I));
  6735. return DAG.getMergeValues(Ops, SL);
  6736. }
  6737. /// \brief Populate a CallLowerinInfo (into \p CLI) based on the properties of
  6738. /// the call being lowered.
  6739. ///
  6740. /// This is a helper for lowering intrinsics that follow a target calling
  6741. /// convention or require stack pointer adjustment. Only a subset of the
  6742. /// intrinsic's operands need to participate in the calling convention.
  6743. void SelectionDAGBuilder::populateCallLoweringInfo(
  6744. TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS,
  6745. unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
  6746. bool IsPatchPoint) {
  6747. TargetLowering::ArgListTy Args;
  6748. Args.reserve(NumArgs);
  6749. // Populate the argument list.
  6750. // Attributes for args start at offset 1, after the return attribute.
  6751. for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
  6752. ArgI != ArgE; ++ArgI) {
  6753. const Value *V = CS->getOperand(ArgI);
  6754. assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
  6755. TargetLowering::ArgListEntry Entry;
  6756. Entry.Node = getValue(V);
  6757. Entry.Ty = V->getType();
  6758. Entry.setAttributes(&CS, ArgIdx);
  6759. Args.push_back(Entry);
  6760. }
  6761. CLI.setDebugLoc(getCurSDLoc())
  6762. .setChain(getRoot())
  6763. .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args))
  6764. .setDiscardResult(CS->use_empty())
  6765. .setIsPatchPoint(IsPatchPoint);
  6766. }
  6767. /// \brief Add a stack map intrinsic call's live variable operands to a stackmap
  6768. /// or patchpoint target node's operand list.
  6769. ///
  6770. /// Constants are converted to TargetConstants purely as an optimization to
  6771. /// avoid constant materialization and register allocation.
  6772. ///
  6773. /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
  6774. /// generate addess computation nodes, and so ExpandISelPseudo can convert the
  6775. /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
  6776. /// address materialization and register allocation, but may also be required
  6777. /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
  6778. /// alloca in the entry block, then the runtime may assume that the alloca's
  6779. /// StackMap location can be read immediately after compilation and that the
  6780. /// location is valid at any point during execution (this is similar to the
  6781. /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
  6782. /// only available in a register, then the runtime would need to trap when
  6783. /// execution reaches the StackMap in order to read the alloca's location.
  6784. static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
  6785. const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
  6786. SelectionDAGBuilder &Builder) {
  6787. for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
  6788. SDValue OpVal = Builder.getValue(CS.getArgument(i));
  6789. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
  6790. Ops.push_back(
  6791. Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
  6792. Ops.push_back(
  6793. Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
  6794. } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
  6795. const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
  6796. Ops.push_back(Builder.DAG.getTargetFrameIndex(
  6797. FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
  6798. } else
  6799. Ops.push_back(OpVal);
  6800. }
  6801. }
  6802. /// \brief Lower llvm.experimental.stackmap directly to its target opcode.
  6803. void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
  6804. // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
  6805. // [live variables...])
  6806. assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
  6807. SDValue Chain, InFlag, Callee, NullPtr;
  6808. SmallVector<SDValue, 32> Ops;
  6809. SDLoc DL = getCurSDLoc();
  6810. Callee = getValue(CI.getCalledValue());
  6811. NullPtr = DAG.getIntPtrConstant(0, DL, true);
  6812. // The stackmap intrinsic only records the live variables (the arguemnts
  6813. // passed to it) and emits NOPS (if requested). Unlike the patchpoint
  6814. // intrinsic, this won't be lowered to a function call. This means we don't
  6815. // have to worry about calling conventions and target specific lowering code.
  6816. // Instead we perform the call lowering right here.
  6817. //
  6818. // chain, flag = CALLSEQ_START(chain, 0, 0)
  6819. // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
  6820. // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
  6821. //
  6822. Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
  6823. InFlag = Chain.getValue(1);
  6824. // Add the <id> and <numBytes> constants.
  6825. SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
  6826. Ops.push_back(DAG.getTargetConstant(
  6827. cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
  6828. SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
  6829. Ops.push_back(DAG.getTargetConstant(
  6830. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
  6831. MVT::i32));
  6832. // Push live variables for the stack map.
  6833. addStackMapLiveVars(&CI, 2, DL, Ops, *this);
  6834. // We are not pushing any register mask info here on the operands list,
  6835. // because the stackmap doesn't clobber anything.
  6836. // Push the chain and the glue flag.
  6837. Ops.push_back(Chain);
  6838. Ops.push_back(InFlag);
  6839. // Create the STACKMAP node.
  6840. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  6841. SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
  6842. Chain = SDValue(SM, 0);
  6843. InFlag = Chain.getValue(1);
  6844. Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
  6845. // Stackmaps don't generate values, so nothing goes into the NodeMap.
  6846. // Set the root to the target-lowered call chain.
  6847. DAG.setRoot(Chain);
  6848. // Inform the Frame Information that we have a stackmap in this function.
  6849. FuncInfo.MF->getFrameInfo().setHasStackMap();
  6850. }
  6851. /// \brief Lower llvm.experimental.patchpoint directly to its target opcode.
  6852. void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
  6853. const BasicBlock *EHPadBB) {
  6854. // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
  6855. // i32 <numBytes>,
  6856. // i8* <target>,
  6857. // i32 <numArgs>,
  6858. // [Args...],
  6859. // [live variables...])
  6860. CallingConv::ID CC = CS.getCallingConv();
  6861. bool IsAnyRegCC = CC == CallingConv::AnyReg;
  6862. bool HasDef = !CS->getType()->isVoidTy();
  6863. SDLoc dl = getCurSDLoc();
  6864. SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
  6865. // Handle immediate and symbolic callees.
  6866. if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
  6867. Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
  6868. /*isTarget=*/true);
  6869. else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
  6870. Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
  6871. SDLoc(SymbolicCallee),
  6872. SymbolicCallee->getValueType(0));
  6873. // Get the real number of arguments participating in the call <numArgs>
  6874. SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
  6875. unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
  6876. // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
  6877. // Intrinsics include all meta-operands up to but not including CC.
  6878. unsigned NumMetaOpers = PatchPointOpers::CCPos;
  6879. assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
  6880. "Not enough arguments provided to the patchpoint intrinsic");
  6881. // For AnyRegCC the arguments are lowered later on manually.
  6882. unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
  6883. Type *ReturnTy =
  6884. IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
  6885. TargetLowering::CallLoweringInfo CLI(DAG);
  6886. populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy,
  6887. true);
  6888. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  6889. SDNode *CallEnd = Result.second.getNode();
  6890. if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
  6891. CallEnd = CallEnd->getOperand(0).getNode();
  6892. /// Get a call instruction from the call sequence chain.
  6893. /// Tail calls are not allowed.
  6894. assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
  6895. "Expected a callseq node.");
  6896. SDNode *Call = CallEnd->getOperand(0).getNode();
  6897. bool HasGlue = Call->getGluedNode();
  6898. // Replace the target specific call node with the patchable intrinsic.
  6899. SmallVector<SDValue, 8> Ops;
  6900. // Add the <id> and <numBytes> constants.
  6901. SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
  6902. Ops.push_back(DAG.getTargetConstant(
  6903. cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
  6904. SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
  6905. Ops.push_back(DAG.getTargetConstant(
  6906. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
  6907. MVT::i32));
  6908. // Add the callee.
  6909. Ops.push_back(Callee);
  6910. // Adjust <numArgs> to account for any arguments that have been passed on the
  6911. // stack instead.
  6912. // Call Node: Chain, Target, {Args}, RegMask, [Glue]
  6913. unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
  6914. NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
  6915. Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
  6916. // Add the calling convention
  6917. Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
  6918. // Add the arguments we omitted previously. The register allocator should
  6919. // place these in any free register.
  6920. if (IsAnyRegCC)
  6921. for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
  6922. Ops.push_back(getValue(CS.getArgument(i)));
  6923. // Push the arguments from the call instruction up to the register mask.
  6924. SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
  6925. Ops.append(Call->op_begin() + 2, e);
  6926. // Push live variables for the stack map.
  6927. addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
  6928. // Push the register mask info.
  6929. if (HasGlue)
  6930. Ops.push_back(*(Call->op_end()-2));
  6931. else
  6932. Ops.push_back(*(Call->op_end()-1));
  6933. // Push the chain (this is originally the first operand of the call, but
  6934. // becomes now the last or second to last operand).
  6935. Ops.push_back(*(Call->op_begin()));
  6936. // Push the glue flag (last operand).
  6937. if (HasGlue)
  6938. Ops.push_back(*(Call->op_end()-1));
  6939. SDVTList NodeTys;
  6940. if (IsAnyRegCC && HasDef) {
  6941. // Create the return types based on the intrinsic definition
  6942. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6943. SmallVector<EVT, 3> ValueVTs;
  6944. ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
  6945. assert(ValueVTs.size() == 1 && "Expected only one return value type.");
  6946. // There is always a chain and a glue type at the end
  6947. ValueVTs.push_back(MVT::Other);
  6948. ValueVTs.push_back(MVT::Glue);
  6949. NodeTys = DAG.getVTList(ValueVTs);
  6950. } else
  6951. NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  6952. // Replace the target specific call node with a PATCHPOINT node.
  6953. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
  6954. dl, NodeTys, Ops);
  6955. // Update the NodeMap.
  6956. if (HasDef) {
  6957. if (IsAnyRegCC)
  6958. setValue(CS.getInstruction(), SDValue(MN, 0));
  6959. else
  6960. setValue(CS.getInstruction(), Result.first);
  6961. }
  6962. // Fixup the consumers of the intrinsic. The chain and glue may be used in the
  6963. // call sequence. Furthermore the location of the chain and glue can change
  6964. // when the AnyReg calling convention is used and the intrinsic returns a
  6965. // value.
  6966. if (IsAnyRegCC && HasDef) {
  6967. SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
  6968. SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
  6969. DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
  6970. } else
  6971. DAG.ReplaceAllUsesWith(Call, MN);
  6972. DAG.DeleteNode(Call);
  6973. // Inform the Frame Information that we have a patchpoint in this function.
  6974. FuncInfo.MF->getFrameInfo().setHasPatchPoint();
  6975. }
  6976. void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
  6977. unsigned Intrinsic) {
  6978. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6979. SDValue Op1 = getValue(I.getArgOperand(0));
  6980. SDValue Op2;
  6981. if (I.getNumArgOperands() > 1)
  6982. Op2 = getValue(I.getArgOperand(1));
  6983. SDLoc dl = getCurSDLoc();
  6984. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  6985. SDValue Res;
  6986. FastMathFlags FMF;
  6987. if (isa<FPMathOperator>(I))
  6988. FMF = I.getFastMathFlags();
  6989. SDNodeFlags SDFlags;
  6990. SDFlags.setNoNaNs(FMF.noNaNs());
  6991. switch (Intrinsic) {
  6992. case Intrinsic::experimental_vector_reduce_fadd:
  6993. if (FMF.isFast())
  6994. Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2);
  6995. else
  6996. Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
  6997. break;
  6998. case Intrinsic::experimental_vector_reduce_fmul:
  6999. if (FMF.isFast())
  7000. Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2);
  7001. else
  7002. Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
  7003. break;
  7004. case Intrinsic::experimental_vector_reduce_add:
  7005. Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
  7006. break;
  7007. case Intrinsic::experimental_vector_reduce_mul:
  7008. Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
  7009. break;
  7010. case Intrinsic::experimental_vector_reduce_and:
  7011. Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
  7012. break;
  7013. case Intrinsic::experimental_vector_reduce_or:
  7014. Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
  7015. break;
  7016. case Intrinsic::experimental_vector_reduce_xor:
  7017. Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
  7018. break;
  7019. case Intrinsic::experimental_vector_reduce_smax:
  7020. Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
  7021. break;
  7022. case Intrinsic::experimental_vector_reduce_smin:
  7023. Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
  7024. break;
  7025. case Intrinsic::experimental_vector_reduce_umax:
  7026. Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
  7027. break;
  7028. case Intrinsic::experimental_vector_reduce_umin:
  7029. Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
  7030. break;
  7031. case Intrinsic::experimental_vector_reduce_fmax:
  7032. Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
  7033. break;
  7034. case Intrinsic::experimental_vector_reduce_fmin:
  7035. Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
  7036. break;
  7037. default:
  7038. llvm_unreachable("Unhandled vector reduce intrinsic");
  7039. }
  7040. setValue(&I, Res);
  7041. }
  7042. /// Returns an AttributeList representing the attributes applied to the return
  7043. /// value of the given call.
  7044. static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
  7045. SmallVector<Attribute::AttrKind, 2> Attrs;
  7046. if (CLI.RetSExt)
  7047. Attrs.push_back(Attribute::SExt);
  7048. if (CLI.RetZExt)
  7049. Attrs.push_back(Attribute::ZExt);
  7050. if (CLI.IsInReg)
  7051. Attrs.push_back(Attribute::InReg);
  7052. return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
  7053. Attrs);
  7054. }
  7055. /// TargetLowering::LowerCallTo - This is the default LowerCallTo
  7056. /// implementation, which just calls LowerCall.
  7057. /// FIXME: When all targets are
  7058. /// migrated to using LowerCall, this hook should be integrated into SDISel.
  7059. std::pair<SDValue, SDValue>
  7060. TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
  7061. // Handle the incoming return values from the call.
  7062. CLI.Ins.clear();
  7063. Type *OrigRetTy = CLI.RetTy;
  7064. SmallVector<EVT, 4> RetTys;
  7065. SmallVector<uint64_t, 4> Offsets;
  7066. auto &DL = CLI.DAG.getDataLayout();
  7067. ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
  7068. if (CLI.IsPostTypeLegalization) {
  7069. // If we are lowering a libcall after legalization, split the return type.
  7070. SmallVector<EVT, 4> OldRetTys = std::move(RetTys);
  7071. SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets);
  7072. for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
  7073. EVT RetVT = OldRetTys[i];
  7074. uint64_t Offset = OldOffsets[i];
  7075. MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
  7076. unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
  7077. unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
  7078. RetTys.append(NumRegs, RegisterVT);
  7079. for (unsigned j = 0; j != NumRegs; ++j)
  7080. Offsets.push_back(Offset + j * RegisterVTByteSZ);
  7081. }
  7082. }
  7083. SmallVector<ISD::OutputArg, 4> Outs;
  7084. GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
  7085. bool CanLowerReturn =
  7086. this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
  7087. CLI.IsVarArg, Outs, CLI.RetTy->getContext());
  7088. SDValue DemoteStackSlot;
  7089. int DemoteStackIdx = -100;
  7090. if (!CanLowerReturn) {
  7091. // FIXME: equivalent assert?
  7092. // assert(!CS.hasInAllocaArgument() &&
  7093. // "sret demotion is incompatible with inalloca");
  7094. uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
  7095. unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
  7096. MachineFunction &MF = CLI.DAG.getMachineFunction();
  7097. DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
  7098. Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy);
  7099. DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
  7100. ArgListEntry Entry;
  7101. Entry.Node = DemoteStackSlot;
  7102. Entry.Ty = StackSlotPtrType;
  7103. Entry.IsSExt = false;
  7104. Entry.IsZExt = false;
  7105. Entry.IsInReg = false;
  7106. Entry.IsSRet = true;
  7107. Entry.IsNest = false;
  7108. Entry.IsByVal = false;
  7109. Entry.IsReturned = false;
  7110. Entry.IsSwiftSelf = false;
  7111. Entry.IsSwiftError = false;
  7112. Entry.Alignment = Align;
  7113. CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
  7114. CLI.NumFixedArgs += 1;
  7115. CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
  7116. // sret demotion isn't compatible with tail-calls, since the sret argument
  7117. // points into the callers stack frame.
  7118. CLI.IsTailCall = false;
  7119. } else {
  7120. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  7121. EVT VT = RetTys[I];
  7122. MVT RegisterVT =
  7123. getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
  7124. unsigned NumRegs =
  7125. getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
  7126. for (unsigned i = 0; i != NumRegs; ++i) {
  7127. ISD::InputArg MyFlags;
  7128. MyFlags.VT = RegisterVT;
  7129. MyFlags.ArgVT = VT;
  7130. MyFlags.Used = CLI.IsReturnValueUsed;
  7131. if (CLI.RetSExt)
  7132. MyFlags.Flags.setSExt();
  7133. if (CLI.RetZExt)
  7134. MyFlags.Flags.setZExt();
  7135. if (CLI.IsInReg)
  7136. MyFlags.Flags.setInReg();
  7137. CLI.Ins.push_back(MyFlags);
  7138. }
  7139. }
  7140. }
  7141. // We push in swifterror return as the last element of CLI.Ins.
  7142. ArgListTy &Args = CLI.getArgs();
  7143. if (supportSwiftError()) {
  7144. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  7145. if (Args[i].IsSwiftError) {
  7146. ISD::InputArg MyFlags;
  7147. MyFlags.VT = getPointerTy(DL);
  7148. MyFlags.ArgVT = EVT(getPointerTy(DL));
  7149. MyFlags.Flags.setSwiftError();
  7150. CLI.Ins.push_back(MyFlags);
  7151. }
  7152. }
  7153. }
  7154. // Handle all of the outgoing arguments.
  7155. CLI.Outs.clear();
  7156. CLI.OutVals.clear();
  7157. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  7158. SmallVector<EVT, 4> ValueVTs;
  7159. ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
  7160. // FIXME: Split arguments if CLI.IsPostTypeLegalization
  7161. Type *FinalType = Args[i].Ty;
  7162. if (Args[i].IsByVal)
  7163. FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
  7164. bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
  7165. FinalType, CLI.CallConv, CLI.IsVarArg);
  7166. for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
  7167. ++Value) {
  7168. EVT VT = ValueVTs[Value];
  7169. Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
  7170. SDValue Op = SDValue(Args[i].Node.getNode(),
  7171. Args[i].Node.getResNo() + Value);
  7172. ISD::ArgFlagsTy Flags;
  7173. // Certain targets (such as MIPS), may have a different ABI alignment
  7174. // for a type depending on the context. Give the target a chance to
  7175. // specify the alignment it wants.
  7176. unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
  7177. if (Args[i].IsZExt)
  7178. Flags.setZExt();
  7179. if (Args[i].IsSExt)
  7180. Flags.setSExt();
  7181. if (Args[i].IsInReg) {
  7182. // If we are using vectorcall calling convention, a structure that is
  7183. // passed InReg - is surely an HVA
  7184. if (CLI.CallConv == CallingConv::X86_VectorCall &&
  7185. isa<StructType>(FinalType)) {
  7186. // The first value of a structure is marked
  7187. if (0 == Value)
  7188. Flags.setHvaStart();
  7189. Flags.setHva();
  7190. }
  7191. // Set InReg Flag
  7192. Flags.setInReg();
  7193. }
  7194. if (Args[i].IsSRet)
  7195. Flags.setSRet();
  7196. if (Args[i].IsSwiftSelf)
  7197. Flags.setSwiftSelf();
  7198. if (Args[i].IsSwiftError)
  7199. Flags.setSwiftError();
  7200. if (Args[i].IsByVal)
  7201. Flags.setByVal();
  7202. if (Args[i].IsInAlloca) {
  7203. Flags.setInAlloca();
  7204. // Set the byval flag for CCAssignFn callbacks that don't know about
  7205. // inalloca. This way we can know how many bytes we should've allocated
  7206. // and how many bytes a callee cleanup function will pop. If we port
  7207. // inalloca to more targets, we'll have to add custom inalloca handling
  7208. // in the various CC lowering callbacks.
  7209. Flags.setByVal();
  7210. }
  7211. if (Args[i].IsByVal || Args[i].IsInAlloca) {
  7212. PointerType *Ty = cast<PointerType>(Args[i].Ty);
  7213. Type *ElementTy = Ty->getElementType();
  7214. Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
  7215. // For ByVal, alignment should come from FE. BE will guess if this
  7216. // info is not there but there are cases it cannot get right.
  7217. unsigned FrameAlign;
  7218. if (Args[i].Alignment)
  7219. FrameAlign = Args[i].Alignment;
  7220. else
  7221. FrameAlign = getByValTypeAlignment(ElementTy, DL);
  7222. Flags.setByValAlign(FrameAlign);
  7223. }
  7224. if (Args[i].IsNest)
  7225. Flags.setNest();
  7226. if (NeedsRegBlock)
  7227. Flags.setInConsecutiveRegs();
  7228. Flags.setOrigAlign(OriginalAlignment);
  7229. MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
  7230. unsigned NumParts =
  7231. getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
  7232. SmallVector<SDValue, 4> Parts(NumParts);
  7233. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  7234. if (Args[i].IsSExt)
  7235. ExtendKind = ISD::SIGN_EXTEND;
  7236. else if (Args[i].IsZExt)
  7237. ExtendKind = ISD::ZERO_EXTEND;
  7238. // Conservatively only handle 'returned' on non-vectors for now
  7239. if (Args[i].IsReturned && !Op.getValueType().isVector()) {
  7240. assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
  7241. "unexpected use of 'returned'");
  7242. // Before passing 'returned' to the target lowering code, ensure that
  7243. // either the register MVT and the actual EVT are the same size or that
  7244. // the return value and argument are extended in the same way; in these
  7245. // cases it's safe to pass the argument register value unchanged as the
  7246. // return register value (although it's at the target's option whether
  7247. // to do so)
  7248. // TODO: allow code generation to take advantage of partially preserved
  7249. // registers rather than clobbering the entire register when the
  7250. // parameter extension method is not compatible with the return
  7251. // extension method
  7252. if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
  7253. (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
  7254. CLI.RetZExt == Args[i].IsZExt))
  7255. Flags.setReturned();
  7256. }
  7257. getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
  7258. CLI.CS.getInstruction(), ExtendKind, true);
  7259. for (unsigned j = 0; j != NumParts; ++j) {
  7260. // if it isn't first piece, alignment must be 1
  7261. ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
  7262. i < CLI.NumFixedArgs,
  7263. i, j*Parts[j].getValueType().getStoreSize());
  7264. if (NumParts > 1 && j == 0)
  7265. MyFlags.Flags.setSplit();
  7266. else if (j != 0) {
  7267. MyFlags.Flags.setOrigAlign(1);
  7268. if (j == NumParts - 1)
  7269. MyFlags.Flags.setSplitEnd();
  7270. }
  7271. CLI.Outs.push_back(MyFlags);
  7272. CLI.OutVals.push_back(Parts[j]);
  7273. }
  7274. if (NeedsRegBlock && Value == NumValues - 1)
  7275. CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
  7276. }
  7277. }
  7278. SmallVector<SDValue, 4> InVals;
  7279. CLI.Chain = LowerCall(CLI, InVals);
  7280. // Update CLI.InVals to use outside of this function.
  7281. CLI.InVals = InVals;
  7282. // Verify that the target's LowerCall behaved as expected.
  7283. assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
  7284. "LowerCall didn't return a valid chain!");
  7285. assert((!CLI.IsTailCall || InVals.empty()) &&
  7286. "LowerCall emitted a return value for a tail call!");
  7287. assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
  7288. "LowerCall didn't emit the correct number of values!");
  7289. // For a tail call, the return value is merely live-out and there aren't
  7290. // any nodes in the DAG representing it. Return a special value to
  7291. // indicate that a tail call has been emitted and no more Instructions
  7292. // should be processed in the current block.
  7293. if (CLI.IsTailCall) {
  7294. CLI.DAG.setRoot(CLI.Chain);
  7295. return std::make_pair(SDValue(), SDValue());
  7296. }
  7297. #ifndef NDEBUG
  7298. for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
  7299. assert(InVals[i].getNode() && "LowerCall emitted a null value!");
  7300. assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
  7301. "LowerCall emitted a value with the wrong type!");
  7302. }
  7303. #endif
  7304. SmallVector<SDValue, 4> ReturnValues;
  7305. if (!CanLowerReturn) {
  7306. // The instruction result is the result of loading from the
  7307. // hidden sret parameter.
  7308. SmallVector<EVT, 1> PVTs;
  7309. Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
  7310. ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
  7311. assert(PVTs.size() == 1 && "Pointers should fit in one register");
  7312. EVT PtrVT = PVTs[0];
  7313. unsigned NumValues = RetTys.size();
  7314. ReturnValues.resize(NumValues);
  7315. SmallVector<SDValue, 4> Chains(NumValues);
  7316. // An aggregate return value cannot wrap around the address space, so
  7317. // offsets to its parts don't wrap either.
  7318. SDNodeFlags Flags;
  7319. Flags.setNoUnsignedWrap(true);
  7320. for (unsigned i = 0; i < NumValues; ++i) {
  7321. SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
  7322. CLI.DAG.getConstant(Offsets[i], CLI.DL,
  7323. PtrVT), Flags);
  7324. SDValue L = CLI.DAG.getLoad(
  7325. RetTys[i], CLI.DL, CLI.Chain, Add,
  7326. MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
  7327. DemoteStackIdx, Offsets[i]),
  7328. /* Alignment = */ 1);
  7329. ReturnValues[i] = L;
  7330. Chains[i] = L.getValue(1);
  7331. }
  7332. CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
  7333. } else {
  7334. // Collect the legal value parts into potentially illegal values
  7335. // that correspond to the original function's return values.
  7336. Optional<ISD::NodeType> AssertOp;
  7337. if (CLI.RetSExt)
  7338. AssertOp = ISD::AssertSext;
  7339. else if (CLI.RetZExt)
  7340. AssertOp = ISD::AssertZext;
  7341. unsigned CurReg = 0;
  7342. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  7343. EVT VT = RetTys[I];
  7344. MVT RegisterVT =
  7345. getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
  7346. unsigned NumRegs =
  7347. getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
  7348. ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
  7349. NumRegs, RegisterVT, VT, nullptr,
  7350. AssertOp, true));
  7351. CurReg += NumRegs;
  7352. }
  7353. // For a function returning void, there is no return value. We can't create
  7354. // such a node, so we just return a null return value in that case. In
  7355. // that case, nothing will actually look at the value.
  7356. if (ReturnValues.empty())
  7357. return std::make_pair(SDValue(), CLI.Chain);
  7358. }
  7359. SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
  7360. CLI.DAG.getVTList(RetTys), ReturnValues);
  7361. return std::make_pair(Res, CLI.Chain);
  7362. }
  7363. void TargetLowering::LowerOperationWrapper(SDNode *N,
  7364. SmallVectorImpl<SDValue> &Results,
  7365. SelectionDAG &DAG) const {
  7366. if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
  7367. Results.push_back(Res);
  7368. }
  7369. SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
  7370. llvm_unreachable("LowerOperation not implemented for this target!");
  7371. }
  7372. void
  7373. SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
  7374. SDValue Op = getNonRegisterValue(V);
  7375. assert((Op.getOpcode() != ISD::CopyFromReg ||
  7376. cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
  7377. "Copy from a reg to the same reg!");
  7378. assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
  7379. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7380. // If this is an InlineAsm we have to match the registers required, not the
  7381. // notional registers required by the type.
  7382. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
  7383. V->getType(), isABIRegCopy(V));
  7384. SDValue Chain = DAG.getEntryNode();
  7385. ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
  7386. FuncInfo.PreferredExtendType.end())
  7387. ? ISD::ANY_EXTEND
  7388. : FuncInfo.PreferredExtendType[V];
  7389. RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
  7390. PendingExports.push_back(Chain);
  7391. }
  7392. #include "llvm/CodeGen/SelectionDAGISel.h"
  7393. /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
  7394. /// entry block, return true. This includes arguments used by switches, since
  7395. /// the switch may expand into multiple basic blocks.
  7396. static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
  7397. // With FastISel active, we may be splitting blocks, so force creation
  7398. // of virtual registers for all non-dead arguments.
  7399. if (FastISel)
  7400. return A->use_empty();
  7401. const BasicBlock &Entry = A->getParent()->front();
  7402. for (const User *U : A->users())
  7403. if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
  7404. return false; // Use not in entry block.
  7405. return true;
  7406. }
  7407. using ArgCopyElisionMapTy =
  7408. DenseMap<const Argument *,
  7409. std::pair<const AllocaInst *, const StoreInst *>>;
  7410. /// Scan the entry block of the function in FuncInfo for arguments that look
  7411. /// like copies into a local alloca. Record any copied arguments in
  7412. /// ArgCopyElisionCandidates.
  7413. static void
  7414. findArgumentCopyElisionCandidates(const DataLayout &DL,
  7415. FunctionLoweringInfo *FuncInfo,
  7416. ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
  7417. // Record the state of every static alloca used in the entry block. Argument
  7418. // allocas are all used in the entry block, so we need approximately as many
  7419. // entries as we have arguments.
  7420. enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
  7421. SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
  7422. unsigned NumArgs = FuncInfo->Fn->arg_size();
  7423. StaticAllocas.reserve(NumArgs * 2);
  7424. auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
  7425. if (!V)
  7426. return nullptr;
  7427. V = V->stripPointerCasts();
  7428. const auto *AI = dyn_cast<AllocaInst>(V);
  7429. if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
  7430. return nullptr;
  7431. auto Iter = StaticAllocas.insert({AI, Unknown});
  7432. return &Iter.first->second;
  7433. };
  7434. // Look for stores of arguments to static allocas. Look through bitcasts and
  7435. // GEPs to handle type coercions, as long as the alloca is fully initialized
  7436. // by the store. Any non-store use of an alloca escapes it and any subsequent
  7437. // unanalyzed store might write it.
  7438. // FIXME: Handle structs initialized with multiple stores.
  7439. for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
  7440. // Look for stores, and handle non-store uses conservatively.
  7441. const auto *SI = dyn_cast<StoreInst>(&I);
  7442. if (!SI) {
  7443. // We will look through cast uses, so ignore them completely.
  7444. if (I.isCast())
  7445. continue;
  7446. // Ignore debug info intrinsics, they don't escape or store to allocas.
  7447. if (isa<DbgInfoIntrinsic>(I))
  7448. continue;
  7449. // This is an unknown instruction. Assume it escapes or writes to all
  7450. // static alloca operands.
  7451. for (const Use &U : I.operands()) {
  7452. if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
  7453. *Info = StaticAllocaInfo::Clobbered;
  7454. }
  7455. continue;
  7456. }
  7457. // If the stored value is a static alloca, mark it as escaped.
  7458. if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
  7459. *Info = StaticAllocaInfo::Clobbered;
  7460. // Check if the destination is a static alloca.
  7461. const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
  7462. StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
  7463. if (!Info)
  7464. continue;
  7465. const AllocaInst *AI = cast<AllocaInst>(Dst);
  7466. // Skip allocas that have been initialized or clobbered.
  7467. if (*Info != StaticAllocaInfo::Unknown)
  7468. continue;
  7469. // Check if the stored value is an argument, and that this store fully
  7470. // initializes the alloca. Don't elide copies from the same argument twice.
  7471. const Value *Val = SI->getValueOperand()->stripPointerCasts();
  7472. const auto *Arg = dyn_cast<Argument>(Val);
  7473. if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
  7474. Arg->getType()->isEmptyTy() ||
  7475. DL.getTypeStoreSize(Arg->getType()) !=
  7476. DL.getTypeAllocSize(AI->getAllocatedType()) ||
  7477. ArgCopyElisionCandidates.count(Arg)) {
  7478. *Info = StaticAllocaInfo::Clobbered;
  7479. continue;
  7480. }
  7481. DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI << '\n');
  7482. // Mark this alloca and store for argument copy elision.
  7483. *Info = StaticAllocaInfo::Elidable;
  7484. ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
  7485. // Stop scanning if we've seen all arguments. This will happen early in -O0
  7486. // builds, which is useful, because -O0 builds have large entry blocks and
  7487. // many allocas.
  7488. if (ArgCopyElisionCandidates.size() == NumArgs)
  7489. break;
  7490. }
  7491. }
  7492. /// Try to elide argument copies from memory into a local alloca. Succeeds if
  7493. /// ArgVal is a load from a suitable fixed stack object.
  7494. static void tryToElideArgumentCopy(
  7495. FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
  7496. DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
  7497. SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
  7498. ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
  7499. SDValue ArgVal, bool &ArgHasUses) {
  7500. // Check if this is a load from a fixed stack object.
  7501. auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
  7502. if (!LNode)
  7503. return;
  7504. auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
  7505. if (!FINode)
  7506. return;
  7507. // Check that the fixed stack object is the right size and alignment.
  7508. // Look at the alignment that the user wrote on the alloca instead of looking
  7509. // at the stack object.
  7510. auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
  7511. assert(ArgCopyIter != ArgCopyElisionCandidates.end());
  7512. const AllocaInst *AI = ArgCopyIter->second.first;
  7513. int FixedIndex = FINode->getIndex();
  7514. int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
  7515. int OldIndex = AllocaIndex;
  7516. MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
  7517. if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
  7518. DEBUG(dbgs() << " argument copy elision failed due to bad fixed stack "
  7519. "object size\n");
  7520. return;
  7521. }
  7522. unsigned RequiredAlignment = AI->getAlignment();
  7523. if (!RequiredAlignment) {
  7524. RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
  7525. AI->getAllocatedType());
  7526. }
  7527. if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
  7528. DEBUG(dbgs() << " argument copy elision failed: alignment of alloca "
  7529. "greater than stack argument alignment ("
  7530. << RequiredAlignment << " vs "
  7531. << MFI.getObjectAlignment(FixedIndex) << ")\n");
  7532. return;
  7533. }
  7534. // Perform the elision. Delete the old stack object and replace its only use
  7535. // in the variable info map. Mark the stack object as mutable.
  7536. DEBUG({
  7537. dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
  7538. << " Replacing frame index " << OldIndex << " with " << FixedIndex
  7539. << '\n';
  7540. });
  7541. MFI.RemoveStackObject(OldIndex);
  7542. MFI.setIsImmutableObjectIndex(FixedIndex, false);
  7543. AllocaIndex = FixedIndex;
  7544. ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
  7545. Chains.push_back(ArgVal.getValue(1));
  7546. // Avoid emitting code for the store implementing the copy.
  7547. const StoreInst *SI = ArgCopyIter->second.second;
  7548. ElidedArgCopyInstrs.insert(SI);
  7549. // Check for uses of the argument again so that we can avoid exporting ArgVal
  7550. // if it is't used by anything other than the store.
  7551. for (const Value *U : Arg.users()) {
  7552. if (U != SI) {
  7553. ArgHasUses = true;
  7554. break;
  7555. }
  7556. }
  7557. }
  7558. void SelectionDAGISel::LowerArguments(const Function &F) {
  7559. SelectionDAG &DAG = SDB->DAG;
  7560. SDLoc dl = SDB->getCurSDLoc();
  7561. const DataLayout &DL = DAG.getDataLayout();
  7562. SmallVector<ISD::InputArg, 16> Ins;
  7563. if (!FuncInfo->CanLowerReturn) {
  7564. // Put in an sret pointer parameter before all the other parameters.
  7565. SmallVector<EVT, 1> ValueVTs;
  7566. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  7567. F.getReturnType()->getPointerTo(
  7568. DAG.getDataLayout().getAllocaAddrSpace()),
  7569. ValueVTs);
  7570. // NOTE: Assuming that a pointer will never break down to more than one VT
  7571. // or one register.
  7572. ISD::ArgFlagsTy Flags;
  7573. Flags.setSRet();
  7574. MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
  7575. ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
  7576. ISD::InputArg::NoArgIndex, 0);
  7577. Ins.push_back(RetArg);
  7578. }
  7579. // Look for stores of arguments to static allocas. Mark such arguments with a
  7580. // flag to ask the target to give us the memory location of that argument if
  7581. // available.
  7582. ArgCopyElisionMapTy ArgCopyElisionCandidates;
  7583. findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
  7584. // Set up the incoming argument description vector.
  7585. for (const Argument &Arg : F.args()) {
  7586. unsigned ArgNo = Arg.getArgNo();
  7587. SmallVector<EVT, 4> ValueVTs;
  7588. ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
  7589. bool isArgValueUsed = !Arg.use_empty();
  7590. unsigned PartBase = 0;
  7591. Type *FinalType = Arg.getType();
  7592. if (Arg.hasAttribute(Attribute::ByVal))
  7593. FinalType = cast<PointerType>(FinalType)->getElementType();
  7594. bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
  7595. FinalType, F.getCallingConv(), F.isVarArg());
  7596. for (unsigned Value = 0, NumValues = ValueVTs.size();
  7597. Value != NumValues; ++Value) {
  7598. EVT VT = ValueVTs[Value];
  7599. Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
  7600. ISD::ArgFlagsTy Flags;
  7601. // Certain targets (such as MIPS), may have a different ABI alignment
  7602. // for a type depending on the context. Give the target a chance to
  7603. // specify the alignment it wants.
  7604. unsigned OriginalAlignment =
  7605. TLI->getABIAlignmentForCallingConv(ArgTy, DL);
  7606. if (Arg.hasAttribute(Attribute::ZExt))
  7607. Flags.setZExt();
  7608. if (Arg.hasAttribute(Attribute::SExt))
  7609. Flags.setSExt();
  7610. if (Arg.hasAttribute(Attribute::InReg)) {
  7611. // If we are using vectorcall calling convention, a structure that is
  7612. // passed InReg - is surely an HVA
  7613. if (F.getCallingConv() == CallingConv::X86_VectorCall &&
  7614. isa<StructType>(Arg.getType())) {
  7615. // The first value of a structure is marked
  7616. if (0 == Value)
  7617. Flags.setHvaStart();
  7618. Flags.setHva();
  7619. }
  7620. // Set InReg Flag
  7621. Flags.setInReg();
  7622. }
  7623. if (Arg.hasAttribute(Attribute::StructRet))
  7624. Flags.setSRet();
  7625. if (Arg.hasAttribute(Attribute::SwiftSelf))
  7626. Flags.setSwiftSelf();
  7627. if (Arg.hasAttribute(Attribute::SwiftError))
  7628. Flags.setSwiftError();
  7629. if (Arg.hasAttribute(Attribute::ByVal))
  7630. Flags.setByVal();
  7631. if (Arg.hasAttribute(Attribute::InAlloca)) {
  7632. Flags.setInAlloca();
  7633. // Set the byval flag for CCAssignFn callbacks that don't know about
  7634. // inalloca. This way we can know how many bytes we should've allocated
  7635. // and how many bytes a callee cleanup function will pop. If we port
  7636. // inalloca to more targets, we'll have to add custom inalloca handling
  7637. // in the various CC lowering callbacks.
  7638. Flags.setByVal();
  7639. }
  7640. if (F.getCallingConv() == CallingConv::X86_INTR) {
  7641. // IA Interrupt passes frame (1st parameter) by value in the stack.
  7642. if (ArgNo == 0)
  7643. Flags.setByVal();
  7644. }
  7645. if (Flags.isByVal() || Flags.isInAlloca()) {
  7646. PointerType *Ty = cast<PointerType>(Arg.getType());
  7647. Type *ElementTy = Ty->getElementType();
  7648. Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
  7649. // For ByVal, alignment should be passed from FE. BE will guess if
  7650. // this info is not there but there are cases it cannot get right.
  7651. unsigned FrameAlign;
  7652. if (Arg.getParamAlignment())
  7653. FrameAlign = Arg.getParamAlignment();
  7654. else
  7655. FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
  7656. Flags.setByValAlign(FrameAlign);
  7657. }
  7658. if (Arg.hasAttribute(Attribute::Nest))
  7659. Flags.setNest();
  7660. if (NeedsRegBlock)
  7661. Flags.setInConsecutiveRegs();
  7662. Flags.setOrigAlign(OriginalAlignment);
  7663. if (ArgCopyElisionCandidates.count(&Arg))
  7664. Flags.setCopyElisionCandidate();
  7665. MVT RegisterVT =
  7666. TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), VT);
  7667. unsigned NumRegs =
  7668. TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), VT);
  7669. for (unsigned i = 0; i != NumRegs; ++i) {
  7670. ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
  7671. ArgNo, PartBase+i*RegisterVT.getStoreSize());
  7672. if (NumRegs > 1 && i == 0)
  7673. MyFlags.Flags.setSplit();
  7674. // if it isn't first piece, alignment must be 1
  7675. else if (i > 0) {
  7676. MyFlags.Flags.setOrigAlign(1);
  7677. if (i == NumRegs - 1)
  7678. MyFlags.Flags.setSplitEnd();
  7679. }
  7680. Ins.push_back(MyFlags);
  7681. }
  7682. if (NeedsRegBlock && Value == NumValues - 1)
  7683. Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
  7684. PartBase += VT.getStoreSize();
  7685. }
  7686. }
  7687. // Call the target to set up the argument values.
  7688. SmallVector<SDValue, 8> InVals;
  7689. SDValue NewRoot = TLI->LowerFormalArguments(
  7690. DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
  7691. // Verify that the target's LowerFormalArguments behaved as expected.
  7692. assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
  7693. "LowerFormalArguments didn't return a valid chain!");
  7694. assert(InVals.size() == Ins.size() &&
  7695. "LowerFormalArguments didn't emit the correct number of values!");
  7696. DEBUG({
  7697. for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
  7698. assert(InVals[i].getNode() &&
  7699. "LowerFormalArguments emitted a null value!");
  7700. assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
  7701. "LowerFormalArguments emitted a value with the wrong type!");
  7702. }
  7703. });
  7704. // Update the DAG with the new chain value resulting from argument lowering.
  7705. DAG.setRoot(NewRoot);
  7706. // Set up the argument values.
  7707. unsigned i = 0;
  7708. if (!FuncInfo->CanLowerReturn) {
  7709. // Create a virtual register for the sret pointer, and put in a copy
  7710. // from the sret argument into it.
  7711. SmallVector<EVT, 1> ValueVTs;
  7712. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  7713. F.getReturnType()->getPointerTo(
  7714. DAG.getDataLayout().getAllocaAddrSpace()),
  7715. ValueVTs);
  7716. MVT VT = ValueVTs[0].getSimpleVT();
  7717. MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
  7718. Optional<ISD::NodeType> AssertOp = None;
  7719. SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
  7720. RegVT, VT, nullptr, AssertOp);
  7721. MachineFunction& MF = SDB->DAG.getMachineFunction();
  7722. MachineRegisterInfo& RegInfo = MF.getRegInfo();
  7723. unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
  7724. FuncInfo->DemoteRegister = SRetReg;
  7725. NewRoot =
  7726. SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
  7727. DAG.setRoot(NewRoot);
  7728. // i indexes lowered arguments. Bump it past the hidden sret argument.
  7729. ++i;
  7730. }
  7731. SmallVector<SDValue, 4> Chains;
  7732. DenseMap<int, int> ArgCopyElisionFrameIndexMap;
  7733. for (const Argument &Arg : F.args()) {
  7734. SmallVector<SDValue, 4> ArgValues;
  7735. SmallVector<EVT, 4> ValueVTs;
  7736. ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
  7737. unsigned NumValues = ValueVTs.size();
  7738. if (NumValues == 0)
  7739. continue;
  7740. bool ArgHasUses = !Arg.use_empty();
  7741. // Elide the copying store if the target loaded this argument from a
  7742. // suitable fixed stack object.
  7743. if (Ins[i].Flags.isCopyElisionCandidate()) {
  7744. tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
  7745. ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
  7746. InVals[i], ArgHasUses);
  7747. }
  7748. // If this argument is unused then remember its value. It is used to generate
  7749. // debugging information.
  7750. bool isSwiftErrorArg =
  7751. TLI->supportSwiftError() &&
  7752. Arg.hasAttribute(Attribute::SwiftError);
  7753. if (!ArgHasUses && !isSwiftErrorArg) {
  7754. SDB->setUnusedArgValue(&Arg, InVals[i]);
  7755. // Also remember any frame index for use in FastISel.
  7756. if (FrameIndexSDNode *FI =
  7757. dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
  7758. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  7759. }
  7760. for (unsigned Val = 0; Val != NumValues; ++Val) {
  7761. EVT VT = ValueVTs[Val];
  7762. MVT PartVT =
  7763. TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), VT);
  7764. unsigned NumParts =
  7765. TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), VT);
  7766. // Even an apparant 'unused' swifterror argument needs to be returned. So
  7767. // we do generate a copy for it that can be used on return from the
  7768. // function.
  7769. if (ArgHasUses || isSwiftErrorArg) {
  7770. Optional<ISD::NodeType> AssertOp;
  7771. if (Arg.hasAttribute(Attribute::SExt))
  7772. AssertOp = ISD::AssertSext;
  7773. else if (Arg.hasAttribute(Attribute::ZExt))
  7774. AssertOp = ISD::AssertZext;
  7775. ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
  7776. PartVT, VT, nullptr, AssertOp,
  7777. true));
  7778. }
  7779. i += NumParts;
  7780. }
  7781. // We don't need to do anything else for unused arguments.
  7782. if (ArgValues.empty())
  7783. continue;
  7784. // Note down frame index.
  7785. if (FrameIndexSDNode *FI =
  7786. dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
  7787. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  7788. SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
  7789. SDB->getCurSDLoc());
  7790. SDB->setValue(&Arg, Res);
  7791. if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
  7792. // We want to associate the argument with the frame index, among
  7793. // involved operands, that correspond to the lowest address. The
  7794. // getCopyFromParts function, called earlier, is swapping the order of
  7795. // the operands to BUILD_PAIR depending on endianness. The result of
  7796. // that swapping is that the least significant bits of the argument will
  7797. // be in the first operand of the BUILD_PAIR node, and the most
  7798. // significant bits will be in the second operand.
  7799. unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
  7800. if (LoadSDNode *LNode =
  7801. dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
  7802. if (FrameIndexSDNode *FI =
  7803. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  7804. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  7805. }
  7806. // Update the SwiftErrorVRegDefMap.
  7807. if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
  7808. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  7809. if (TargetRegisterInfo::isVirtualRegister(Reg))
  7810. FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB,
  7811. FuncInfo->SwiftErrorArg, Reg);
  7812. }
  7813. // If this argument is live outside of the entry block, insert a copy from
  7814. // wherever we got it to the vreg that other BB's will reference it as.
  7815. if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
  7816. // If we can, though, try to skip creating an unnecessary vreg.
  7817. // FIXME: This isn't very clean... it would be nice to make this more
  7818. // general. It's also subtly incompatible with the hacks FastISel
  7819. // uses with vregs.
  7820. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  7821. if (TargetRegisterInfo::isVirtualRegister(Reg)) {
  7822. FuncInfo->ValueMap[&Arg] = Reg;
  7823. continue;
  7824. }
  7825. }
  7826. if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
  7827. FuncInfo->InitializeRegForValue(&Arg);
  7828. SDB->CopyToExportRegsIfNeeded(&Arg);
  7829. }
  7830. }
  7831. if (!Chains.empty()) {
  7832. Chains.push_back(NewRoot);
  7833. NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  7834. }
  7835. DAG.setRoot(NewRoot);
  7836. assert(i == InVals.size() && "Argument register count mismatch!");
  7837. // If any argument copy elisions occurred and we have debug info, update the
  7838. // stale frame indices used in the dbg.declare variable info table.
  7839. MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
  7840. if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
  7841. for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
  7842. auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
  7843. if (I != ArgCopyElisionFrameIndexMap.end())
  7844. VI.Slot = I->second;
  7845. }
  7846. }
  7847. // Finally, if the target has anything special to do, allow it to do so.
  7848. EmitFunctionEntryCode();
  7849. }
  7850. /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
  7851. /// ensure constants are generated when needed. Remember the virtual registers
  7852. /// that need to be added to the Machine PHI nodes as input. We cannot just
  7853. /// directly add them, because expansion might result in multiple MBB's for one
  7854. /// BB. As such, the start of the BB might correspond to a different MBB than
  7855. /// the end.
  7856. void
  7857. SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
  7858. const TerminatorInst *TI = LLVMBB->getTerminator();
  7859. SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
  7860. // Check PHI nodes in successors that expect a value to be available from this
  7861. // block.
  7862. for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
  7863. const BasicBlock *SuccBB = TI->getSuccessor(succ);
  7864. if (!isa<PHINode>(SuccBB->begin())) continue;
  7865. MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
  7866. // If this terminator has multiple identical successors (common for
  7867. // switches), only handle each succ once.
  7868. if (!SuccsHandled.insert(SuccMBB).second)
  7869. continue;
  7870. MachineBasicBlock::iterator MBBI = SuccMBB->begin();
  7871. // At this point we know that there is a 1-1 correspondence between LLVM PHI
  7872. // nodes and Machine PHI nodes, but the incoming operands have not been
  7873. // emitted yet.
  7874. for (const PHINode &PN : SuccBB->phis()) {
  7875. // Ignore dead phi's.
  7876. if (PN.use_empty())
  7877. continue;
  7878. // Skip empty types
  7879. if (PN.getType()->isEmptyTy())
  7880. continue;
  7881. unsigned Reg;
  7882. const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
  7883. if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
  7884. unsigned &RegOut = ConstantsOut[C];
  7885. if (RegOut == 0) {
  7886. RegOut = FuncInfo.CreateRegs(C->getType());
  7887. CopyValueToVirtualRegister(C, RegOut);
  7888. }
  7889. Reg = RegOut;
  7890. } else {
  7891. DenseMap<const Value *, unsigned>::iterator I =
  7892. FuncInfo.ValueMap.find(PHIOp);
  7893. if (I != FuncInfo.ValueMap.end())
  7894. Reg = I->second;
  7895. else {
  7896. assert(isa<AllocaInst>(PHIOp) &&
  7897. FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
  7898. "Didn't codegen value into a register!??");
  7899. Reg = FuncInfo.CreateRegs(PHIOp->getType());
  7900. CopyValueToVirtualRegister(PHIOp, Reg);
  7901. }
  7902. }
  7903. // Remember that this register needs to added to the machine PHI node as
  7904. // the input for this MBB.
  7905. SmallVector<EVT, 4> ValueVTs;
  7906. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7907. ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
  7908. for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
  7909. EVT VT = ValueVTs[vti];
  7910. unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
  7911. for (unsigned i = 0, e = NumRegisters; i != e; ++i)
  7912. FuncInfo.PHINodesToUpdate.push_back(
  7913. std::make_pair(&*MBBI++, Reg + i));
  7914. Reg += NumRegisters;
  7915. }
  7916. }
  7917. }
  7918. ConstantsOut.clear();
  7919. }
  7920. /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
  7921. /// is 0.
  7922. MachineBasicBlock *
  7923. SelectionDAGBuilder::StackProtectorDescriptor::
  7924. AddSuccessorMBB(const BasicBlock *BB,
  7925. MachineBasicBlock *ParentMBB,
  7926. bool IsLikely,
  7927. MachineBasicBlock *SuccMBB) {
  7928. // If SuccBB has not been created yet, create it.
  7929. if (!SuccMBB) {
  7930. MachineFunction *MF = ParentMBB->getParent();
  7931. MachineFunction::iterator BBI(ParentMBB);
  7932. SuccMBB = MF->CreateMachineBasicBlock(BB);
  7933. MF->insert(++BBI, SuccMBB);
  7934. }
  7935. // Add it as a successor of ParentMBB.
  7936. ParentMBB->addSuccessor(
  7937. SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
  7938. return SuccMBB;
  7939. }
  7940. MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
  7941. MachineFunction::iterator I(MBB);
  7942. if (++I == FuncInfo.MF->end())
  7943. return nullptr;
  7944. return &*I;
  7945. }
  7946. /// During lowering new call nodes can be created (such as memset, etc.).
  7947. /// Those will become new roots of the current DAG, but complications arise
  7948. /// when they are tail calls. In such cases, the call lowering will update
  7949. /// the root, but the builder still needs to know that a tail call has been
  7950. /// lowered in order to avoid generating an additional return.
  7951. void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
  7952. // If the node is null, we do have a tail call.
  7953. if (MaybeTC.getNode() != nullptr)
  7954. DAG.setRoot(MaybeTC);
  7955. else
  7956. HasTailCall = true;
  7957. }
  7958. uint64_t
  7959. SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters,
  7960. unsigned First, unsigned Last) const {
  7961. assert(Last >= First);
  7962. const APInt &LowCase = Clusters[First].Low->getValue();
  7963. const APInt &HighCase = Clusters[Last].High->getValue();
  7964. assert(LowCase.getBitWidth() == HighCase.getBitWidth());
  7965. // FIXME: A range of consecutive cases has 100% density, but only requires one
  7966. // comparison to lower. We should discriminate against such consecutive ranges
  7967. // in jump tables.
  7968. return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1;
  7969. }
  7970. uint64_t SelectionDAGBuilder::getJumpTableNumCases(
  7971. const SmallVectorImpl<unsigned> &TotalCases, unsigned First,
  7972. unsigned Last) const {
  7973. assert(Last >= First);
  7974. assert(TotalCases[Last] >= TotalCases[First]);
  7975. uint64_t NumCases =
  7976. TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
  7977. return NumCases;
  7978. }
  7979. bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters,
  7980. unsigned First, unsigned Last,
  7981. const SwitchInst *SI,
  7982. MachineBasicBlock *DefaultMBB,
  7983. CaseCluster &JTCluster) {
  7984. assert(First <= Last);
  7985. auto Prob = BranchProbability::getZero();
  7986. unsigned NumCmps = 0;
  7987. std::vector<MachineBasicBlock*> Table;
  7988. DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
  7989. // Initialize probabilities in JTProbs.
  7990. for (unsigned I = First; I <= Last; ++I)
  7991. JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
  7992. for (unsigned I = First; I <= Last; ++I) {
  7993. assert(Clusters[I].Kind == CC_Range);
  7994. Prob += Clusters[I].Prob;
  7995. const APInt &Low = Clusters[I].Low->getValue();
  7996. const APInt &High = Clusters[I].High->getValue();
  7997. NumCmps += (Low == High) ? 1 : 2;
  7998. if (I != First) {
  7999. // Fill the gap between this and the previous cluster.
  8000. const APInt &PreviousHigh = Clusters[I - 1].High->getValue();
  8001. assert(PreviousHigh.slt(Low));
  8002. uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
  8003. for (uint64_t J = 0; J < Gap; J++)
  8004. Table.push_back(DefaultMBB);
  8005. }
  8006. uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
  8007. for (uint64_t J = 0; J < ClusterSize; ++J)
  8008. Table.push_back(Clusters[I].MBB);
  8009. JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
  8010. }
  8011. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8012. unsigned NumDests = JTProbs.size();
  8013. if (TLI.isSuitableForBitTests(
  8014. NumDests, NumCmps, Clusters[First].Low->getValue(),
  8015. Clusters[Last].High->getValue(), DAG.getDataLayout())) {
  8016. // Clusters[First..Last] should be lowered as bit tests instead.
  8017. return false;
  8018. }
  8019. // Create the MBB that will load from and jump through the table.
  8020. // Note: We create it here, but it's not inserted into the function yet.
  8021. MachineFunction *CurMF = FuncInfo.MF;
  8022. MachineBasicBlock *JumpTableMBB =
  8023. CurMF->CreateMachineBasicBlock(SI->getParent());
  8024. // Add successors. Note: use table order for determinism.
  8025. SmallPtrSet<MachineBasicBlock *, 8> Done;
  8026. for (MachineBasicBlock *Succ : Table) {
  8027. if (Done.count(Succ))
  8028. continue;
  8029. addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
  8030. Done.insert(Succ);
  8031. }
  8032. JumpTableMBB->normalizeSuccProbs();
  8033. unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
  8034. ->createJumpTableIndex(Table);
  8035. // Set up the jump table info.
  8036. JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
  8037. JumpTableHeader JTH(Clusters[First].Low->getValue(),
  8038. Clusters[Last].High->getValue(), SI->getCondition(),
  8039. nullptr, false);
  8040. JTCases.emplace_back(std::move(JTH), std::move(JT));
  8041. JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
  8042. JTCases.size() - 1, Prob);
  8043. return true;
  8044. }
  8045. void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
  8046. const SwitchInst *SI,
  8047. MachineBasicBlock *DefaultMBB) {
  8048. #ifndef NDEBUG
  8049. // Clusters must be non-empty, sorted, and only contain Range clusters.
  8050. assert(!Clusters.empty());
  8051. for (CaseCluster &C : Clusters)
  8052. assert(C.Kind == CC_Range);
  8053. for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
  8054. assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
  8055. #endif
  8056. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8057. if (!TLI.areJTsAllowed(SI->getParent()->getParent()))
  8058. return;
  8059. const int64_t N = Clusters.size();
  8060. const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries();
  8061. const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2;
  8062. if (N < 2 || N < MinJumpTableEntries)
  8063. return;
  8064. // TotalCases[i]: Total nbr of cases in Clusters[0..i].
  8065. SmallVector<unsigned, 8> TotalCases(N);
  8066. for (unsigned i = 0; i < N; ++i) {
  8067. const APInt &Hi = Clusters[i].High->getValue();
  8068. const APInt &Lo = Clusters[i].Low->getValue();
  8069. TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
  8070. if (i != 0)
  8071. TotalCases[i] += TotalCases[i - 1];
  8072. }
  8073. // Cheap case: the whole range may be suitable for jump table.
  8074. uint64_t Range = getJumpTableRange(Clusters,0, N - 1);
  8075. uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1);
  8076. assert(NumCases < UINT64_MAX / 100);
  8077. assert(Range >= NumCases);
  8078. if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
  8079. CaseCluster JTCluster;
  8080. if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
  8081. Clusters[0] = JTCluster;
  8082. Clusters.resize(1);
  8083. return;
  8084. }
  8085. }
  8086. // The algorithm below is not suitable for -O0.
  8087. if (TM.getOptLevel() == CodeGenOpt::None)
  8088. return;
  8089. // Split Clusters into minimum number of dense partitions. The algorithm uses
  8090. // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
  8091. // for the Case Statement'" (1994), but builds the MinPartitions array in
  8092. // reverse order to make it easier to reconstruct the partitions in ascending
  8093. // order. In the choice between two optimal partitionings, it picks the one
  8094. // which yields more jump tables.
  8095. // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
  8096. SmallVector<unsigned, 8> MinPartitions(N);
  8097. // LastElement[i] is the last element of the partition starting at i.
  8098. SmallVector<unsigned, 8> LastElement(N);
  8099. // PartitionsScore[i] is used to break ties when choosing between two
  8100. // partitionings resulting in the same number of partitions.
  8101. SmallVector<unsigned, 8> PartitionsScore(N);
  8102. // For PartitionsScore, a small number of comparisons is considered as good as
  8103. // a jump table and a single comparison is considered better than a jump
  8104. // table.
  8105. enum PartitionScores : unsigned {
  8106. NoTable = 0,
  8107. Table = 1,
  8108. FewCases = 1,
  8109. SingleCase = 2
  8110. };
  8111. // Base case: There is only one way to partition Clusters[N-1].
  8112. MinPartitions[N - 1] = 1;
  8113. LastElement[N - 1] = N - 1;
  8114. PartitionsScore[N - 1] = PartitionScores::SingleCase;
  8115. // Note: loop indexes are signed to avoid underflow.
  8116. for (int64_t i = N - 2; i >= 0; i--) {
  8117. // Find optimal partitioning of Clusters[i..N-1].
  8118. // Baseline: Put Clusters[i] into a partition on its own.
  8119. MinPartitions[i] = MinPartitions[i + 1] + 1;
  8120. LastElement[i] = i;
  8121. PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase;
  8122. // Search for a solution that results in fewer partitions.
  8123. for (int64_t j = N - 1; j > i; j--) {
  8124. // Try building a partition from Clusters[i..j].
  8125. uint64_t Range = getJumpTableRange(Clusters, i, j);
  8126. uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j);
  8127. assert(NumCases < UINT64_MAX / 100);
  8128. assert(Range >= NumCases);
  8129. if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
  8130. unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
  8131. unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1];
  8132. int64_t NumEntries = j - i + 1;
  8133. if (NumEntries == 1)
  8134. Score += PartitionScores::SingleCase;
  8135. else if (NumEntries <= SmallNumberOfEntries)
  8136. Score += PartitionScores::FewCases;
  8137. else if (NumEntries >= MinJumpTableEntries)
  8138. Score += PartitionScores::Table;
  8139. // If this leads to fewer partitions, or to the same number of
  8140. // partitions with better score, it is a better partitioning.
  8141. if (NumPartitions < MinPartitions[i] ||
  8142. (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) {
  8143. MinPartitions[i] = NumPartitions;
  8144. LastElement[i] = j;
  8145. PartitionsScore[i] = Score;
  8146. }
  8147. }
  8148. }
  8149. }
  8150. // Iterate over the partitions, replacing some with jump tables in-place.
  8151. unsigned DstIndex = 0;
  8152. for (unsigned First = 0, Last; First < N; First = Last + 1) {
  8153. Last = LastElement[First];
  8154. assert(Last >= First);
  8155. assert(DstIndex <= First);
  8156. unsigned NumClusters = Last - First + 1;
  8157. CaseCluster JTCluster;
  8158. if (NumClusters >= MinJumpTableEntries &&
  8159. buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
  8160. Clusters[DstIndex++] = JTCluster;
  8161. } else {
  8162. for (unsigned I = First; I <= Last; ++I)
  8163. std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
  8164. }
  8165. }
  8166. Clusters.resize(DstIndex);
  8167. }
  8168. bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
  8169. unsigned First, unsigned Last,
  8170. const SwitchInst *SI,
  8171. CaseCluster &BTCluster) {
  8172. assert(First <= Last);
  8173. if (First == Last)
  8174. return false;
  8175. BitVector Dests(FuncInfo.MF->getNumBlockIDs());
  8176. unsigned NumCmps = 0;
  8177. for (int64_t I = First; I <= Last; ++I) {
  8178. assert(Clusters[I].Kind == CC_Range);
  8179. Dests.set(Clusters[I].MBB->getNumber());
  8180. NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
  8181. }
  8182. unsigned NumDests = Dests.count();
  8183. APInt Low = Clusters[First].Low->getValue();
  8184. APInt High = Clusters[Last].High->getValue();
  8185. assert(Low.slt(High));
  8186. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8187. const DataLayout &DL = DAG.getDataLayout();
  8188. if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL))
  8189. return false;
  8190. APInt LowBound;
  8191. APInt CmpRange;
  8192. const int BitWidth = TLI.getPointerTy(DL).getSizeInBits();
  8193. assert(TLI.rangeFitsInWord(Low, High, DL) &&
  8194. "Case range must fit in bit mask!");
  8195. // Check if the clusters cover a contiguous range such that no value in the
  8196. // range will jump to the default statement.
  8197. bool ContiguousRange = true;
  8198. for (int64_t I = First + 1; I <= Last; ++I) {
  8199. if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
  8200. ContiguousRange = false;
  8201. break;
  8202. }
  8203. }
  8204. if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
  8205. // Optimize the case where all the case values fit in a word without having
  8206. // to subtract minValue. In this case, we can optimize away the subtraction.
  8207. LowBound = APInt::getNullValue(Low.getBitWidth());
  8208. CmpRange = High;
  8209. ContiguousRange = false;
  8210. } else {
  8211. LowBound = Low;
  8212. CmpRange = High - Low;
  8213. }
  8214. CaseBitsVector CBV;
  8215. auto TotalProb = BranchProbability::getZero();
  8216. for (unsigned i = First; i <= Last; ++i) {
  8217. // Find the CaseBits for this destination.
  8218. unsigned j;
  8219. for (j = 0; j < CBV.size(); ++j)
  8220. if (CBV[j].BB == Clusters[i].MBB)
  8221. break;
  8222. if (j == CBV.size())
  8223. CBV.push_back(
  8224. CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
  8225. CaseBits *CB = &CBV[j];
  8226. // Update Mask, Bits and ExtraProb.
  8227. uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
  8228. uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
  8229. assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
  8230. CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
  8231. CB->Bits += Hi - Lo + 1;
  8232. CB->ExtraProb += Clusters[i].Prob;
  8233. TotalProb += Clusters[i].Prob;
  8234. }
  8235. BitTestInfo BTI;
  8236. std::sort(CBV.begin(), CBV.end(), [](const CaseBits &a, const CaseBits &b) {
  8237. // Sort by probability first, number of bits second, bit mask third.
  8238. if (a.ExtraProb != b.ExtraProb)
  8239. return a.ExtraProb > b.ExtraProb;
  8240. if (a.Bits != b.Bits)
  8241. return a.Bits > b.Bits;
  8242. return a.Mask < b.Mask;
  8243. });
  8244. for (auto &CB : CBV) {
  8245. MachineBasicBlock *BitTestBB =
  8246. FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
  8247. BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
  8248. }
  8249. BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
  8250. SI->getCondition(), -1U, MVT::Other, false,
  8251. ContiguousRange, nullptr, nullptr, std::move(BTI),
  8252. TotalProb);
  8253. BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
  8254. BitTestCases.size() - 1, TotalProb);
  8255. return true;
  8256. }
  8257. void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
  8258. const SwitchInst *SI) {
  8259. // Partition Clusters into as few subsets as possible, where each subset has a
  8260. // range that fits in a machine word and has <= 3 unique destinations.
  8261. #ifndef NDEBUG
  8262. // Clusters must be sorted and contain Range or JumpTable clusters.
  8263. assert(!Clusters.empty());
  8264. assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
  8265. for (const CaseCluster &C : Clusters)
  8266. assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
  8267. for (unsigned i = 1; i < Clusters.size(); ++i)
  8268. assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
  8269. #endif
  8270. // The algorithm below is not suitable for -O0.
  8271. if (TM.getOptLevel() == CodeGenOpt::None)
  8272. return;
  8273. // If target does not have legal shift left, do not emit bit tests at all.
  8274. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8275. const DataLayout &DL = DAG.getDataLayout();
  8276. EVT PTy = TLI.getPointerTy(DL);
  8277. if (!TLI.isOperationLegal(ISD::SHL, PTy))
  8278. return;
  8279. int BitWidth = PTy.getSizeInBits();
  8280. const int64_t N = Clusters.size();
  8281. // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
  8282. SmallVector<unsigned, 8> MinPartitions(N);
  8283. // LastElement[i] is the last element of the partition starting at i.
  8284. SmallVector<unsigned, 8> LastElement(N);
  8285. // FIXME: This might not be the best algorithm for finding bit test clusters.
  8286. // Base case: There is only one way to partition Clusters[N-1].
  8287. MinPartitions[N - 1] = 1;
  8288. LastElement[N - 1] = N - 1;
  8289. // Note: loop indexes are signed to avoid underflow.
  8290. for (int64_t i = N - 2; i >= 0; --i) {
  8291. // Find optimal partitioning of Clusters[i..N-1].
  8292. // Baseline: Put Clusters[i] into a partition on its own.
  8293. MinPartitions[i] = MinPartitions[i + 1] + 1;
  8294. LastElement[i] = i;
  8295. // Search for a solution that results in fewer partitions.
  8296. // Note: the search is limited by BitWidth, reducing time complexity.
  8297. for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
  8298. // Try building a partition from Clusters[i..j].
  8299. // Check the range.
  8300. if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(),
  8301. Clusters[j].High->getValue(), DL))
  8302. continue;
  8303. // Check nbr of destinations and cluster types.
  8304. // FIXME: This works, but doesn't seem very efficient.
  8305. bool RangesOnly = true;
  8306. BitVector Dests(FuncInfo.MF->getNumBlockIDs());
  8307. for (int64_t k = i; k <= j; k++) {
  8308. if (Clusters[k].Kind != CC_Range) {
  8309. RangesOnly = false;
  8310. break;
  8311. }
  8312. Dests.set(Clusters[k].MBB->getNumber());
  8313. }
  8314. if (!RangesOnly || Dests.count() > 3)
  8315. break;
  8316. // Check if it's a better partition.
  8317. unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
  8318. if (NumPartitions < MinPartitions[i]) {
  8319. // Found a better partition.
  8320. MinPartitions[i] = NumPartitions;
  8321. LastElement[i] = j;
  8322. }
  8323. }
  8324. }
  8325. // Iterate over the partitions, replacing with bit-test clusters in-place.
  8326. unsigned DstIndex = 0;
  8327. for (unsigned First = 0, Last; First < N; First = Last + 1) {
  8328. Last = LastElement[First];
  8329. assert(First <= Last);
  8330. assert(DstIndex <= First);
  8331. CaseCluster BitTestCluster;
  8332. if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
  8333. Clusters[DstIndex++] = BitTestCluster;
  8334. } else {
  8335. size_t NumClusters = Last - First + 1;
  8336. std::memmove(&Clusters[DstIndex], &Clusters[First],
  8337. sizeof(Clusters[0]) * NumClusters);
  8338. DstIndex += NumClusters;
  8339. }
  8340. }
  8341. Clusters.resize(DstIndex);
  8342. }
  8343. void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
  8344. MachineBasicBlock *SwitchMBB,
  8345. MachineBasicBlock *DefaultMBB) {
  8346. MachineFunction *CurMF = FuncInfo.MF;
  8347. MachineBasicBlock *NextMBB = nullptr;
  8348. MachineFunction::iterator BBI(W.MBB);
  8349. if (++BBI != FuncInfo.MF->end())
  8350. NextMBB = &*BBI;
  8351. unsigned Size = W.LastCluster - W.FirstCluster + 1;
  8352. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  8353. if (Size == 2 && W.MBB == SwitchMBB) {
  8354. // If any two of the cases has the same destination, and if one value
  8355. // is the same as the other, but has one bit unset that the other has set,
  8356. // use bit manipulation to do two compares at once. For example:
  8357. // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
  8358. // TODO: This could be extended to merge any 2 cases in switches with 3
  8359. // cases.
  8360. // TODO: Handle cases where W.CaseBB != SwitchBB.
  8361. CaseCluster &Small = *W.FirstCluster;
  8362. CaseCluster &Big = *W.LastCluster;
  8363. if (Small.Low == Small.High && Big.Low == Big.High &&
  8364. Small.MBB == Big.MBB) {
  8365. const APInt &SmallValue = Small.Low->getValue();
  8366. const APInt &BigValue = Big.Low->getValue();
  8367. // Check that there is only one bit different.
  8368. APInt CommonBit = BigValue ^ SmallValue;
  8369. if (CommonBit.isPowerOf2()) {
  8370. SDValue CondLHS = getValue(Cond);
  8371. EVT VT = CondLHS.getValueType();
  8372. SDLoc DL = getCurSDLoc();
  8373. SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
  8374. DAG.getConstant(CommonBit, DL, VT));
  8375. SDValue Cond = DAG.getSetCC(
  8376. DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
  8377. ISD::SETEQ);
  8378. // Update successor info.
  8379. // Both Small and Big will jump to Small.BB, so we sum up the
  8380. // probabilities.
  8381. addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
  8382. if (BPI)
  8383. addSuccessorWithProb(
  8384. SwitchMBB, DefaultMBB,
  8385. // The default destination is the first successor in IR.
  8386. BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
  8387. else
  8388. addSuccessorWithProb(SwitchMBB, DefaultMBB);
  8389. // Insert the true branch.
  8390. SDValue BrCond =
  8391. DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
  8392. DAG.getBasicBlock(Small.MBB));
  8393. // Insert the false branch.
  8394. BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
  8395. DAG.getBasicBlock(DefaultMBB));
  8396. DAG.setRoot(BrCond);
  8397. return;
  8398. }
  8399. }
  8400. }
  8401. if (TM.getOptLevel() != CodeGenOpt::None) {
  8402. // Here, we order cases by probability so the most likely case will be
  8403. // checked first. However, two clusters can have the same probability in
  8404. // which case their relative ordering is non-deterministic. So we use Low
  8405. // as a tie-breaker as clusters are guaranteed to never overlap.
  8406. std::sort(W.FirstCluster, W.LastCluster + 1,
  8407. [](const CaseCluster &a, const CaseCluster &b) {
  8408. return a.Prob != b.Prob ?
  8409. a.Prob > b.Prob :
  8410. a.Low->getValue().slt(b.Low->getValue());
  8411. });
  8412. // Rearrange the case blocks so that the last one falls through if possible
  8413. // without without changing the order of probabilities.
  8414. for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
  8415. --I;
  8416. if (I->Prob > W.LastCluster->Prob)
  8417. break;
  8418. if (I->Kind == CC_Range && I->MBB == NextMBB) {
  8419. std::swap(*I, *W.LastCluster);
  8420. break;
  8421. }
  8422. }
  8423. }
  8424. // Compute total probability.
  8425. BranchProbability DefaultProb = W.DefaultProb;
  8426. BranchProbability UnhandledProbs = DefaultProb;
  8427. for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
  8428. UnhandledProbs += I->Prob;
  8429. MachineBasicBlock *CurMBB = W.MBB;
  8430. for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
  8431. MachineBasicBlock *Fallthrough;
  8432. if (I == W.LastCluster) {
  8433. // For the last cluster, fall through to the default destination.
  8434. Fallthrough = DefaultMBB;
  8435. } else {
  8436. Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
  8437. CurMF->insert(BBI, Fallthrough);
  8438. // Put Cond in a virtual register to make it available from the new blocks.
  8439. ExportFromCurrentBlock(Cond);
  8440. }
  8441. UnhandledProbs -= I->Prob;
  8442. switch (I->Kind) {
  8443. case CC_JumpTable: {
  8444. // FIXME: Optimize away range check based on pivot comparisons.
  8445. JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
  8446. JumpTable *JT = &JTCases[I->JTCasesIndex].second;
  8447. // The jump block hasn't been inserted yet; insert it here.
  8448. MachineBasicBlock *JumpMBB = JT->MBB;
  8449. CurMF->insert(BBI, JumpMBB);
  8450. auto JumpProb = I->Prob;
  8451. auto FallthroughProb = UnhandledProbs;
  8452. // If the default statement is a target of the jump table, we evenly
  8453. // distribute the default probability to successors of CurMBB. Also
  8454. // update the probability on the edge from JumpMBB to Fallthrough.
  8455. for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
  8456. SE = JumpMBB->succ_end();
  8457. SI != SE; ++SI) {
  8458. if (*SI == DefaultMBB) {
  8459. JumpProb += DefaultProb / 2;
  8460. FallthroughProb -= DefaultProb / 2;
  8461. JumpMBB->setSuccProbability(SI, DefaultProb / 2);
  8462. JumpMBB->normalizeSuccProbs();
  8463. break;
  8464. }
  8465. }
  8466. addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
  8467. addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
  8468. CurMBB->normalizeSuccProbs();
  8469. // The jump table header will be inserted in our current block, do the
  8470. // range check, and fall through to our fallthrough block.
  8471. JTH->HeaderBB = CurMBB;
  8472. JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
  8473. // If we're in the right place, emit the jump table header right now.
  8474. if (CurMBB == SwitchMBB) {
  8475. visitJumpTableHeader(*JT, *JTH, SwitchMBB);
  8476. JTH->Emitted = true;
  8477. }
  8478. break;
  8479. }
  8480. case CC_BitTests: {
  8481. // FIXME: Optimize away range check based on pivot comparisons.
  8482. BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
  8483. // The bit test blocks haven't been inserted yet; insert them here.
  8484. for (BitTestCase &BTC : BTB->Cases)
  8485. CurMF->insert(BBI, BTC.ThisBB);
  8486. // Fill in fields of the BitTestBlock.
  8487. BTB->Parent = CurMBB;
  8488. BTB->Default = Fallthrough;
  8489. BTB->DefaultProb = UnhandledProbs;
  8490. // If the cases in bit test don't form a contiguous range, we evenly
  8491. // distribute the probability on the edge to Fallthrough to two
  8492. // successors of CurMBB.
  8493. if (!BTB->ContiguousRange) {
  8494. BTB->Prob += DefaultProb / 2;
  8495. BTB->DefaultProb -= DefaultProb / 2;
  8496. }
  8497. // If we're in the right place, emit the bit test header right now.
  8498. if (CurMBB == SwitchMBB) {
  8499. visitBitTestHeader(*BTB, SwitchMBB);
  8500. BTB->Emitted = true;
  8501. }
  8502. break;
  8503. }
  8504. case CC_Range: {
  8505. const Value *RHS, *LHS, *MHS;
  8506. ISD::CondCode CC;
  8507. if (I->Low == I->High) {
  8508. // Check Cond == I->Low.
  8509. CC = ISD::SETEQ;
  8510. LHS = Cond;
  8511. RHS=I->Low;
  8512. MHS = nullptr;
  8513. } else {
  8514. // Check I->Low <= Cond <= I->High.
  8515. CC = ISD::SETLE;
  8516. LHS = I->Low;
  8517. MHS = Cond;
  8518. RHS = I->High;
  8519. }
  8520. // The false probability is the sum of all unhandled cases.
  8521. CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
  8522. getCurSDLoc(), I->Prob, UnhandledProbs);
  8523. if (CurMBB == SwitchMBB)
  8524. visitSwitchCase(CB, SwitchMBB);
  8525. else
  8526. SwitchCases.push_back(CB);
  8527. break;
  8528. }
  8529. }
  8530. CurMBB = Fallthrough;
  8531. }
  8532. }
  8533. unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
  8534. CaseClusterIt First,
  8535. CaseClusterIt Last) {
  8536. return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
  8537. if (X.Prob != CC.Prob)
  8538. return X.Prob > CC.Prob;
  8539. // Ties are broken by comparing the case value.
  8540. return X.Low->getValue().slt(CC.Low->getValue());
  8541. });
  8542. }
  8543. void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
  8544. const SwitchWorkListItem &W,
  8545. Value *Cond,
  8546. MachineBasicBlock *SwitchMBB) {
  8547. assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
  8548. "Clusters not sorted?");
  8549. assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
  8550. // Balance the tree based on branch probabilities to create a near-optimal (in
  8551. // terms of search time given key frequency) binary search tree. See e.g. Kurt
  8552. // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
  8553. CaseClusterIt LastLeft = W.FirstCluster;
  8554. CaseClusterIt FirstRight = W.LastCluster;
  8555. auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
  8556. auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
  8557. // Move LastLeft and FirstRight towards each other from opposite directions to
  8558. // find a partitioning of the clusters which balances the probability on both
  8559. // sides. If LeftProb and RightProb are equal, alternate which side is
  8560. // taken to ensure 0-probability nodes are distributed evenly.
  8561. unsigned I = 0;
  8562. while (LastLeft + 1 < FirstRight) {
  8563. if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
  8564. LeftProb += (++LastLeft)->Prob;
  8565. else
  8566. RightProb += (--FirstRight)->Prob;
  8567. I++;
  8568. }
  8569. while (true) {
  8570. // Our binary search tree differs from a typical BST in that ours can have up
  8571. // to three values in each leaf. The pivot selection above doesn't take that
  8572. // into account, which means the tree might require more nodes and be less
  8573. // efficient. We compensate for this here.
  8574. unsigned NumLeft = LastLeft - W.FirstCluster + 1;
  8575. unsigned NumRight = W.LastCluster - FirstRight + 1;
  8576. if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
  8577. // If one side has less than 3 clusters, and the other has more than 3,
  8578. // consider taking a cluster from the other side.
  8579. if (NumLeft < NumRight) {
  8580. // Consider moving the first cluster on the right to the left side.
  8581. CaseCluster &CC = *FirstRight;
  8582. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  8583. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  8584. if (LeftSideRank <= RightSideRank) {
  8585. // Moving the cluster to the left does not demote it.
  8586. ++LastLeft;
  8587. ++FirstRight;
  8588. continue;
  8589. }
  8590. } else {
  8591. assert(NumRight < NumLeft);
  8592. // Consider moving the last element on the left to the right side.
  8593. CaseCluster &CC = *LastLeft;
  8594. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  8595. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  8596. if (RightSideRank <= LeftSideRank) {
  8597. // Moving the cluster to the right does not demot it.
  8598. --LastLeft;
  8599. --FirstRight;
  8600. continue;
  8601. }
  8602. }
  8603. }
  8604. break;
  8605. }
  8606. assert(LastLeft + 1 == FirstRight);
  8607. assert(LastLeft >= W.FirstCluster);
  8608. assert(FirstRight <= W.LastCluster);
  8609. // Use the first element on the right as pivot since we will make less-than
  8610. // comparisons against it.
  8611. CaseClusterIt PivotCluster = FirstRight;
  8612. assert(PivotCluster > W.FirstCluster);
  8613. assert(PivotCluster <= W.LastCluster);
  8614. CaseClusterIt FirstLeft = W.FirstCluster;
  8615. CaseClusterIt LastRight = W.LastCluster;
  8616. const ConstantInt *Pivot = PivotCluster->Low;
  8617. // New blocks will be inserted immediately after the current one.
  8618. MachineFunction::iterator BBI(W.MBB);
  8619. ++BBI;
  8620. // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
  8621. // we can branch to its destination directly if it's squeezed exactly in
  8622. // between the known lower bound and Pivot - 1.
  8623. MachineBasicBlock *LeftMBB;
  8624. if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
  8625. FirstLeft->Low == W.GE &&
  8626. (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
  8627. LeftMBB = FirstLeft->MBB;
  8628. } else {
  8629. LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  8630. FuncInfo.MF->insert(BBI, LeftMBB);
  8631. WorkList.push_back(
  8632. {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
  8633. // Put Cond in a virtual register to make it available from the new blocks.
  8634. ExportFromCurrentBlock(Cond);
  8635. }
  8636. // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
  8637. // single cluster, RHS.Low == Pivot, and we can branch to its destination
  8638. // directly if RHS.High equals the current upper bound.
  8639. MachineBasicBlock *RightMBB;
  8640. if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
  8641. W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
  8642. RightMBB = FirstRight->MBB;
  8643. } else {
  8644. RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  8645. FuncInfo.MF->insert(BBI, RightMBB);
  8646. WorkList.push_back(
  8647. {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
  8648. // Put Cond in a virtual register to make it available from the new blocks.
  8649. ExportFromCurrentBlock(Cond);
  8650. }
  8651. // Create the CaseBlock record that will be used to lower the branch.
  8652. CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
  8653. getCurSDLoc(), LeftProb, RightProb);
  8654. if (W.MBB == SwitchMBB)
  8655. visitSwitchCase(CB, SwitchMBB);
  8656. else
  8657. SwitchCases.push_back(CB);
  8658. }
  8659. // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
  8660. // from the swith statement.
  8661. static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
  8662. BranchProbability PeeledCaseProb) {
  8663. if (PeeledCaseProb == BranchProbability::getOne())
  8664. return BranchProbability::getZero();
  8665. BranchProbability SwitchProb = PeeledCaseProb.getCompl();
  8666. uint32_t Numerator = CaseProb.getNumerator();
  8667. uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
  8668. return BranchProbability(Numerator, std::max(Numerator, Denominator));
  8669. }
  8670. // Try to peel the top probability case if it exceeds the threshold.
  8671. // Return current MachineBasicBlock for the switch statement if the peeling
  8672. // does not occur.
  8673. // If the peeling is performed, return the newly created MachineBasicBlock
  8674. // for the peeled switch statement. Also update Clusters to remove the peeled
  8675. // case. PeeledCaseProb is the BranchProbability for the peeled case.
  8676. MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
  8677. const SwitchInst &SI, CaseClusterVector &Clusters,
  8678. BranchProbability &PeeledCaseProb) {
  8679. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  8680. // Don't perform if there is only one cluster or optimizing for size.
  8681. if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
  8682. TM.getOptLevel() == CodeGenOpt::None ||
  8683. SwitchMBB->getParent()->getFunction().optForMinSize())
  8684. return SwitchMBB;
  8685. BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
  8686. unsigned PeeledCaseIndex = 0;
  8687. bool SwitchPeeled = false;
  8688. for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
  8689. CaseCluster &CC = Clusters[Index];
  8690. if (CC.Prob < TopCaseProb)
  8691. continue;
  8692. TopCaseProb = CC.Prob;
  8693. PeeledCaseIndex = Index;
  8694. SwitchPeeled = true;
  8695. }
  8696. if (!SwitchPeeled)
  8697. return SwitchMBB;
  8698. DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " << TopCaseProb
  8699. << "\n");
  8700. // Record the MBB for the peeled switch statement.
  8701. MachineFunction::iterator BBI(SwitchMBB);
  8702. ++BBI;
  8703. MachineBasicBlock *PeeledSwitchMBB =
  8704. FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
  8705. FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
  8706. ExportFromCurrentBlock(SI.getCondition());
  8707. auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
  8708. SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
  8709. nullptr, nullptr, TopCaseProb.getCompl()};
  8710. lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
  8711. Clusters.erase(PeeledCaseIt);
  8712. for (CaseCluster &CC : Clusters) {
  8713. DEBUG(dbgs() << "Scale the probablity for one cluster, before scaling: "
  8714. << CC.Prob << "\n");
  8715. CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
  8716. DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
  8717. }
  8718. PeeledCaseProb = TopCaseProb;
  8719. return PeeledSwitchMBB;
  8720. }
  8721. void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
  8722. // Extract cases from the switch.
  8723. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  8724. CaseClusterVector Clusters;
  8725. Clusters.reserve(SI.getNumCases());
  8726. for (auto I : SI.cases()) {
  8727. MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
  8728. const ConstantInt *CaseVal = I.getCaseValue();
  8729. BranchProbability Prob =
  8730. BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
  8731. : BranchProbability(1, SI.getNumCases() + 1);
  8732. Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
  8733. }
  8734. MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
  8735. // Cluster adjacent cases with the same destination. We do this at all
  8736. // optimization levels because it's cheap to do and will make codegen faster
  8737. // if there are many clusters.
  8738. sortAndRangeify(Clusters);
  8739. if (TM.getOptLevel() != CodeGenOpt::None) {
  8740. // Replace an unreachable default with the most popular destination.
  8741. // FIXME: Exploit unreachable default more aggressively.
  8742. bool UnreachableDefault =
  8743. isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg());
  8744. if (UnreachableDefault && !Clusters.empty()) {
  8745. DenseMap<const BasicBlock *, unsigned> Popularity;
  8746. unsigned MaxPop = 0;
  8747. const BasicBlock *MaxBB = nullptr;
  8748. for (auto I : SI.cases()) {
  8749. const BasicBlock *BB = I.getCaseSuccessor();
  8750. if (++Popularity[BB] > MaxPop) {
  8751. MaxPop = Popularity[BB];
  8752. MaxBB = BB;
  8753. }
  8754. }
  8755. // Set new default.
  8756. assert(MaxPop > 0 && MaxBB);
  8757. DefaultMBB = FuncInfo.MBBMap[MaxBB];
  8758. // Remove cases that were pointing to the destination that is now the
  8759. // default.
  8760. CaseClusterVector New;
  8761. New.reserve(Clusters.size());
  8762. for (CaseCluster &CC : Clusters) {
  8763. if (CC.MBB != DefaultMBB)
  8764. New.push_back(CC);
  8765. }
  8766. Clusters = std::move(New);
  8767. }
  8768. }
  8769. // The branch probablity of the peeled case.
  8770. BranchProbability PeeledCaseProb = BranchProbability::getZero();
  8771. MachineBasicBlock *PeeledSwitchMBB =
  8772. peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
  8773. // If there is only the default destination, jump there directly.
  8774. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  8775. if (Clusters.empty()) {
  8776. assert(PeeledSwitchMBB == SwitchMBB);
  8777. SwitchMBB->addSuccessor(DefaultMBB);
  8778. if (DefaultMBB != NextBlock(SwitchMBB)) {
  8779. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  8780. getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
  8781. }
  8782. return;
  8783. }
  8784. findJumpTables(Clusters, &SI, DefaultMBB);
  8785. findBitTestClusters(Clusters, &SI);
  8786. DEBUG({
  8787. dbgs() << "Case clusters: ";
  8788. for (const CaseCluster &C : Clusters) {
  8789. if (C.Kind == CC_JumpTable) dbgs() << "JT:";
  8790. if (C.Kind == CC_BitTests) dbgs() << "BT:";
  8791. C.Low->getValue().print(dbgs(), true);
  8792. if (C.Low != C.High) {
  8793. dbgs() << '-';
  8794. C.High->getValue().print(dbgs(), true);
  8795. }
  8796. dbgs() << ' ';
  8797. }
  8798. dbgs() << '\n';
  8799. });
  8800. assert(!Clusters.empty());
  8801. SwitchWorkList WorkList;
  8802. CaseClusterIt First = Clusters.begin();
  8803. CaseClusterIt Last = Clusters.end() - 1;
  8804. auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
  8805. // Scale the branchprobability for DefaultMBB if the peel occurs and
  8806. // DefaultMBB is not replaced.
  8807. if (PeeledCaseProb != BranchProbability::getZero() &&
  8808. DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
  8809. DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
  8810. WorkList.push_back(
  8811. {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
  8812. while (!WorkList.empty()) {
  8813. SwitchWorkListItem W = WorkList.back();
  8814. WorkList.pop_back();
  8815. unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
  8816. if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
  8817. !DefaultMBB->getParent()->getFunction().optForMinSize()) {
  8818. // For optimized builds, lower large range as a balanced binary tree.
  8819. splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
  8820. continue;
  8821. }
  8822. lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
  8823. }
  8824. }